1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/ParentMapContext.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticSema.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/LiteralSupport.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/DelayedDiagnostic.h"
43#include "clang/Sema/Designator.h"
44#include "clang/Sema/EnterExpressionEvaluationContext.h"
45#include "clang/Sema/Initialization.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Overload.h"
48#include "clang/Sema/ParsedTemplate.h"
49#include "clang/Sema/Scope.h"
50#include "clang/Sema/ScopeInfo.h"
51#include "clang/Sema/SemaFixItUtils.h"
52#include "clang/Sema/SemaInternal.h"
53#include "clang/Sema/Template.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/Casting.h"
57#include "llvm/Support/ConvertUTF.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include "llvm/Support/TypeSize.h"
60#include <optional>
61
62using namespace clang;
63using namespace sema;
64
65/// Determine whether the use of this declaration is valid, without
66/// emitting diagnostics.
67bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
68 // See if this is an auto-typed variable whose initializer we are parsing.
69 if (ParsingInitForAutoVars.count(D))
70 return false;
71
72 // See if this is a deleted function.
73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->isDeleted())
75 return false;
76
77 // If the function has a deduced return type, and we can't deduce it,
78 // then we can't use it either.
79 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
80 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
81 return false;
82
83 // See if this is an aligned allocation/deallocation function that is
84 // unavailable.
85 if (TreatUnavailableAsInvalid &&
86 isUnavailableAlignedAllocationFunction(*FD))
87 return false;
88 }
89
90 // See if this function is unavailable.
91 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
92 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
93 return false;
94
95 if (isa<UnresolvedUsingIfExistsDecl>(D))
96 return false;
97
98 return true;
99}
100
101static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
102 // Warn if this is used but marked unused.
103 if (const auto *A = D->getAttr<UnusedAttr>()) {
104 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
105 // should diagnose them.
106 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
107 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
108 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
109 if (DC && !DC->hasAttr<UnusedAttr>())
110 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
111 }
112 }
113}
114
115/// Emit a note explaining that this function is deleted.
116void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
117 assert(Decl && Decl->isDeleted());
118
119 if (Decl->isDefaulted()) {
120 // If the method was explicitly defaulted, point at that declaration.
121 if (!Decl->isImplicit())
122 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
123
124 // Try to diagnose why this special member function was implicitly
125 // deleted. This might fail, if that reason no longer applies.
126 DiagnoseDeletedDefaultedFunction(Decl);
127 return;
128 }
129
130 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
131 if (Ctor && Ctor->isInheritingConstructor())
132 return NoteDeletedInheritingConstructor(Ctor);
133
134 Diag(Decl->getLocation(), diag::note_availability_specified_here)
135 << Decl << 1;
136}
137
138/// Determine whether a FunctionDecl was ever declared with an
139/// explicit storage class.
140static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
141 for (auto *I : D->redecls()) {
142 if (I->getStorageClass() != SC_None)
143 return true;
144 }
145 return false;
146}
147
148/// Check whether we're in an extern inline function and referring to a
149/// variable or function with internal linkage (C11 6.7.4p3).
150///
151/// This is only a warning because we used to silently accept this code, but
152/// in many cases it will not behave correctly. This is not enabled in C++ mode
153/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
154/// and so while there may still be user mistakes, most of the time we can't
155/// prove that there are errors.
156static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
157 const NamedDecl *D,
158 SourceLocation Loc) {
159 // This is disabled under C++; there are too many ways for this to fire in
160 // contexts where the warning is a false positive, or where it is technically
161 // correct but benign.
162 if (S.getLangOpts().CPlusPlus)
163 return;
164
165 // Check if this is an inlined function or method.
166 FunctionDecl *Current = S.getCurFunctionDecl();
167 if (!Current)
168 return;
169 if (!Current->isInlined())
170 return;
171 if (!Current->isExternallyVisible())
172 return;
173
174 // Check if the decl has internal linkage.
175 if (D->getFormalLinkage() != InternalLinkage)
176 return;
177
178 // Downgrade from ExtWarn to Extension if
179 // (1) the supposedly external inline function is in the main file,
180 // and probably won't be included anywhere else.
181 // (2) the thing we're referencing is a pure function.
182 // (3) the thing we're referencing is another inline function.
183 // This last can give us false negatives, but it's better than warning on
184 // wrappers for simple C library functions.
185 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
186 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
187 if (!DowngradeWarning && UsedFn)
188 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
189
190 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
191 : diag::ext_internal_in_extern_inline)
192 << /*IsVar=*/!UsedFn << D;
193
194 S.MaybeSuggestAddingStaticToDecl(Current);
195
196 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
197 << D;
198}
199
200void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
201 const FunctionDecl *First = Cur->getFirstDecl();
202
203 // Suggest "static" on the function, if possible.
204 if (!hasAnyExplicitStorageClass(First)) {
205 SourceLocation DeclBegin = First->getSourceRange().getBegin();
206 Diag(DeclBegin, diag::note_convert_inline_to_static)
207 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
208 }
209}
210
211/// Determine whether the use of this declaration is valid, and
212/// emit any corresponding diagnostics.
213///
214/// This routine diagnoses various problems with referencing
215/// declarations that can occur when using a declaration. For example,
216/// it might warn if a deprecated or unavailable declaration is being
217/// used, or produce an error (and return true) if a C++0x deleted
218/// function is being used.
219///
220/// \returns true if there was an error (this declaration cannot be
221/// referenced), false otherwise.
222///
223bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
224 const ObjCInterfaceDecl *UnknownObjCClass,
225 bool ObjCPropertyAccess,
226 bool AvoidPartialAvailabilityChecks,
227 ObjCInterfaceDecl *ClassReceiver,
228 bool SkipTrailingRequiresClause) {
229 SourceLocation Loc = Locs.front();
230 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
231 // If there were any diagnostics suppressed by template argument deduction,
232 // emit them now.
233 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
234 if (Pos != SuppressedDiagnostics.end()) {
235 for (const PartialDiagnosticAt &Suppressed : Pos->second)
236 Diag(Suppressed.first, Suppressed.second);
237
238 // Clear out the list of suppressed diagnostics, so that we don't emit
239 // them again for this specialization. However, we don't obsolete this
240 // entry from the table, because we want to avoid ever emitting these
241 // diagnostics again.
242 Pos->second.clear();
243 }
244
245 // C++ [basic.start.main]p3:
246 // The function 'main' shall not be used within a program.
247 if (cast<FunctionDecl>(D)->isMain())
248 Diag(Loc, diag::ext_main_used);
249
250 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
251 }
252
253 // See if this is an auto-typed variable whose initializer we are parsing.
254 if (ParsingInitForAutoVars.count(D)) {
255 if (isa<BindingDecl>(D)) {
256 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
257 << D->getDeclName();
258 } else {
259 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
260 << D->getDeclName() << cast<VarDecl>(D)->getType();
261 }
262 return true;
263 }
264
265 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // See if this is a deleted function.
267 if (FD->isDeleted()) {
268 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
269 if (Ctor && Ctor->isInheritingConstructor())
270 Diag(Loc, diag::err_deleted_inherited_ctor_use)
271 << Ctor->getParent()
272 << Ctor->getInheritedConstructor().getConstructor()->getParent();
273 else
274 Diag(Loc, diag::err_deleted_function_use);
275 NoteDeletedFunction(FD);
276 return true;
277 }
278
279 // [expr.prim.id]p4
280 // A program that refers explicitly or implicitly to a function with a
281 // trailing requires-clause whose constraint-expression is not satisfied,
282 // other than to declare it, is ill-formed. [...]
283 //
284 // See if this is a function with constraints that need to be satisfied.
285 // Check this before deducing the return type, as it might instantiate the
286 // definition.
287 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
288 ConstraintSatisfaction Satisfaction;
289 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
290 /*ForOverloadResolution*/ true))
291 // A diagnostic will have already been generated (non-constant
292 // constraint expression, for example)
293 return true;
294 if (!Satisfaction.IsSatisfied) {
295 Diag(Loc,
296 diag::err_reference_to_function_with_unsatisfied_constraints)
297 << D;
298 DiagnoseUnsatisfiedConstraint(Satisfaction);
299 return true;
300 }
301 }
302
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
306 DeduceReturnType(FD, Loc))
307 return true;
308
309 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
310 return true;
311
312 }
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
332 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
333 return true;
334 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
346 << getCurFunction()->HasOMPDeclareReductionCombiner;
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
359 << getOpenMPDeclareMapperVarName();
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
375 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
376
377 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
378 if (getLangOpts().getFPEvalMethod() !=
379 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
380 PP.getLastFPEvalPragmaLocation().isValid() &&
381 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D->getLocation(),
383 diag::err_type_available_only_in_default_eval_method)
384 << D->getName();
385 }
386
387 if (auto *VD = dyn_cast<ValueDecl>(D))
388 checkTypeSupport(VD->getType(), Loc, VD);
389
390 if (LangOpts.SYCLIsDevice ||
391 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
392 if (!Context.getTargetInfo().isTLSSupported())
393 if (const auto *VD = dyn_cast<VarDecl>(D))
394 if (VD->getTLSKind() != VarDecl::TLS_None)
395 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
396 }
397
398 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
399 !isUnevaluatedContext()) {
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
404 << D;
405 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
406 return true;
407 }
408
409 return false;
410}
411
412/// DiagnoseSentinelCalls - This routine checks whether a call or
413/// message-send is to a declaration with the sentinel attribute, and
414/// if so, it checks that the requirements of the sentinel are
415/// satisfied.
416void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
417 ArrayRef<Expr *> Args) {
418 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
419 if (!attr)
420 return;
421
422 // The number of formal parameters of the declaration.
423 unsigned numFormalParams;
424
425 // The kind of declaration. This is also an index into a %select in
426 // the diagnostic.
427 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
428
429 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
430 numFormalParams = MD->param_size();
431 calleeType = CT_Method;
432 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433 numFormalParams = FD->param_size();
434 calleeType = CT_Function;
435 } else if (isa<VarDecl>(D)) {
436 QualType type = cast<ValueDecl>(D)->getType();
437 const FunctionType *fn = nullptr;
438 if (const PointerType *ptr = type->getAs<PointerType>()) {
439 fn = ptr->getPointeeType()->getAs<FunctionType>();
440 if (!fn) return;
441 calleeType = CT_Function;
442 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
443 fn = ptr->getPointeeType()->castAs<FunctionType>();
444 calleeType = CT_Block;
445 } else {
446 return;
447 }
448
449 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
450 numFormalParams = proto->getNumParams();
451 } else {
452 numFormalParams = 0;
453 }
454 } else {
455 return;
456 }
457
458 // "nullPos" is the number of formal parameters at the end which
459 // effectively count as part of the variadic arguments. This is
460 // useful if you would prefer to not have *any* formal parameters,
461 // but the language forces you to have at least one.
462 unsigned nullPos = attr->getNullPos();
463 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
464 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
465
466 // The number of arguments which should follow the sentinel.
467 unsigned numArgsAfterSentinel = attr->getSentinel();
468
469 // If there aren't enough arguments for all the formal parameters,
470 // the sentinel, and the args after the sentinel, complain.
471 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
474 return;
475 }
476
477 // Otherwise, find the sentinel expression.
478 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
479 if (!sentinelExpr) return;
480 if (sentinelExpr->isValueDependent()) return;
481 if (Context.isSentinelNullExpr(sentinelExpr)) return;
482
483 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
484 // or 'NULL' if those are actually defined in the context. Only use
485 // 'nil' for ObjC methods, where it's much more likely that the
486 // variadic arguments form a list of object pointers.
487 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
488 std::string NullValue;
489 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
490 NullValue = "nil";
491 else if (getLangOpts().CPlusPlus11)
492 NullValue = "nullptr";
493 else if (PP.isMacroDefined("NULL"))
494 NullValue = "NULL";
495 else
496 NullValue = "(void*) 0";
497
498 if (MissingNilLoc.isInvalid())
499 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
500 else
501 Diag(MissingNilLoc, diag::warn_missing_sentinel)
502 << int(calleeType)
503 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
504 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
505}
506
507SourceRange Sema::getExprRange(Expr *E) const {
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
516ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
519 ExprResult result = CheckPlaceholderExpr(E);
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
530 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
531 return ExprError();
532
533 E = ImpCastExprToType(E, Context.getPointerType(Ty),
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
548 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
558static void CheckForNullPointerDereference(Sema &S, Expr *E) {
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
572 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
591 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
592 if (!Member || !Member->isStr("isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
607 S.LookupSingleName(S.TUScope,
608 &S.Context.Idents.get("object_setClass"),
609 SourceLocation(), S.LookupOrdinaryName);
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
613 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
614 "object_setClass(")
615 << FixItHint::CreateReplacement(
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
618 }
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
623 S.LookupSingleName(S.TUScope,
624 &S.Context.Idents.get("object_getClass"),
625 SourceLocation(), S.LookupOrdinaryName);
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
628 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
629 "object_getClass(")
630 << FixItHint::CreateReplacement(
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
634 }
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
636 }
637 }
638}
639
640ExprResult Sema::DefaultLvalueConversion(Expr *E) {
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
643 ExprResult result = CheckPlaceholderExpr(E);
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to function or array types.
657 if (T->isFunctionType() || T->isArrayType())
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 (E->getType() == Context.OverloadTy ||
664 T->isDependentType() ||
665 T->isRecordType()))
666 return E;
667
668 // The C standard is actually really unclear on this point, and
669 // DR106 tells us what the result should be but not why. It's
670 // generally best to say that void types just doesn't undergo
671 // lvalue-to-rvalue at all. Note that expressions of unqualified
672 // 'void' type are never l-values, but qualified void can be.
673 if (T->isVoidType())
674 return E;
675
676 // OpenCL usually rejects direct accesses to values of 'half' type.
677 if (getLangOpts().OpenCL &&
678 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
679 T->isHalfType()) {
680 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
681 << 0 << T;
682 return ExprError();
683 }
684
685 CheckForNullPointerDereference(*this, E);
686 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
687 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
688 &Context.Idents.get("object_getClass"),
689 SourceLocation(), LookupOrdinaryName);
690 if (ObjectGetClass)
691 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
692 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
693 << FixItHint::CreateReplacement(
694 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
695 else
696 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
697 }
698 else if (const ObjCIvarRefExpr *OIRE =
699 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
700 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
701
702 // C++ [conv.lval]p1:
703 // [...] If T is a non-class type, the type of the prvalue is the
704 // cv-unqualified version of T. Otherwise, the type of the
705 // rvalue is T.
706 //
707 // C99 6.3.2.1p2:
708 // If the lvalue has qualified type, the value has the unqualified
709 // version of the type of the lvalue; otherwise, the value has the
710 // type of the lvalue.
711 if (T.hasQualifiers())
712 T = T.getUnqualifiedType();
713
714 // Under the MS ABI, lock down the inheritance model now.
715 if (T->isMemberPointerType() &&
716 Context.getTargetInfo().getCXXABI().isMicrosoft())
717 (void)isCompleteType(E->getExprLoc(), T);
718
719 ExprResult Res = CheckLValueToRValueConversionOperand(E);
720 if (Res.isInvalid())
721 return Res;
722 E = Res.get();
723
724 // Loading a __weak object implicitly retains the value, so we need a cleanup to
725 // balance that.
726 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
727 Cleanup.setExprNeedsCleanups(true);
728
729 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
730 Cleanup.setExprNeedsCleanups(true);
731
732 // C++ [conv.lval]p3:
733 // If T is cv std::nullptr_t, the result is a null pointer constant.
734 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
735 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
736 CurFPFeatureOverrides());
737
738 // C11 6.3.2.1p2:
739 // ... if the lvalue has atomic type, the value has the non-atomic version
740 // of the type of the lvalue ...
741 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
742 T = Atomic->getValueType().getUnqualifiedType();
743 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
744 nullptr, VK_PRValue, FPOptionsOverride());
745 }
746
747 return Res;
748}
749
750ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
751 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
752 if (Res.isInvalid())
753 return ExprError();
754 Res = DefaultLvalueConversion(Res.get());
755 if (Res.isInvalid())
756 return ExprError();
757 return Res;
758}
759
760/// CallExprUnaryConversions - a special case of an unary conversion
761/// performed on a function designator of a call expression.
762ExprResult Sema::CallExprUnaryConversions(Expr *E) {
763 QualType Ty = E->getType();
764 ExprResult Res = E;
765 // Only do implicit cast for a function type, but not for a pointer
766 // to function type.
767 if (Ty->isFunctionType()) {
768 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
769 CK_FunctionToPointerDecay);
770 if (Res.isInvalid())
771 return ExprError();
772 }
773 Res = DefaultLvalueConversion(Res.get());
774 if (Res.isInvalid())
775 return ExprError();
776 return Res.get();
777}
778
779/// UsualUnaryConversions - Performs various conversions that are common to most
780/// operators (C99 6.3). The conversions of array and function types are
781/// sometimes suppressed. For example, the array->pointer conversion doesn't
782/// apply if the array is an argument to the sizeof or address (&) operators.
783/// In these instances, this routine should *not* be called.
784ExprResult Sema::UsualUnaryConversions(Expr *E) {
785 // First, convert to an r-value.
786 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
787 if (Res.isInvalid())
788 return ExprError();
789 E = Res.get();
790
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
797 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
798 PP.getLastFPEvalPragmaLocation().isValid())) {
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
803 case LangOptions::FEM_UnsetOnCommandLine:
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
806 case LangOptions::FEM_Double:
807 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
808 // Widen the expression to double.
809 return Ty->isComplexType()
810 ? ImpCastExprToType(E,
811 Context.getComplexType(Context.DoubleTy),
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
815 case LangOptions::FEM_Extended:
816 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
817 // Widen the expression to long double.
818 return Ty->isComplexType()
819 ? ImpCastExprToType(
820 E, Context.getComplexType(Context.LongDoubleTy),
821 CK_FloatingComplexCast)
822 : ImpCastExprToType(E, Context.LongDoubleTy,
823 CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
831
832 // Try to perform integral promotions if the object has a theoretically
833 // promotable type.
834 if (Ty->isIntegralOrUnscopedEnumerationType()) {
835 // C99 6.3.1.1p2:
836 //
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
841 // and unsigned int.
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
843 //
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
848
849 QualType PTy = Context.isPromotableBitField(E);
850 if (!PTy.isNull()) {
851 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
852 return E;
853 }
854 if (Context.isPromotableIntegerType(Ty)) {
855 QualType PT = Context.getPromotedIntegerType(Ty);
856 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
857 return E;
858 }
859 }
860 return E;
861}
862
863/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864/// do not have a prototype. Arguments that have type float or __fp16
865/// are promoted to double. All other argument types are converted by
866/// UsualUnaryConversions().
867ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
868 QualType Ty = E->getType();
869 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
870
871 ExprResult Res = UsualUnaryConversions(E);
872 if (Res.isInvalid())
873 return ExprError();
874 E = Res.get();
875
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
881 if (BTy && (BTy->getKind() == BuiltinType::Half ||
882 BTy->getKind() == BuiltinType::Float)) {
883 if (getLangOpts().OpenCL &&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy->getKind() == BuiltinType::Half) {
886 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
887 }
888 } else {
889 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
890 }
891 }
892 if (BTy &&
893 getLangOpts().getExtendIntArgs() ==
894 LangOptions::ExtendArgsKind::ExtendTo64 &&
895 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
896 Context.getTypeSizeInChars(BTy) <
897 Context.getTypeSizeInChars(Context.LongLongTy)) {
898 E = (Ty->isUnsignedIntegerType())
899 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
900 .get()
901 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
902 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
903 "Unexpected typesize for LongLongTy");
904 }
905
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
917 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
918 ExprResult Temp = PerformCopyInitialization(
919 InitializedEntity::InitializeTemporary(E->getType()),
920 E->getExprLoc(), E);
921 if (Temp.isInvalid())
922 return ExprError();
923 E = Temp.get();
924 }
925
926 return E;
927}
928
929/// Determine the degree of POD-ness for an expression.
930/// Incomplete types are considered POD, since this check can be performed
931/// when we're in an unevaluated context.
932Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
933 if (Ty->isIncompleteType()) {
934 // C++11 [expr.call]p7:
935 // After these conversions, if the argument does not have arithmetic,
936 // enumeration, pointer, pointer to member, or class type, the program
937 // is ill-formed.
938 //
939 // Since we've already performed array-to-pointer and function-to-pointer
940 // decay, the only such type in C++ is cv void. This also handles
941 // initializer lists as variadic arguments.
942 if (Ty->isVoidType())
943 return VAK_Invalid;
944
945 if (Ty->isObjCObjectType())
946 return VAK_Invalid;
947 return VAK_Valid;
948 }
949
950 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
951 return VAK_Invalid;
952
953 if (Context.getTargetInfo().getTriple().isWasm() &&
954 Ty.isWebAssemblyReferenceType()) {
955 return VAK_Invalid;
956 }
957
958 if (Ty.isCXX98PODType(Context))
959 return VAK_Valid;
960
961 // C++11 [expr.call]p7:
962 // Passing a potentially-evaluated argument of class type (Clause 9)
963 // having a non-trivial copy constructor, a non-trivial move constructor,
964 // or a non-trivial destructor, with no corresponding parameter,
965 // is conditionally-supported with implementation-defined semantics.
966 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
967 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
968 if (!Record->hasNonTrivialCopyConstructor() &&
969 !Record->hasNonTrivialMoveConstructor() &&
970 !Record->hasNonTrivialDestructor())
971 return VAK_ValidInCXX11;
972
973 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
974 return VAK_Valid;
975
976 if (Ty->isObjCObjectType())
977 return VAK_Invalid;
978
979 if (getLangOpts().MSVCCompat)
980 return VAK_MSVCUndefined;
981
982 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
983 // permitted to reject them. We should consider doing so.
984 return VAK_Undefined;
985}
986
987void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
988 // Don't allow one to pass an Objective-C interface to a vararg.
989 const QualType &Ty = E->getType();
990 VarArgKind VAK = isValidVarArgType(Ty);
991
992 // Complain about passing non-POD types through varargs.
993 switch (VAK) {
994 case VAK_ValidInCXX11:
995 DiagRuntimeBehavior(
996 E->getBeginLoc(), nullptr,
997 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
998 [[fallthrough]];
999 case VAK_Valid:
1000 if (Ty->isRecordType()) {
1001 // This is unlikely to be what the user intended. If the class has a
1002 // 'c_str' member function, the user probably meant to call that.
1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004 PDiag(diag::warn_pass_class_arg_to_vararg)
1005 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1006 }
1007 break;
1008
1009 case VAK_Undefined:
1010 case VAK_MSVCUndefined:
1011 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1012 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1013 << getLangOpts().CPlusPlus11 << Ty << CT);
1014 break;
1015
1016 case VAK_Invalid:
1017 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1018 Diag(E->getBeginLoc(),
1019 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1020 << Ty << CT;
1021 else if (Ty->isObjCObjectType())
1022 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1023 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1024 << Ty << CT);
1025 else
1026 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1027 << isa<InitListExpr>(E) << Ty << CT;
1028 break;
1029 }
1030}
1031
1032/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1033/// will create a trap if the resulting type is not a POD type.
1034ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1035 FunctionDecl *FDecl) {
1036 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1037 // Strip the unbridged-cast placeholder expression off, if applicable.
1038 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1039 (CT == VariadicMethod ||
1040 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1041 E = stripARCUnbridgedCast(E);
1042
1043 // Otherwise, do normal placeholder checking.
1044 } else {
1045 ExprResult ExprRes = CheckPlaceholderExpr(E);
1046 if (ExprRes.isInvalid())
1047 return ExprError();
1048 E = ExprRes.get();
1049 }
1050 }
1051
1052 ExprResult ExprRes = DefaultArgumentPromotion(E);
1053 if (ExprRes.isInvalid())
1054 return ExprError();
1055
1056 // Copy blocks to the heap.
1057 if (ExprRes.get()->getType()->isBlockPointerType())
1058 maybeExtendBlockObject(ExprRes);
1059
1060 E = ExprRes.get();
1061
1062 // Diagnostics regarding non-POD argument types are
1063 // emitted along with format string checking in Sema::CheckFunctionCall().
1064 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1065 // Turn this into a trap.
1066 CXXScopeSpec SS;
1067 SourceLocation TemplateKWLoc;
1068 UnqualifiedId Name;
1069 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1070 E->getBeginLoc());
1071 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1072 /*HasTrailingLParen=*/true,
1073 /*IsAddressOfOperand=*/false);
1074 if (TrapFn.isInvalid())
1075 return ExprError();
1076
1077 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1078 std::nullopt, E->getEndLoc());
1079 if (Call.isInvalid())
1080 return ExprError();
1081
1082 ExprResult Comma =
1083 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1084 if (Comma.isInvalid())
1085 return ExprError();
1086 return Comma.get();
1087 }
1088
1089 if (!getLangOpts().CPlusPlus &&
1090 RequireCompleteType(E->getExprLoc(), E->getType(),
1091 diag::err_call_incomplete_argument))
1092 return ExprError();
1093
1094 return E;
1095}
1096
1097/// Converts an integer to complex float type. Helper function of
1098/// UsualArithmeticConversions()
1099///
1100/// \return false if the integer expression is an integer type and is
1101/// successfully converted to the complex type.
1102static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1103 ExprResult &ComplexExpr,
1104 QualType IntTy,
1105 QualType ComplexTy,
1106 bool SkipCast) {
1107 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1108 if (SkipCast) return false;
1109 if (IntTy->isIntegerType()) {
1110 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1111 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1112 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1113 CK_FloatingRealToComplex);
1114 } else {
1115 assert(IntTy->isComplexIntegerType());
1116 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1117 CK_IntegralComplexToFloatingComplex);
1118 }
1119 return false;
1120}
1121
1122// This handles complex/complex, complex/float, or float/complex.
1123// When both operands are complex, the shorter operand is converted to the
1124// type of the longer, and that is the type of the result. This corresponds
1125// to what is done when combining two real floating-point operands.
1126// The fun begins when size promotion occur across type domains.
1127// From H&S 6.3.4: When one operand is complex and the other is a real
1128// floating-point type, the less precise type is converted, within it's
1129// real or complex domain, to the precision of the other type. For example,
1130// when combining a "long double" with a "double _Complex", the
1131// "double _Complex" is promoted to "long double _Complex".
1132static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1133 QualType ShorterType,
1134 QualType LongerType,
1135 bool PromotePrecision) {
1136 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1137 QualType Result =
1138 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1139
1140 if (PromotePrecision) {
1141 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1142 Shorter =
1143 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1144 } else {
1145 if (LongerIsComplex)
1146 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1147 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1148 }
1149 }
1150 return Result;
1151}
1152
1153/// Handle arithmetic conversion with complex types. Helper function of
1154/// UsualArithmeticConversions()
1155static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1156 ExprResult &RHS, QualType LHSType,
1157 QualType RHSType, bool IsCompAssign) {
1158 // if we have an integer operand, the result is the complex type.
1159 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1160 /*SkipCast=*/false))
1161 return LHSType;
1162 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1163 /*SkipCast=*/IsCompAssign))
1164 return RHSType;
1165
1166 // Compute the rank of the two types, regardless of whether they are complex.
1167 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1168 if (Order < 0)
1169 // Promote the precision of the LHS if not an assignment.
1170 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1171 /*PromotePrecision=*/!IsCompAssign);
1172 // Promote the precision of the RHS unless it is already the same as the LHS.
1173 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1174 /*PromotePrecision=*/Order > 0);
1175}
1176
1177/// Handle arithmetic conversion from integer to float. Helper function
1178/// of UsualArithmeticConversions()
1179static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1180 ExprResult &IntExpr,
1181 QualType FloatTy, QualType IntTy,
1182 bool ConvertFloat, bool ConvertInt) {
1183 if (IntTy->isIntegerType()) {
1184 if (ConvertInt)
1185 // Convert intExpr to the lhs floating point type.
1186 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1187 CK_IntegralToFloating);
1188 return FloatTy;
1189 }
1190
1191 // Convert both sides to the appropriate complex float.
1192 assert(IntTy->isComplexIntegerType());
1193 QualType result = S.Context.getComplexType(FloatTy);
1194
1195 // _Complex int -> _Complex float
1196 if (ConvertInt)
1197 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1198 CK_IntegralComplexToFloatingComplex);
1199
1200 // float -> _Complex float
1201 if (ConvertFloat)
1202 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1203 CK_FloatingRealToComplex);
1204
1205 return result;
1206}
1207
1208/// Handle arithmethic conversion with floating point types. Helper
1209/// function of UsualArithmeticConversions()
1210static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1211 ExprResult &RHS, QualType LHSType,
1212 QualType RHSType, bool IsCompAssign) {
1213 bool LHSFloat = LHSType->isRealFloatingType();
1214 bool RHSFloat = RHSType->isRealFloatingType();
1215
1216 // N1169 4.1.4: If one of the operands has a floating type and the other
1217 // operand has a fixed-point type, the fixed-point operand
1218 // is converted to the floating type [...]
1219 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1220 if (LHSFloat)
1221 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1222 else if (!IsCompAssign)
1223 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1224 return LHSFloat ? LHSType : RHSType;
1225 }
1226
1227 // If we have two real floating types, convert the smaller operand
1228 // to the bigger result.
1229 if (LHSFloat && RHSFloat) {
1230 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1231 if (order > 0) {
1232 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1233 return LHSType;
1234 }
1235
1236 assert(order < 0 && "illegal float comparison");
1237 if (!IsCompAssign)
1238 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1239 return RHSType;
1240 }
1241
1242 if (LHSFloat) {
1243 // Half FP has to be promoted to float unless it is natively supported
1244 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1245 LHSType = S.Context.FloatTy;
1246
1247 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1248 /*ConvertFloat=*/!IsCompAssign,
1249 /*ConvertInt=*/ true);
1250 }
1251 assert(RHSFloat);
1252 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1253 /*ConvertFloat=*/ true,
1254 /*ConvertInt=*/!IsCompAssign);
1255}
1256
1257/// Diagnose attempts to convert between __float128, __ibm128 and
1258/// long double if there is no support for such conversion.
1259/// Helper function of UsualArithmeticConversions().
1260static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1261 QualType RHSType) {
1262 // No issue if either is not a floating point type.
1263 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1264 return false;
1265
1266 // No issue if both have the same 128-bit float semantics.
1267 auto *LHSComplex = LHSType->getAs<ComplexType>();
1268 auto *RHSComplex = RHSType->getAs<ComplexType>();
1269
1270 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1271 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1272
1273 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1274 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1275
1276 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1277 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1278 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1279 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1280 return false;
1281
1282 return true;
1283}
1284
1285typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1286
1287namespace {
1288/// These helper callbacks are placed in an anonymous namespace to
1289/// permit their use as function template parameters.
1290ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1291 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1292}
1293
1294ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1295 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1296 CK_IntegralComplexCast);
1297}
1298}
1299
1300/// Handle integer arithmetic conversions. Helper function of
1301/// UsualArithmeticConversions()
1302template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1303static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1304 ExprResult &RHS, QualType LHSType,
1305 QualType RHSType, bool IsCompAssign) {
1306 // The rules for this case are in C99 6.3.1.8
1307 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1308 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1309 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1310 if (LHSSigned == RHSSigned) {
1311 // Same signedness; use the higher-ranked type
1312 if (order >= 0) {
1313 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1314 return LHSType;
1315 } else if (!IsCompAssign)
1316 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1317 return RHSType;
1318 } else if (order != (LHSSigned ? 1 : -1)) {
1319 // The unsigned type has greater than or equal rank to the
1320 // signed type, so use the unsigned type
1321 if (RHSSigned) {
1322 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1323 return LHSType;
1324 } else if (!IsCompAssign)
1325 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1326 return RHSType;
1327 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1328 // The two types are different widths; if we are here, that
1329 // means the signed type is larger than the unsigned type, so
1330 // use the signed type.
1331 if (LHSSigned) {
1332 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1333 return LHSType;
1334 } else if (!IsCompAssign)
1335 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1336 return RHSType;
1337 } else {
1338 // The signed type is higher-ranked than the unsigned type,
1339 // but isn't actually any bigger (like unsigned int and long
1340 // on most 32-bit systems). Use the unsigned type corresponding
1341 // to the signed type.
1342 QualType result =
1343 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1344 RHS = (*doRHSCast)(S, RHS.get(), result);
1345 if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), result);
1347 return result;
1348 }
1349}
1350
1351/// Handle conversions with GCC complex int extension. Helper function
1352/// of UsualArithmeticConversions()
1353static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1354 ExprResult &RHS, QualType LHSType,
1355 QualType RHSType,
1356 bool IsCompAssign) {
1357 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1358 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1359
1360 if (LHSComplexInt && RHSComplexInt) {
1361 QualType LHSEltType = LHSComplexInt->getElementType();
1362 QualType RHSEltType = RHSComplexInt->getElementType();
1363 QualType ScalarType =
1364 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1365 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1366
1367 return S.Context.getComplexType(ScalarType);
1368 }
1369
1370 if (LHSComplexInt) {
1371 QualType LHSEltType = LHSComplexInt->getElementType();
1372 QualType ScalarType =
1373 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1374 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1375 QualType ComplexType = S.Context.getComplexType(ScalarType);
1376 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1377 CK_IntegralRealToComplex);
1378
1379 return ComplexType;
1380 }
1381
1382 assert(RHSComplexInt);
1383
1384 QualType RHSEltType = RHSComplexInt->getElementType();
1385 QualType ScalarType =
1386 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1387 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1388 QualType ComplexType = S.Context.getComplexType(ScalarType);
1389
1390 if (!IsCompAssign)
1391 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1392 CK_IntegralRealToComplex);
1393 return ComplexType;
1394}
1395
1396/// Return the rank of a given fixed point or integer type. The value itself
1397/// doesn't matter, but the values must be increasing with proper increasing
1398/// rank as described in N1169 4.1.1.
1399static unsigned GetFixedPointRank(QualType Ty) {
1400 const auto *BTy = Ty->getAs<BuiltinType>();
1401 assert(BTy && "Expected a builtin type.");
1402
1403 switch (BTy->getKind()) {
1404 case BuiltinType::ShortFract:
1405 case BuiltinType::UShortFract:
1406 case BuiltinType::SatShortFract:
1407 case BuiltinType::SatUShortFract:
1408 return 1;
1409 case BuiltinType::Fract:
1410 case BuiltinType::UFract:
1411 case BuiltinType::SatFract:
1412 case BuiltinType::SatUFract:
1413 return 2;
1414 case BuiltinType::LongFract:
1415 case BuiltinType::ULongFract:
1416 case BuiltinType::SatLongFract:
1417 case BuiltinType::SatULongFract:
1418 return 3;
1419 case BuiltinType::ShortAccum:
1420 case BuiltinType::UShortAccum:
1421 case BuiltinType::SatShortAccum:
1422 case BuiltinType::SatUShortAccum:
1423 return 4;
1424 case BuiltinType::Accum:
1425 case BuiltinType::UAccum:
1426 case BuiltinType::SatAccum:
1427 case BuiltinType::SatUAccum:
1428 return 5;
1429 case BuiltinType::LongAccum:
1430 case BuiltinType::ULongAccum:
1431 case BuiltinType::SatLongAccum:
1432 case BuiltinType::SatULongAccum:
1433 return 6;
1434 default:
1435 if (BTy->isInteger())
1436 return 0;
1437 llvm_unreachable("Unexpected fixed point or integer type");
1438 }
1439}
1440
1441/// handleFixedPointConversion - Fixed point operations between fixed
1442/// point types and integers or other fixed point types do not fall under
1443/// usual arithmetic conversion since these conversions could result in loss
1444/// of precsision (N1169 4.1.4). These operations should be calculated with
1445/// the full precision of their result type (N1169 4.1.6.2.1).
1446static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1447 QualType RHSTy) {
1448 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1449 "Expected at least one of the operands to be a fixed point type");
1450 assert((LHSTy->isFixedPointOrIntegerType() ||
1451 RHSTy->isFixedPointOrIntegerType()) &&
1452 "Special fixed point arithmetic operation conversions are only "
1453 "applied to ints or other fixed point types");
1454
1455 // If one operand has signed fixed-point type and the other operand has
1456 // unsigned fixed-point type, then the unsigned fixed-point operand is
1457 // converted to its corresponding signed fixed-point type and the resulting
1458 // type is the type of the converted operand.
1459 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1460 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1461 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1462 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1463
1464 // The result type is the type with the highest rank, whereby a fixed-point
1465 // conversion rank is always greater than an integer conversion rank; if the
1466 // type of either of the operands is a saturating fixedpoint type, the result
1467 // type shall be the saturating fixed-point type corresponding to the type
1468 // with the highest rank; the resulting value is converted (taking into
1469 // account rounding and overflow) to the precision of the resulting type.
1470 // Same ranks between signed and unsigned types are resolved earlier, so both
1471 // types are either signed or both unsigned at this point.
1472 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1473 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1474
1475 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1476
1477 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1478 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1479
1480 return ResultTy;
1481}
1482
1483/// Check that the usual arithmetic conversions can be performed on this pair of
1484/// expressions that might be of enumeration type.
1485static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1486 SourceLocation Loc,
1487 Sema::ArithConvKind ACK) {
1488 // C++2a [expr.arith.conv]p1:
1489 // If one operand is of enumeration type and the other operand is of a
1490 // different enumeration type or a floating-point type, this behavior is
1491 // deprecated ([depr.arith.conv.enum]).
1492 //
1493 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1494 // Eventually we will presumably reject these cases (in C++23 onwards?).
1495 QualType L = LHS->getType(), R = RHS->getType();
1496 bool LEnum = L->isUnscopedEnumerationType(),
1497 REnum = R->isUnscopedEnumerationType();
1498 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1499 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1500 (REnum && L->isFloatingType())) {
1501 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1502 ? diag::warn_arith_conv_enum_float_cxx20
1503 : diag::warn_arith_conv_enum_float)
1504 << LHS->getSourceRange() << RHS->getSourceRange()
1505 << (int)ACK << LEnum << L << R;
1506 } else if (!IsCompAssign && LEnum && REnum &&
1507 !S.Context.hasSameUnqualifiedType(L, R)) {
1508 unsigned DiagID;
1509 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1510 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1511 // If either enumeration type is unnamed, it's less likely that the
1512 // user cares about this, but this situation is still deprecated in
1513 // C++2a. Use a different warning group.
1514 DiagID = S.getLangOpts().CPlusPlus20
1515 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1516 : diag::warn_arith_conv_mixed_anon_enum_types;
1517 } else if (ACK == Sema::ACK_Conditional) {
1518 // Conditional expressions are separated out because they have
1519 // historically had a different warning flag.
1520 DiagID = S.getLangOpts().CPlusPlus20
1521 ? diag::warn_conditional_mixed_enum_types_cxx20
1522 : diag::warn_conditional_mixed_enum_types;
1523 } else if (ACK == Sema::ACK_Comparison) {
1524 // Comparison expressions are separated out because they have
1525 // historically had a different warning flag.
1526 DiagID = S.getLangOpts().CPlusPlus20
1527 ? diag::warn_comparison_mixed_enum_types_cxx20
1528 : diag::warn_comparison_mixed_enum_types;
1529 } else {
1530 DiagID = S.getLangOpts().CPlusPlus20
1531 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1532 : diag::warn_arith_conv_mixed_enum_types;
1533 }
1534 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1535 << (int)ACK << L << R;
1536 }
1537}
1538
1539/// UsualArithmeticConversions - Performs various conversions that are common to
1540/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1541/// routine returns the first non-arithmetic type found. The client is
1542/// responsible for emitting appropriate error diagnostics.
1543QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1544 SourceLocation Loc,
1545 ArithConvKind ACK) {
1546 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1547
1548 if (ACK != ACK_CompAssign) {
1549 LHS = UsualUnaryConversions(LHS.get());
1550 if (LHS.isInvalid())
1551 return QualType();
1552 }
1553
1554 RHS = UsualUnaryConversions(RHS.get());
1555 if (RHS.isInvalid())
1556 return QualType();
1557
1558 // For conversion purposes, we ignore any qualifiers.
1559 // For example, "const float" and "float" are equivalent.
1560 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1561 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1562
1563 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1564 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1565 LHSType = AtomicLHS->getValueType();
1566
1567 // If both types are identical, no conversion is needed.
1568 if (Context.hasSameType(LHSType, RHSType))
1569 return Context.getCommonSugaredType(LHSType, RHSType);
1570
1571 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1572 // The caller can deal with this (e.g. pointer + int).
1573 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1574 return QualType();
1575
1576 // Apply unary and bitfield promotions to the LHS's type.
1577 QualType LHSUnpromotedType = LHSType;
1578 if (Context.isPromotableIntegerType(LHSType))
1579 LHSType = Context.getPromotedIntegerType(LHSType);
1580 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1581 if (!LHSBitfieldPromoteTy.isNull())
1582 LHSType = LHSBitfieldPromoteTy;
1583 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1584 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1585
1586 // If both types are identical, no conversion is needed.
1587 if (Context.hasSameType(LHSType, RHSType))
1588 return Context.getCommonSugaredType(LHSType, RHSType);
1589
1590 // At this point, we have two different arithmetic types.
1591
1592 // Diagnose attempts to convert between __ibm128, __float128 and long double
1593 // where such conversions currently can't be handled.
1594 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1595 return QualType();
1596
1597 // Handle complex types first (C99 6.3.1.8p1).
1598 if (LHSType->isComplexType() || RHSType->isComplexType())
1599 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1600 ACK == ACK_CompAssign);
1601
1602 // Now handle "real" floating types (i.e. float, double, long double).
1603 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1604 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1605 ACK == ACK_CompAssign);
1606
1607 // Handle GCC complex int extension.
1608 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1609 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1610 ACK == ACK_CompAssign);
1611
1612 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1613 return handleFixedPointConversion(*this, LHSType, RHSType);
1614
1615 // Finally, we have two differing integer types.
1616 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1617 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1618}
1619
1620//===----------------------------------------------------------------------===//
1621// Semantic Analysis for various Expression Types
1622//===----------------------------------------------------------------------===//
1623
1624
1625ExprResult Sema::ActOnGenericSelectionExpr(
1626 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1627 bool PredicateIsExpr, void *ControllingExprOrType,
1628 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1629 unsigned NumAssocs = ArgTypes.size();
1630 assert(NumAssocs == ArgExprs.size());
1631
1632 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1633 for (unsigned i = 0; i < NumAssocs; ++i) {
1634 if (ArgTypes[i])
1635 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1636 else
1637 Types[i] = nullptr;
1638 }
1639
1640 // If we have a controlling type, we need to convert it from a parsed type
1641 // into a semantic type and then pass that along.
1642 if (!PredicateIsExpr) {
1643 TypeSourceInfo *ControllingType;
1644 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1645 &ControllingType);
1646 assert(ControllingType && "couldn't get the type out of the parser");
1647 ControllingExprOrType = ControllingType;
1648 }
1649
1650 ExprResult ER = CreateGenericSelectionExpr(
1651 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1652 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1653 delete [] Types;
1654 return ER;
1655}
1656
1657ExprResult Sema::CreateGenericSelectionExpr(
1658 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1659 bool PredicateIsExpr, void *ControllingExprOrType,
1660 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1661 unsigned NumAssocs = Types.size();
1662 assert(NumAssocs == Exprs.size());
1663 assert(ControllingExprOrType &&
1664 "Must have either a controlling expression or a controlling type");
1665
1666 Expr *ControllingExpr = nullptr;
1667 TypeSourceInfo *ControllingType = nullptr;
1668 if (PredicateIsExpr) {
1669 // Decay and strip qualifiers for the controlling expression type, and
1670 // handle placeholder type replacement. See committee discussion from WG14
1671 // DR423.
1672 EnterExpressionEvaluationContext Unevaluated(
1673 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1674 ExprResult R = DefaultFunctionArrayLvalueConversion(
1675 reinterpret_cast<Expr *>(ControllingExprOrType));
1676 if (R.isInvalid())
1677 return ExprError();
1678 ControllingExpr = R.get();
1679 } else {
1680 // The extension form uses the type directly rather than converting it.
1681 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1682 if (!ControllingType)
1683 return ExprError();
1684 }
1685
1686 bool TypeErrorFound = false,
1687 IsResultDependent = ControllingExpr
1688 ? ControllingExpr->isTypeDependent()
1689 : ControllingType->getType()->isDependentType(),
1690 ContainsUnexpandedParameterPack =
1691 ControllingExpr
1692 ? ControllingExpr->containsUnexpandedParameterPack()
1693 : ControllingType->getType()->containsUnexpandedParameterPack();
1694
1695 // The controlling expression is an unevaluated operand, so side effects are
1696 // likely unintended.
1697 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1698 ControllingExpr->HasSideEffects(Context, false))
1699 Diag(ControllingExpr->getExprLoc(),
1700 diag::warn_side_effects_unevaluated_context);
1701
1702 for (unsigned i = 0; i < NumAssocs; ++i) {
1703 if (Exprs[i]->containsUnexpandedParameterPack())
1704 ContainsUnexpandedParameterPack = true;
1705
1706 if (Types[i]) {
1707 if (Types[i]->getType()->containsUnexpandedParameterPack())
1708 ContainsUnexpandedParameterPack = true;
1709
1710 if (Types[i]->getType()->isDependentType()) {
1711 IsResultDependent = true;
1712 } else {
1713 // We relax the restriction on use of incomplete types and non-object
1714 // types with the type-based extension of _Generic. Allowing incomplete
1715 // objects means those can be used as "tags" for a type-safe way to map
1716 // to a value. Similarly, matching on function types rather than
1717 // function pointer types can be useful. However, the restriction on VM
1718 // types makes sense to retain as there are open questions about how
1719 // the selection can be made at compile time.
1720 //
1721 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1722 // complete object type other than a variably modified type."
1723 unsigned D = 0;
1724 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1725 D = diag::err_assoc_type_incomplete;
1726 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1727 D = diag::err_assoc_type_nonobject;
1728 else if (Types[i]->getType()->isVariablyModifiedType())
1729 D = diag::err_assoc_type_variably_modified;
1730 else if (ControllingExpr) {
1731 // Because the controlling expression undergoes lvalue conversion,
1732 // array conversion, and function conversion, an association which is
1733 // of array type, function type, or is qualified can never be
1734 // reached. We will warn about this so users are less surprised by
1735 // the unreachable association. However, we don't have to handle
1736 // function types; that's not an object type, so it's handled above.
1737 //
1738 // The logic is somewhat different for C++ because C++ has different
1739 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1740 // If T is a non-class type, the type of the prvalue is the cv-
1741 // unqualified version of T. Otherwise, the type of the prvalue is T.
1742 // The result of these rules is that all qualified types in an
1743 // association in C are unreachable, and in C++, only qualified non-
1744 // class types are unreachable.
1745 //
1746 // NB: this does not apply when the first operand is a type rather
1747 // than an expression, because the type form does not undergo
1748 // conversion.
1749 unsigned Reason = 0;
1750 QualType QT = Types[i]->getType();
1751 if (QT->isArrayType())
1752 Reason = 1;
1753 else if (QT.hasQualifiers() &&
1754 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1755 Reason = 2;
1756
1757 if (Reason)
1758 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1759 diag::warn_unreachable_association)
1760 << QT << (Reason - 1);
1761 }
1762
1763 if (D != 0) {
1764 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1765 << Types[i]->getTypeLoc().getSourceRange()
1766 << Types[i]->getType();
1767 TypeErrorFound = true;
1768 }
1769
1770 // C11 6.5.1.1p2 "No two generic associations in the same generic
1771 // selection shall specify compatible types."
1772 for (unsigned j = i+1; j < NumAssocs; ++j)
1773 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1774 Context.typesAreCompatible(Types[i]->getType(),
1775 Types[j]->getType())) {
1776 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1777 diag::err_assoc_compatible_types)
1778 << Types[j]->getTypeLoc().getSourceRange()
1779 << Types[j]->getType()
1780 << Types[i]->getType();
1781 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1782 diag::note_compat_assoc)
1783 << Types[i]->getTypeLoc().getSourceRange()
1784 << Types[i]->getType();
1785 TypeErrorFound = true;
1786 }
1787 }
1788 }
1789 }
1790 if (TypeErrorFound)
1791 return ExprError();
1792
1793 // If we determined that the generic selection is result-dependent, don't
1794 // try to compute the result expression.
1795 if (IsResultDependent) {
1796 if (ControllingExpr)
1797 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1798 Types, Exprs, DefaultLoc, RParenLoc,
1799 ContainsUnexpandedParameterPack);
1800 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1801 Exprs, DefaultLoc, RParenLoc,
1802 ContainsUnexpandedParameterPack);
1803 }
1804
1805 SmallVector<unsigned, 1> CompatIndices;
1806 unsigned DefaultIndex = -1U;
1807 // Look at the canonical type of the controlling expression in case it was a
1808 // deduced type like __auto_type. However, when issuing diagnostics, use the
1809 // type the user wrote in source rather than the canonical one.
1810 for (unsigned i = 0; i < NumAssocs; ++i) {
1811 if (!Types[i])
1812 DefaultIndex = i;
1813 else if (ControllingExpr &&
1814 Context.typesAreCompatible(
1815 ControllingExpr->getType().getCanonicalType(),
1816 Types[i]->getType()))
1817 CompatIndices.push_back(i);
1818 else if (ControllingType &&
1819 Context.typesAreCompatible(
1820 ControllingType->getType().getCanonicalType(),
1821 Types[i]->getType()))
1822 CompatIndices.push_back(i);
1823 }
1824
1825 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1826 TypeSourceInfo *ControllingType) {
1827 // We strip parens here because the controlling expression is typically
1828 // parenthesized in macro definitions.
1829 if (ControllingExpr)
1830 ControllingExpr = ControllingExpr->IgnoreParens();
1831
1832 SourceRange SR = ControllingExpr
1833 ? ControllingExpr->getSourceRange()
1834 : ControllingType->getTypeLoc().getSourceRange();
1835 QualType QT = ControllingExpr ? ControllingExpr->getType()
1836 : ControllingType->getType();
1837
1838 return std::make_pair(SR, QT);
1839 };
1840
1841 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1842 // type compatible with at most one of the types named in its generic
1843 // association list."
1844 if (CompatIndices.size() > 1) {
1845 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1846 SourceRange SR = P.first;
1847 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1848 << SR << P.second << (unsigned)CompatIndices.size();
1849 for (unsigned I : CompatIndices) {
1850 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1851 diag::note_compat_assoc)
1852 << Types[I]->getTypeLoc().getSourceRange()
1853 << Types[I]->getType();
1854 }
1855 return ExprError();
1856 }
1857
1858 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1859 // its controlling expression shall have type compatible with exactly one of
1860 // the types named in its generic association list."
1861 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1862 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1863 SourceRange SR = P.first;
1864 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1865 return ExprError();
1866 }
1867
1868 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1869 // type name that is compatible with the type of the controlling expression,
1870 // then the result expression of the generic selection is the expression
1871 // in that generic association. Otherwise, the result expression of the
1872 // generic selection is the expression in the default generic association."
1873 unsigned ResultIndex =
1874 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1875
1876 if (ControllingExpr) {
1877 return GenericSelectionExpr::Create(
1878 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1879 ContainsUnexpandedParameterPack, ResultIndex);
1880 }
1881 return GenericSelectionExpr::Create(
1882 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1883 ContainsUnexpandedParameterPack, ResultIndex);
1884}
1885
1886/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1887/// location of the token and the offset of the ud-suffix within it.
1888static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1889 unsigned Offset) {
1890 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1891 S.getLangOpts());
1892}
1893
1894/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1895/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1896static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1897 IdentifierInfo *UDSuffix,
1898 SourceLocation UDSuffixLoc,
1899 ArrayRef<Expr*> Args,
1900 SourceLocation LitEndLoc) {
1901 assert(Args.size() <= 2 && "too many arguments for literal operator");
1902
1903 QualType ArgTy[2];
1904 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1905 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1906 if (ArgTy[ArgIdx]->isArrayType())
1907 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1908 }
1909
1910 DeclarationName OpName =
1911 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1912 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1913 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1914
1915 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1916 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1917 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1918 /*AllowStringTemplatePack*/ false,
1919 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1920 return ExprError();
1921
1922 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1923}
1924
1925ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
1926 StringLiteralParser Literal(StringToks, PP,
1927 StringLiteralEvalMethod::Unevaluated);
1928 if (Literal.hadError)
1929 return ExprError();
1930
1931 SmallVector<SourceLocation, 4> StringTokLocs;
1932 for (const Token &Tok : StringToks)
1933 StringTokLocs.push_back(Tok.getLocation());
1934
1935 StringLiteral *Lit = StringLiteral::Create(
1936 Context, Literal.GetString(), StringLiteral::Unevaluated, false, {},
1937 &StringTokLocs[0], StringTokLocs.size());
1938
1939 if (!Literal.getUDSuffix().empty()) {
1940 SourceLocation UDSuffixLoc =
1941 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1942 Literal.getUDSuffixOffset());
1943 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1944 }
1945
1946 return Lit;
1947}
1948
1949/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1950/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1951/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1952/// multiple tokens. However, the common case is that StringToks points to one
1953/// string.
1954///
1955ExprResult
1956Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1957 assert(!StringToks.empty() && "Must have at least one string!");
1958
1959 StringLiteralParser Literal(StringToks, PP);
1960 if (Literal.hadError)
1961 return ExprError();
1962
1963 SmallVector<SourceLocation, 4> StringTokLocs;
1964 for (const Token &Tok : StringToks)
1965 StringTokLocs.push_back(Tok.getLocation());
1966
1967 QualType CharTy = Context.CharTy;
1968 StringLiteral::StringKind Kind = StringLiteral::Ordinary;
1969 if (Literal.isWide()) {
1970 CharTy = Context.getWideCharType();
1971 Kind = StringLiteral::Wide;
1972 } else if (Literal.isUTF8()) {
1973 if (getLangOpts().Char8)
1974 CharTy = Context.Char8Ty;
1975 Kind = StringLiteral::UTF8;
1976 } else if (Literal.isUTF16()) {
1977 CharTy = Context.Char16Ty;
1978 Kind = StringLiteral::UTF16;
1979 } else if (Literal.isUTF32()) {
1980 CharTy = Context.Char32Ty;
1981 Kind = StringLiteral::UTF32;
1982 } else if (Literal.isPascal()) {
1983 CharTy = Context.UnsignedCharTy;
1984 }
1985
1986 // Warn on initializing an array of char from a u8 string literal; this
1987 // becomes ill-formed in C++2a.
1988 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1989 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1990 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1991
1992 // Create removals for all 'u8' prefixes in the string literal(s). This
1993 // ensures C++2a compatibility (but may change the program behavior when
1994 // built by non-Clang compilers for which the execution character set is
1995 // not always UTF-8).
1996 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1997 SourceLocation RemovalDiagLoc;
1998 for (const Token &Tok : StringToks) {
1999 if (Tok.getKind() == tok::utf8_string_literal) {
2000 if (RemovalDiagLoc.isInvalid())
2001 RemovalDiagLoc = Tok.getLocation();
2002 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2003 Tok.getLocation(),
2004 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2005 getSourceManager(), getLangOpts())));
2006 }
2007 }
2008 Diag(RemovalDiagLoc, RemovalDiag);
2009 }
2010
2011 QualType StrTy =
2012 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2013
2014 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2015 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2016 Kind, Literal.Pascal, StrTy,
2017 &StringTokLocs[0],
2018 StringTokLocs.size());
2019 if (Literal.getUDSuffix().empty())
2020 return Lit;
2021
2022 // We're building a user-defined literal.
2023 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2024 SourceLocation UDSuffixLoc =
2025 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2026 Literal.getUDSuffixOffset());
2027
2028 // Make sure we're allowed user-defined literals here.
2029 if (!UDLScope)
2030 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2031
2032 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2033 // operator "" X (str, len)
2034 QualType SizeType = Context.getSizeType();
2035
2036 DeclarationName OpName =
2037 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2038 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2039 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2040
2041 QualType ArgTy[] = {
2042 Context.getArrayDecayedType(StrTy), SizeType
2043 };
2044
2045 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2046 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2047 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2048 /*AllowStringTemplatePack*/ true,
2049 /*DiagnoseMissing*/ true, Lit)) {
2050
2051 case LOLR_Cooked: {
2052 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2053 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2054 StringTokLocs[0]);
2055 Expr *Args[] = { Lit, LenArg };
2056
2057 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2058 }
2059
2060 case LOLR_Template: {
2061 TemplateArgumentListInfo ExplicitArgs;
2062 TemplateArgument Arg(Lit);
2063 TemplateArgumentLocInfo ArgInfo(Lit);
2064 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2065 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2066 StringTokLocs.back(), &ExplicitArgs);
2067 }
2068
2069 case LOLR_StringTemplatePack: {
2070 TemplateArgumentListInfo ExplicitArgs;
2071
2072 unsigned CharBits = Context.getIntWidth(CharTy);
2073 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2074 llvm::APSInt Value(CharBits, CharIsUnsigned);
2075
2076 TemplateArgument TypeArg(CharTy);
2077 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2078 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2079
2080 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2081 Value = Lit->getCodeUnit(I);
2082 TemplateArgument Arg(Context, Value, CharTy);
2083 TemplateArgumentLocInfo ArgInfo;
2084 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2085 }
2086 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2087 StringTokLocs.back(), &ExplicitArgs);
2088 }
2089 case LOLR_Raw:
2090 case LOLR_ErrorNoDiagnostic:
2091 llvm_unreachable("unexpected literal operator lookup result");
2092 case LOLR_Error:
2093 return ExprError();
2094 }
2095 llvm_unreachable("unexpected literal operator lookup result");
2096}
2097
2098DeclRefExpr *
2099Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2100 SourceLocation Loc,
2101 const CXXScopeSpec *SS) {
2102 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2103 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2104}
2105
2106DeclRefExpr *
2107Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2108 const DeclarationNameInfo &NameInfo,
2109 const CXXScopeSpec *SS, NamedDecl *FoundD,
2110 SourceLocation TemplateKWLoc,
2111 const TemplateArgumentListInfo *TemplateArgs) {
2112 NestedNameSpecifierLoc NNS =
2113 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2114 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2115 TemplateArgs);
2116}
2117
2118// CUDA/HIP: Check whether a captured reference variable is referencing a
2119// host variable in a device or host device lambda.
2120static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2121 VarDecl *VD) {
2122 if (!S.getLangOpts().CUDA || !VD->hasInit())
2123 return false;
2124 assert(VD->getType()->isReferenceType());
2125
2126 // Check whether the reference variable is referencing a host variable.
2127 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2128 if (!DRE)
2129 return false;
2130 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2131 if (!Referee || !Referee->hasGlobalStorage() ||
2132 Referee->hasAttr<CUDADeviceAttr>())
2133 return false;
2134
2135 // Check whether the current function is a device or host device lambda.
2136 // Check whether the reference variable is a capture by getDeclContext()
2137 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2138 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2139 if (MD && MD->getParent()->isLambda() &&
2140 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2141 VD->getDeclContext() != MD)
2142 return true;
2143
2144 return false;
2145}
2146
2147NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2148 // A declaration named in an unevaluated operand never constitutes an odr-use.
2149 if (isUnevaluatedContext())
2150 return NOUR_Unevaluated;
2151
2152 // C++2a [basic.def.odr]p4:
2153 // A variable x whose name appears as a potentially-evaluated expression e
2154 // is odr-used by e unless [...] x is a reference that is usable in
2155 // constant expressions.
2156 // CUDA/HIP:
2157 // If a reference variable referencing a host variable is captured in a
2158 // device or host device lambda, the value of the referee must be copied
2159 // to the capture and the reference variable must be treated as odr-use
2160 // since the value of the referee is not known at compile time and must
2161 // be loaded from the captured.
2162 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2163 if (VD->getType()->isReferenceType() &&
2164 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2165 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2166 VD->isUsableInConstantExpressions(Context))
2167 return NOUR_Constant;
2168 }
2169
2170 // All remaining non-variable cases constitute an odr-use. For variables, we
2171 // need to wait and see how the expression is used.
2172 return NOUR_None;
2173}
2174
2175/// BuildDeclRefExpr - Build an expression that references a
2176/// declaration that does not require a closure capture.
2177DeclRefExpr *
2178Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2179 const DeclarationNameInfo &NameInfo,
2180 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2181 SourceLocation TemplateKWLoc,
2182 const TemplateArgumentListInfo *TemplateArgs) {
2183 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2184 NeedToCaptureVariable(D, NameInfo.getLoc());
2185
2186 DeclRefExpr *E = DeclRefExpr::Create(
2187 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2188 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2189 MarkDeclRefReferenced(E);
2190
2191 // C++ [except.spec]p17:
2192 // An exception-specification is considered to be needed when:
2193 // - in an expression, the function is the unique lookup result or
2194 // the selected member of a set of overloaded functions.
2195 //
2196 // We delay doing this until after we've built the function reference and
2197 // marked it as used so that:
2198 // a) if the function is defaulted, we get errors from defining it before /
2199 // instead of errors from computing its exception specification, and
2200 // b) if the function is a defaulted comparison, we can use the body we
2201 // build when defining it as input to the exception specification
2202 // computation rather than computing a new body.
2203 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2204 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2205 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2206 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2207 }
2208 }
2209
2210 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2211 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2212 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2213 getCurFunction()->recordUseOfWeak(E);
2214
2215 const auto *FD = dyn_cast<FieldDecl>(D);
2216 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2217 FD = IFD->getAnonField();
2218 if (FD) {
2219 UnusedPrivateFields.remove(FD);
2220 // Just in case we're building an illegal pointer-to-member.
2221 if (FD->isBitField())
2222 E->setObjectKind(OK_BitField);
2223 }
2224
2225 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2226 // designates a bit-field.
2227 if (const auto *BD = dyn_cast<BindingDecl>(D))
2228 if (const auto *BE = BD->getBinding())
2229 E->setObjectKind(BE->getObjectKind());
2230
2231 return E;
2232}
2233
2234/// Decomposes the given name into a DeclarationNameInfo, its location, and
2235/// possibly a list of template arguments.
2236///
2237/// If this produces template arguments, it is permitted to call
2238/// DecomposeTemplateName.
2239///
2240/// This actually loses a lot of source location information for
2241/// non-standard name kinds; we should consider preserving that in
2242/// some way.
2243void
2244Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2245 TemplateArgumentListInfo &Buffer,
2246 DeclarationNameInfo &NameInfo,
2247 const TemplateArgumentListInfo *&TemplateArgs) {
2248 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2249 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2250 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2251
2252 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2253 Id.TemplateId->NumArgs);
2254 translateTemplateArguments(TemplateArgsPtr, Buffer);
2255
2256 TemplateName TName = Id.TemplateId->Template.get();
2257 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2258 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2259 TemplateArgs = &Buffer;
2260 } else {
2261 NameInfo = GetNameFromUnqualifiedId(Id);
2262 TemplateArgs = nullptr;
2263 }
2264}
2265
2266static void emitEmptyLookupTypoDiagnostic(
2267 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2268 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2269 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2270 DeclContext *Ctx =
2271 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2272 if (!TC) {
2273 // Emit a special diagnostic for failed member lookups.
2274 // FIXME: computing the declaration context might fail here (?)
2275 if (Ctx)
2276 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2277 << SS.getRange();
2278 else
2279 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2280 return;
2281 }
2282
2283 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2284 bool DroppedSpecifier =
2285 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2286 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2287 ? diag::note_implicit_param_decl
2288 : diag::note_previous_decl;
2289 if (!Ctx)
2290 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2291 SemaRef.PDiag(NoteID));
2292 else
2293 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2294 << Typo << Ctx << DroppedSpecifier
2295 << SS.getRange(),
2296 SemaRef.PDiag(NoteID));
2297}
2298
2299/// Diagnose a lookup that found results in an enclosing class during error
2300/// recovery. This usually indicates that the results were found in a dependent
2301/// base class that could not be searched as part of a template definition.
2302/// Always issues a diagnostic (though this may be only a warning in MS
2303/// compatibility mode).
2304///
2305/// Return \c true if the error is unrecoverable, or \c false if the caller
2306/// should attempt to recover using these lookup results.
2307bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2308 // During a default argument instantiation the CurContext points
2309 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2310 // function parameter list, hence add an explicit check.
2311 bool isDefaultArgument =
2312 !CodeSynthesisContexts.empty() &&
2313 CodeSynthesisContexts.back().Kind ==
2314 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2315 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2316 bool isInstance = CurMethod && CurMethod->isInstance() &&
2317 R.getNamingClass() == CurMethod->getParent() &&
2318 !isDefaultArgument;
2319
2320 // There are two ways we can find a class-scope declaration during template
2321 // instantiation that we did not find in the template definition: if it is a
2322 // member of a dependent base class, or if it is declared after the point of
2323 // use in the same class. Distinguish these by comparing the class in which
2324 // the member was found to the naming class of the lookup.
2325 unsigned DiagID = diag::err_found_in_dependent_base;
2326 unsigned NoteID = diag::note_member_declared_at;
2327 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2328 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2329 : diag::err_found_later_in_class;
2330 } else if (getLangOpts().MSVCCompat) {
2331 DiagID = diag::ext_found_in_dependent_base;
2332 NoteID = diag::note_dependent_member_use;
2333 }
2334
2335 if (isInstance) {
2336 // Give a code modification hint to insert 'this->'.
2337 Diag(R.getNameLoc(), DiagID)
2338 << R.getLookupName()
2339 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2340 CheckCXXThisCapture(R.getNameLoc());
2341 } else {
2342 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2343 // they're not shadowed).
2344 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2345 }
2346
2347 for (const NamedDecl *D : R)
2348 Diag(D->getLocation(), NoteID);
2349
2350 // Return true if we are inside a default argument instantiation
2351 // and the found name refers to an instance member function, otherwise
2352 // the caller will try to create an implicit member call and this is wrong
2353 // for default arguments.
2354 //
2355 // FIXME: Is this special case necessary? We could allow the caller to
2356 // diagnose this.
2357 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2358 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2359 return true;
2360 }
2361
2362 // Tell the callee to try to recover.
2363 return false;
2364}
2365
2366/// Diagnose an empty lookup.
2367///
2368/// \return false if new lookup candidates were found
2369bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2370 CorrectionCandidateCallback &CCC,
2371 TemplateArgumentListInfo *ExplicitTemplateArgs,
2372 ArrayRef<Expr *> Args, TypoExpr **Out) {
2373 DeclarationName Name = R.getLookupName();
2374
2375 unsigned diagnostic = diag::err_undeclared_var_use;
2376 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2377 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2378 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2379 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2380 diagnostic = diag::err_undeclared_use;
2381 diagnostic_suggest = diag::err_undeclared_use_suggest;
2382 }
2383
2384 // If the original lookup was an unqualified lookup, fake an
2385 // unqualified lookup. This is useful when (for example) the
2386 // original lookup would not have found something because it was a
2387 // dependent name.
2388 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2389 while (DC) {
2390 if (isa<CXXRecordDecl>(DC)) {
2391 LookupQualifiedName(R, DC);
2392
2393 if (!R.empty()) {
2394 // Don't give errors about ambiguities in this lookup.
2395 R.suppressDiagnostics();
2396
2397 // If there's a best viable function among the results, only mention
2398 // that one in the notes.
2399 OverloadCandidateSet Candidates(R.getNameLoc(),
2400 OverloadCandidateSet::CSK_Normal);
2401 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2402 OverloadCandidateSet::iterator Best;
2403 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2404 OR_Success) {
2405 R.clear();
2406 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2407 R.resolveKind();
2408 }
2409
2410 return DiagnoseDependentMemberLookup(R);
2411 }
2412
2413 R.clear();
2414 }
2415
2416 DC = DC->getLookupParent();
2417 }
2418
2419 // We didn't find anything, so try to correct for a typo.
2420 TypoCorrection Corrected;
2421 if (S && Out) {
2422 SourceLocation TypoLoc = R.getNameLoc();
2423 assert(!ExplicitTemplateArgs &&
2424 "Diagnosing an empty lookup with explicit template args!");
2425 *Out = CorrectTypoDelayed(
2426 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2427 [=](const TypoCorrection &TC) {
2428 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2429 diagnostic, diagnostic_suggest);
2430 },
2431 nullptr, CTK_ErrorRecovery);
2432 if (*Out)
2433 return true;
2434 } else if (S &&
2435 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2436 S, &SS, CCC, CTK_ErrorRecovery))) {
2437 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2438 bool DroppedSpecifier =
2439 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2440 R.setLookupName(Corrected.getCorrection());
2441
2442 bool AcceptableWithRecovery = false;
2443 bool AcceptableWithoutRecovery = false;
2444 NamedDecl *ND = Corrected.getFoundDecl();
2445 if (ND) {
2446 if (Corrected.isOverloaded()) {
2447 OverloadCandidateSet OCS(R.getNameLoc(),
2448 OverloadCandidateSet::CSK_Normal);
2449 OverloadCandidateSet::iterator Best;
2450 for (NamedDecl *CD : Corrected) {
2451 if (FunctionTemplateDecl *FTD =
2452 dyn_cast<FunctionTemplateDecl>(CD))
2453 AddTemplateOverloadCandidate(
2454 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2455 Args, OCS);
2456 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2457 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2458 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2459 Args, OCS);
2460 }
2461 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2462 case OR_Success:
2463 ND = Best->FoundDecl;
2464 Corrected.setCorrectionDecl(ND);
2465 break;
2466 default:
2467 // FIXME: Arbitrarily pick the first declaration for the note.
2468 Corrected.setCorrectionDecl(ND);
2469 break;
2470 }
2471 }
2472 R.addDecl(ND);
2473 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2474 CXXRecordDecl *Record = nullptr;
2475 if (Corrected.getCorrectionSpecifier()) {
2476 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2477 Record = Ty->getAsCXXRecordDecl();
2478 }
2479 if (!Record)
2480 Record = cast<CXXRecordDecl>(
2481 ND->getDeclContext()->getRedeclContext());
2482 R.setNamingClass(Record);
2483 }
2484
2485 auto *UnderlyingND = ND->getUnderlyingDecl();
2486 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2487 isa<FunctionTemplateDecl>(UnderlyingND);
2488 // FIXME: If we ended up with a typo for a type name or
2489 // Objective-C class name, we're in trouble because the parser
2490 // is in the wrong place to recover. Suggest the typo
2491 // correction, but don't make it a fix-it since we're not going
2492 // to recover well anyway.
2493 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2494 getAsTypeTemplateDecl(UnderlyingND) ||
2495 isa<ObjCInterfaceDecl>(UnderlyingND);
2496 } else {
2497 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2498 // because we aren't able to recover.
2499 AcceptableWithoutRecovery = true;
2500 }
2501
2502 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2503 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2504 ? diag::note_implicit_param_decl
2505 : diag::note_previous_decl;
2506 if (SS.isEmpty())
2507 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2508 PDiag(NoteID), AcceptableWithRecovery);
2509 else
2510 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2511 << Name << computeDeclContext(SS, false)
2512 << DroppedSpecifier << SS.getRange(),
2513 PDiag(NoteID), AcceptableWithRecovery);
2514
2515 // Tell the callee whether to try to recover.
2516 return !AcceptableWithRecovery;
2517 }
2518 }
2519 R.clear();
2520
2521 // Emit a special diagnostic for failed member lookups.
2522 // FIXME: computing the declaration context might fail here (?)
2523 if (!SS.isEmpty()) {
2524 Diag(R.getNameLoc(), diag::err_no_member)
2525 << Name << computeDeclContext(SS, false)
2526 << SS.getRange();
2527 return true;
2528 }
2529
2530 // Give up, we can't recover.
2531 Diag(R.getNameLoc(), diagnostic) << Name;
2532 return true;
2533}
2534
2535/// In Microsoft mode, if we are inside a template class whose parent class has
2536/// dependent base classes, and we can't resolve an unqualified identifier, then
2537/// assume the identifier is a member of a dependent base class. We can only
2538/// recover successfully in static methods, instance methods, and other contexts
2539/// where 'this' is available. This doesn't precisely match MSVC's
2540/// instantiation model, but it's close enough.
2541static Expr *
2542recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2543 DeclarationNameInfo &NameInfo,
2544 SourceLocation TemplateKWLoc,
2545 const TemplateArgumentListInfo *TemplateArgs) {
2546 // Only try to recover from lookup into dependent bases in static methods or
2547 // contexts where 'this' is available.
2548 QualType ThisType = S.getCurrentThisType();
2549 const CXXRecordDecl *RD = nullptr;
2550 if (!ThisType.isNull())
2551 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2552 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2553 RD = MD->getParent();
2554 if (!RD || !RD->hasAnyDependentBases())
2555 return nullptr;
2556
2557 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2558 // is available, suggest inserting 'this->' as a fixit.
2559 SourceLocation Loc = NameInfo.getLoc();
2560 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2561 DB << NameInfo.getName() << RD;
2562
2563 if (!ThisType.isNull()) {
2564 DB << FixItHint::CreateInsertion(Loc, "this->");
2565 return CXXDependentScopeMemberExpr::Create(
2566 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2567 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2568 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2569 }
2570
2571 // Synthesize a fake NNS that points to the derived class. This will
2572 // perform name lookup during template instantiation.
2573 CXXScopeSpec SS;
2574 auto *NNS =
2575 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2576 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2577 return DependentScopeDeclRefExpr::Create(
2578 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2579 TemplateArgs);
2580}
2581
2582ExprResult
2583Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2584 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2585 bool HasTrailingLParen, bool IsAddressOfOperand,
2586 CorrectionCandidateCallback *CCC,
2587 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2588 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2589 "cannot be direct & operand and have a trailing lparen");
2590 if (SS.isInvalid())
2591 return ExprError();
2592
2593 TemplateArgumentListInfo TemplateArgsBuffer;
2594
2595 // Decompose the UnqualifiedId into the following data.
2596 DeclarationNameInfo NameInfo;
2597 const TemplateArgumentListInfo *TemplateArgs;
2598 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2599
2600 DeclarationName Name = NameInfo.getName();
2601 IdentifierInfo *II = Name.getAsIdentifierInfo();
2602 SourceLocation NameLoc = NameInfo.getLoc();
2603
2604 if (II && II->isEditorPlaceholder()) {
2605 // FIXME: When typed placeholders are supported we can create a typed
2606 // placeholder expression node.
2607 return ExprError();
2608 }
2609
2610 // C++ [temp.dep.expr]p3:
2611 // An id-expression is type-dependent if it contains:
2612 // -- an identifier that was declared with a dependent type,
2613 // (note: handled after lookup)
2614 // -- a template-id that is dependent,
2615 // (note: handled in BuildTemplateIdExpr)
2616 // -- a conversion-function-id that specifies a dependent type,
2617 // -- a nested-name-specifier that contains a class-name that
2618 // names a dependent type.
2619 // Determine whether this is a member of an unknown specialization;
2620 // we need to handle these differently.
2621 bool DependentID = false;
2622 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2623 Name.getCXXNameType()->isDependentType()) {
2624 DependentID = true;
2625 } else if (SS.isSet()) {
2626 if (DeclContext *DC = computeDeclContext(SS, false)) {
2627 if (RequireCompleteDeclContext(SS, DC))
2628 return ExprError();
2629 } else {
2630 DependentID = true;
2631 }
2632 }
2633
2634 if (DependentID)
2635 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2636 IsAddressOfOperand, TemplateArgs);
2637
2638 // Perform the required lookup.
2639 LookupResult R(*this, NameInfo,
2640 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2641 ? LookupObjCImplicitSelfParam
2642 : LookupOrdinaryName);
2643 if (TemplateKWLoc.isValid() || TemplateArgs) {
2644 // Lookup the template name again to correctly establish the context in
2645 // which it was found. This is really unfortunate as we already did the
2646 // lookup to determine that it was a template name in the first place. If
2647 // this becomes a performance hit, we can work harder to preserve those
2648 // results until we get here but it's likely not worth it.
2649 bool MemberOfUnknownSpecialization;
2650 AssumedTemplateKind AssumedTemplate;
2651 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2652 MemberOfUnknownSpecialization, TemplateKWLoc,
2653 &AssumedTemplate))
2654 return ExprError();
2655
2656 if (MemberOfUnknownSpecialization ||
2657 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2658 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2659 IsAddressOfOperand, TemplateArgs);
2660 } else {
2661 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2662 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2663
2664 // If the result might be in a dependent base class, this is a dependent
2665 // id-expression.
2666 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2667 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2668 IsAddressOfOperand, TemplateArgs);
2669
2670 // If this reference is in an Objective-C method, then we need to do
2671 // some special Objective-C lookup, too.
2672 if (IvarLookupFollowUp) {
2673 ExprResult E(LookupInObjCMethod(R, S, II, true));
2674 if (E.isInvalid())
2675 return ExprError();
2676
2677 if (Expr *Ex = E.getAs<Expr>())
2678 return Ex;
2679 }
2680 }
2681
2682 if (R.isAmbiguous())
2683 return ExprError();
2684
2685 // This could be an implicitly declared function reference if the language
2686 // mode allows it as a feature.
2687 if (R.empty() && HasTrailingLParen && II &&
2688 getLangOpts().implicitFunctionsAllowed()) {
2689 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2690 if (D) R.addDecl(D);
2691 }
2692
2693 // Determine whether this name might be a candidate for
2694 // argument-dependent lookup.
2695 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2696
2697 if (R.empty() && !ADL) {
2698 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2699 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2700 TemplateKWLoc, TemplateArgs))
2701 return E;
2702 }
2703
2704 // Don't diagnose an empty lookup for inline assembly.
2705 if (IsInlineAsmIdentifier)
2706 return ExprError();
2707
2708 // If this name wasn't predeclared and if this is not a function
2709 // call, diagnose the problem.
2710 TypoExpr *TE = nullptr;
2711 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2712 : nullptr);
2713 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2714 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2715 "Typo correction callback misconfigured");
2716 if (CCC) {
2717 // Make sure the callback knows what the typo being diagnosed is.
2718 CCC->setTypoName(II);
2719 if (SS.isValid())
2720 CCC->setTypoNNS(SS.getScopeRep());
2721 }
2722 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2723 // a template name, but we happen to have always already looked up the name
2724 // before we get here if it must be a template name.
2725 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2726 std::nullopt, &TE)) {
2727 if (TE && KeywordReplacement) {
2728 auto &State = getTypoExprState(TE);
2729 auto BestTC = State.Consumer->getNextCorrection();
2730 if (BestTC.isKeyword()) {
2731 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2732 if (State.DiagHandler)
2733 State.DiagHandler(BestTC);
2734 KeywordReplacement->startToken();
2735 KeywordReplacement->setKind(II->getTokenID());
2736 KeywordReplacement->setIdentifierInfo(II);
2737 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2738 // Clean up the state associated with the TypoExpr, since it has
2739 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2740 clearDelayedTypo(TE);
2741 // Signal that a correction to a keyword was performed by returning a
2742 // valid-but-null ExprResult.
2743 return (Expr*)nullptr;
2744 }
2745 State.Consumer->resetCorrectionStream();
2746 }
2747 return TE ? TE : ExprError();
2748 }
2749
2750 assert(!R.empty() &&
2751 "DiagnoseEmptyLookup returned false but added no results");
2752
2753 // If we found an Objective-C instance variable, let
2754 // LookupInObjCMethod build the appropriate expression to
2755 // reference the ivar.
2756 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2757 R.clear();
2758 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2759 // In a hopelessly buggy code, Objective-C instance variable
2760 // lookup fails and no expression will be built to reference it.
2761 if (!E.isInvalid() && !E.get())
2762 return ExprError();
2763 return E;
2764 }
2765 }
2766
2767 // This is guaranteed from this point on.
2768 assert(!R.empty() || ADL);
2769
2770 // Check whether this might be a C++ implicit instance member access.
2771 // C++ [class.mfct.non-static]p3:
2772 // When an id-expression that is not part of a class member access
2773 // syntax and not used to form a pointer to member is used in the
2774 // body of a non-static member function of class X, if name lookup
2775 // resolves the name in the id-expression to a non-static non-type
2776 // member of some class C, the id-expression is transformed into a
2777 // class member access expression using (*this) as the
2778 // postfix-expression to the left of the . operator.
2779 //
2780 // But we don't actually need to do this for '&' operands if R
2781 // resolved to a function or overloaded function set, because the
2782 // expression is ill-formed if it actually works out to be a
2783 // non-static member function:
2784 //
2785 // C++ [expr.ref]p4:
2786 // Otherwise, if E1.E2 refers to a non-static member function. . .
2787 // [t]he expression can be used only as the left-hand operand of a
2788 // member function call.
2789 //
2790 // There are other safeguards against such uses, but it's important
2791 // to get this right here so that we don't end up making a
2792 // spuriously dependent expression if we're inside a dependent
2793 // instance method.
2794 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2795 bool MightBeImplicitMember;
2796 if (!IsAddressOfOperand)
2797 MightBeImplicitMember = true;
2798 else if (!SS.isEmpty())
2799 MightBeImplicitMember = false;
2800 else if (R.isOverloadedResult())
2801 MightBeImplicitMember = false;
2802 else if (R.isUnresolvableResult())
2803 MightBeImplicitMember = true;
2804 else
2805 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2806 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2807 isa<MSPropertyDecl>(R.getFoundDecl());
2808
2809 if (MightBeImplicitMember)
2810 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2811 R, TemplateArgs, S);
2812 }
2813
2814 if (TemplateArgs || TemplateKWLoc.isValid()) {
2815
2816 // In C++1y, if this is a variable template id, then check it
2817 // in BuildTemplateIdExpr().
2818 // The single lookup result must be a variable template declaration.
2819 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2820 Id.TemplateId->Kind == TNK_Var_template) {
2821 assert(R.getAsSingle<VarTemplateDecl>() &&
2822 "There should only be one declaration found.");
2823 }
2824
2825 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2826 }
2827
2828 return BuildDeclarationNameExpr(SS, R, ADL);
2829}
2830
2831/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2832/// declaration name, generally during template instantiation.
2833/// There's a large number of things which don't need to be done along
2834/// this path.
2835ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2836 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2837 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2838 if (NameInfo.getName().isDependentName())
2839 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2840 NameInfo, /*TemplateArgs=*/nullptr);
2841
2842 DeclContext *DC = computeDeclContext(SS, false);
2843 if (!DC)
2844 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2845 NameInfo, /*TemplateArgs=*/nullptr);
2846
2847 if (RequireCompleteDeclContext(SS, DC))
2848 return ExprError();
2849
2850 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2851 LookupQualifiedName(R, DC);
2852
2853 if (R.isAmbiguous())
2854 return ExprError();
2855
2856 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2857 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2858 NameInfo, /*TemplateArgs=*/nullptr);
2859
2860 if (R.empty()) {
2861 // Don't diagnose problems with invalid record decl, the secondary no_member
2862 // diagnostic during template instantiation is likely bogus, e.g. if a class
2863 // is invalid because it's derived from an invalid base class, then missing
2864 // members were likely supposed to be inherited.
2865 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2866 if (CD->isInvalidDecl())
2867 return ExprError();
2868 Diag(NameInfo.getLoc(), diag::err_no_member)
2869 << NameInfo.getName() << DC << SS.getRange();
2870 return ExprError();
2871 }
2872
2873 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2874 // Diagnose a missing typename if this resolved unambiguously to a type in
2875 // a dependent context. If we can recover with a type, downgrade this to
2876 // a warning in Microsoft compatibility mode.
2877 unsigned DiagID = diag::err_typename_missing;
2878 if (RecoveryTSI && getLangOpts().MSVCCompat)
2879 DiagID = diag::ext_typename_missing;
2880 SourceLocation Loc = SS.getBeginLoc();
2881 auto D = Diag(Loc, DiagID);
2882 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2883 << SourceRange(Loc, NameInfo.getEndLoc());
2884
2885 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2886 // context.
2887 if (!RecoveryTSI)
2888 return ExprError();
2889
2890 // Only issue the fixit if we're prepared to recover.
2891 D << FixItHint::CreateInsertion(Loc, "typename ");
2892
2893 // Recover by pretending this was an elaborated type.
2894 QualType Ty = Context.getTypeDeclType(TD);
2895 TypeLocBuilder TLB;
2896 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2897
2898 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2899 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2900 QTL.setElaboratedKeywordLoc(SourceLocation());
2901 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2902
2903 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2904
2905 return ExprEmpty();
2906 }
2907
2908 // Defend against this resolving to an implicit member access. We usually
2909 // won't get here if this might be a legitimate a class member (we end up in
2910 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2911 // a pointer-to-member or in an unevaluated context in C++11.
2912 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2913 return BuildPossibleImplicitMemberExpr(SS,
2914 /*TemplateKWLoc=*/SourceLocation(),
2915 R, /*TemplateArgs=*/nullptr, S);
2916
2917 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2918}
2919
2920/// The parser has read a name in, and Sema has detected that we're currently
2921/// inside an ObjC method. Perform some additional checks and determine if we
2922/// should form a reference to an ivar.
2923///
2924/// Ideally, most of this would be done by lookup, but there's
2925/// actually quite a lot of extra work involved.
2926DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2927 IdentifierInfo *II) {
2928 SourceLocation Loc = Lookup.getNameLoc();
2929 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2930
2931 // Check for error condition which is already reported.
2932 if (!CurMethod)
2933 return DeclResult(true);
2934
2935 // There are two cases to handle here. 1) scoped lookup could have failed,
2936 // in which case we should look for an ivar. 2) scoped lookup could have
2937 // found a decl, but that decl is outside the current instance method (i.e.
2938 // a global variable). In these two cases, we do a lookup for an ivar with
2939 // this name, if the lookup sucedes, we replace it our current decl.
2940
2941 // If we're in a class method, we don't normally want to look for
2942 // ivars. But if we don't find anything else, and there's an
2943 // ivar, that's an error.
2944 bool IsClassMethod = CurMethod->isClassMethod();
2945
2946 bool LookForIvars;
2947 if (Lookup.empty())
2948 LookForIvars = true;
2949 else if (IsClassMethod)
2950 LookForIvars = false;
2951 else
2952 LookForIvars = (Lookup.isSingleResult() &&
2953 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2954 ObjCInterfaceDecl *IFace = nullptr;
2955 if (LookForIvars) {
2956 IFace = CurMethod->getClassInterface();
2957 ObjCInterfaceDecl *ClassDeclared;
2958 ObjCIvarDecl *IV = nullptr;
2959 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2960 // Diagnose using an ivar in a class method.
2961 if (IsClassMethod) {
2962 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2963 return DeclResult(true);
2964 }
2965
2966 // Diagnose the use of an ivar outside of the declaring class.
2967 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2968 !declaresSameEntity(ClassDeclared, IFace) &&
2969 !getLangOpts().DebuggerSupport)
2970 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2971
2972 // Success.
2973 return IV;
2974 }
2975 } else if (CurMethod->isInstanceMethod()) {
2976 // We should warn if a local variable hides an ivar.
2977 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2978 ObjCInterfaceDecl *ClassDeclared;
2979 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2980 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2981 declaresSameEntity(IFace, ClassDeclared))
2982 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2983 }
2984 }
2985 } else if (Lookup.isSingleResult() &&
2986 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2987 // If accessing a stand-alone ivar in a class method, this is an error.
2988 if (const ObjCIvarDecl *IV =
2989 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2990 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2991 return DeclResult(true);
2992 }
2993 }
2994
2995 // Didn't encounter an error, didn't find an ivar.
2996 return DeclResult(false);
2997}
2998
2999ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
3000 ObjCIvarDecl *IV) {
3001 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3002 assert(CurMethod && CurMethod->isInstanceMethod() &&
3003 "should not reference ivar from this context");
3004
3005 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3006 assert(IFace && "should not reference ivar from this context");
3007
3008 // If we're referencing an invalid decl, just return this as a silent
3009 // error node. The error diagnostic was already emitted on the decl.
3010 if (IV->isInvalidDecl())
3011 return ExprError();
3012
3013 // Check if referencing a field with __attribute__((deprecated)).
3014 if (DiagnoseUseOfDecl(IV, Loc))
3015 return ExprError();
3016
3017 // FIXME: This should use a new expr for a direct reference, don't
3018 // turn this into Self->ivar, just return a BareIVarExpr or something.
3019 IdentifierInfo &II = Context.Idents.get("self");
3020 UnqualifiedId SelfName;
3021 SelfName.setImplicitSelfParam(&II);
3022 CXXScopeSpec SelfScopeSpec;
3023 SourceLocation TemplateKWLoc;
3024 ExprResult SelfExpr =
3025 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3026 /*HasTrailingLParen=*/false,
3027 /*IsAddressOfOperand=*/false);
3028 if (SelfExpr.isInvalid())
3029 return ExprError();
3030
3031 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3032 if (SelfExpr.isInvalid())
3033 return ExprError();
3034
3035 MarkAnyDeclReferenced(Loc, IV, true);
3036
3037 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3038 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3039 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3040 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3041
3042 ObjCIvarRefExpr *Result = new (Context)
3043 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3044 IV->getLocation(), SelfExpr.get(), true, true);
3045
3046 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3047 if (!isUnevaluatedContext() &&
3048 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3049 getCurFunction()->recordUseOfWeak(Result);
3050 }
3051 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3052 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3053 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3054
3055 return Result;
3056}
3057
3058/// The parser has read a name in, and Sema has detected that we're currently
3059/// inside an ObjC method. Perform some additional checks and determine if we
3060/// should form a reference to an ivar. If so, build an expression referencing
3061/// that ivar.
3062ExprResult
3063Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
3064 IdentifierInfo *II, bool AllowBuiltinCreation) {
3065 // FIXME: Integrate this lookup step into LookupParsedName.
3066 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3067 if (Ivar.isInvalid())
3068 return ExprError();
3069 if (Ivar.isUsable())
3070 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3071 cast<ObjCIvarDecl>(Ivar.get()));
3072
3073 if (Lookup.empty() && II && AllowBuiltinCreation)
3074 LookupBuiltin(Lookup);
3075
3076 // Sentinel value saying that we didn't do anything special.
3077 return ExprResult(false);
3078}
3079
3080/// Cast a base object to a member's actual type.
3081///
3082/// There are two relevant checks:
3083///
3084/// C++ [class.access.base]p7:
3085///
3086/// If a class member access operator [...] is used to access a non-static
3087/// data member or non-static member function, the reference is ill-formed if
3088/// the left operand [...] cannot be implicitly converted to a pointer to the
3089/// naming class of the right operand.
3090///
3091/// C++ [expr.ref]p7:
3092///
3093/// If E2 is a non-static data member or a non-static member function, the
3094/// program is ill-formed if the class of which E2 is directly a member is an
3095/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3096///
3097/// Note that the latter check does not consider access; the access of the
3098/// "real" base class is checked as appropriate when checking the access of the
3099/// member name.
3100ExprResult
3101Sema::PerformObjectMemberConversion(Expr *From,
3102 NestedNameSpecifier *Qualifier,
3103 NamedDecl *FoundDecl,
3104 NamedDecl *Member) {
3105 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3106 if (!RD)
3107 return From;
3108
3109 QualType DestRecordType;
3110 QualType DestType;
3111 QualType FromRecordType;
3112 QualType FromType = From->getType();
3113 bool PointerConversions = false;
3114 if (isa<FieldDecl>(Member)) {
3115 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3116 auto FromPtrType = FromType->getAs<PointerType>();
3117 DestRecordType = Context.getAddrSpaceQualType(
3118 DestRecordType, FromPtrType
3119 ? FromType->getPointeeType().getAddressSpace()
3120 : FromType.getAddressSpace());
3121
3122 if (FromPtrType) {
3123 DestType = Context.getPointerType(DestRecordType);
3124 FromRecordType = FromPtrType->getPointeeType();
3125 PointerConversions = true;
3126 } else {
3127 DestType = DestRecordType;
3128 FromRecordType = FromType;
3129 }
3130 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3131 if (Method->isStatic())
3132 return From;
3133
3134 DestType = Method->getThisType();
3135 DestRecordType = DestType->getPointeeType();
3136
3137 if (FromType->getAs<PointerType>()) {
3138 FromRecordType = FromType->getPointeeType();
3139 PointerConversions = true;
3140 } else {
3141 FromRecordType = FromType;
3142 DestType = DestRecordType;
3143 }
3144
3145 LangAS FromAS = FromRecordType.getAddressSpace();
3146 LangAS DestAS = DestRecordType.getAddressSpace();
3147 if (FromAS != DestAS) {
3148 QualType FromRecordTypeWithoutAS =
3149 Context.removeAddrSpaceQualType(FromRecordType);
3150 QualType FromTypeWithDestAS =
3151 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3152 if (PointerConversions)
3153 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3154 From = ImpCastExprToType(From, FromTypeWithDestAS,
3155 CK_AddressSpaceConversion, From->getValueKind())
3156 .get();
3157 }
3158 } else {
3159 // No conversion necessary.
3160 return From;
3161 }
3162
3163 if (DestType->isDependentType() || FromType->isDependentType())
3164 return From;
3165
3166 // If the unqualified types are the same, no conversion is necessary.
3167 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3168 return From;
3169
3170 SourceRange FromRange = From->getSourceRange();
3171 SourceLocation FromLoc = FromRange.getBegin();
3172
3173 ExprValueKind VK = From->getValueKind();
3174
3175 // C++ [class.member.lookup]p8:
3176 // [...] Ambiguities can often be resolved by qualifying a name with its
3177 // class name.
3178 //
3179 // If the member was a qualified name and the qualified referred to a
3180 // specific base subobject type, we'll cast to that intermediate type
3181 // first and then to the object in which the member is declared. That allows
3182 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3183 //
3184 // class Base { public: int x; };
3185 // class Derived1 : public Base { };
3186 // class Derived2 : public Base { };
3187 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3188 //
3189 // void VeryDerived::f() {
3190 // x = 17; // error: ambiguous base subobjects
3191 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3192 // }
3193 if (Qualifier && Qualifier->getAsType()) {
3194 QualType QType = QualType(Qualifier->getAsType(), 0);
3195 assert(QType->isRecordType() && "lookup done with non-record type");
3196
3197 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3198
3199 // In C++98, the qualifier type doesn't actually have to be a base
3200 // type of the object type, in which case we just ignore it.
3201 // Otherwise build the appropriate casts.
3202 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3203 CXXCastPath BasePath;
3204 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3205 FromLoc, FromRange, &BasePath))
3206 return ExprError();
3207
3208 if (PointerConversions)
3209 QType = Context.getPointerType(QType);
3210 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3211 VK, &BasePath).get();
3212
3213 FromType = QType;
3214 FromRecordType = QRecordType;
3215
3216 // If the qualifier type was the same as the destination type,
3217 // we're done.
3218 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3219 return From;
3220 }
3221 }
3222
3223 CXXCastPath BasePath;
3224 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3225 FromLoc, FromRange, &BasePath,
3226 /*IgnoreAccess=*/true))
3227 return ExprError();
3228
3229 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3230 VK, &BasePath);
3231}
3232
3233bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3234 const LookupResult &R,
3235 bool HasTrailingLParen) {
3236 // Only when used directly as the postfix-expression of a call.
3237 if (!HasTrailingLParen)
3238 return false;
3239
3240 // Never if a scope specifier was provided.
3241 if (SS.isSet())
3242 return false;
3243
3244 // Only in C++ or ObjC++.
3245 if (!getLangOpts().CPlusPlus)
3246 return false;
3247
3248 // Turn off ADL when we find certain kinds of declarations during
3249 // normal lookup:
3250 for (const NamedDecl *D : R) {
3251 // C++0x [basic.lookup.argdep]p3:
3252 // -- a declaration of a class member
3253 // Since using decls preserve this property, we check this on the
3254 // original decl.
3255 if (D->isCXXClassMember())
3256 return false;
3257
3258 // C++0x [basic.lookup.argdep]p3:
3259 // -- a block-scope function declaration that is not a
3260 // using-declaration
3261 // NOTE: we also trigger this for function templates (in fact, we
3262 // don't check the decl type at all, since all other decl types
3263 // turn off ADL anyway).
3264 if (isa<UsingShadowDecl>(D))
3265 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3266 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3267 return false;
3268
3269 // C++0x [basic.lookup.argdep]p3:
3270 // -- a declaration that is neither a function or a function
3271 // template
3272 // And also for builtin functions.
3273 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3274 // But also builtin functions.
3275 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3276 return false;
3277 } else if (!isa<FunctionTemplateDecl>(D))
3278 return false;
3279 }
3280
3281 return true;
3282}
3283
3284
3285/// Diagnoses obvious problems with the use of the given declaration
3286/// as an expression. This is only actually called for lookups that
3287/// were not overloaded, and it doesn't promise that the declaration
3288/// will in fact be used.
3289static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3290 bool AcceptInvalid) {
3291 if (D->isInvalidDecl() && !AcceptInvalid)
3292 return true;
3293
3294 if (isa<TypedefNameDecl>(D)) {
3295 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3296 return true;
3297 }
3298
3299 if (isa<ObjCInterfaceDecl>(D)) {
3300 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3301 return true;
3302 }
3303
3304 if (isa<NamespaceDecl>(D)) {
3305 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3306 return true;
3307 }
3308
3309 return false;
3310}
3311
3312// Certain multiversion types should be treated as overloaded even when there is
3313// only one result.
3314static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3315 assert(R.isSingleResult() && "Expected only a single result");
3316 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3317 return FD &&
3318 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3319}
3320
3321ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3322 LookupResult &R, bool NeedsADL,
3323 bool AcceptInvalidDecl) {
3324 // If this is a single, fully-resolved result and we don't need ADL,
3325 // just build an ordinary singleton decl ref.
3326 if (!NeedsADL && R.isSingleResult() &&
3327 !R.getAsSingle<FunctionTemplateDecl>() &&
3328 !ShouldLookupResultBeMultiVersionOverload(R))
3329 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3330 R.getRepresentativeDecl(), nullptr,
3331 AcceptInvalidDecl);
3332
3333 // We only need to check the declaration if there's exactly one
3334 // result, because in the overloaded case the results can only be
3335 // functions and function templates.
3336 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3337 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3338 AcceptInvalidDecl))
3339 return ExprError();
3340
3341 // Otherwise, just build an unresolved lookup expression. Suppress
3342 // any lookup-related diagnostics; we'll hash these out later, when
3343 // we've picked a target.
3344 R.suppressDiagnostics();
3345
3346 UnresolvedLookupExpr *ULE
3347 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3348 SS.getWithLocInContext(Context),
3349 R.getLookupNameInfo(),
3350 NeedsADL, R.isOverloadedResult(),
3351 R.begin(), R.end());
3352
3353 return ULE;
3354}
3355
3356static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3357 SourceLocation loc,
3358 ValueDecl *var);
3359
3360/// Complete semantic analysis for a reference to the given declaration.
3361ExprResult Sema::BuildDeclarationNameExpr(
3362 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3363 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3364 bool AcceptInvalidDecl) {
3365 assert(D && "Cannot refer to a NULL declaration");
3366 assert(!isa<FunctionTemplateDecl>(D) &&
3367 "Cannot refer unambiguously to a function template");
3368
3369 SourceLocation Loc = NameInfo.getLoc();
3370 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3371 // Recovery from invalid cases (e.g. D is an invalid Decl).
3372 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3373 // diagnostics, as invalid decls use int as a fallback type.
3374 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3375 }
3376
3377 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3378 // Specifically diagnose references to class templates that are missing
3379 // a template argument list.
3380 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3381 return ExprError();
3382 }
3383
3384 // Make sure that we're referring to a value.
3385 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3386 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3387 Diag(D->getLocation(), diag::note_declared_at);
3388 return ExprError();
3389 }
3390
3391 // Check whether this declaration can be used. Note that we suppress
3392 // this check when we're going to perform argument-dependent lookup
3393 // on this function name, because this might not be the function
3394 // that overload resolution actually selects.
3395 if (DiagnoseUseOfDecl(D, Loc))
3396 return ExprError();
3397
3398 auto *VD = cast<ValueDecl>(D);
3399
3400 // Only create DeclRefExpr's for valid Decl's.
3401 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3402 return ExprError();
3403
3404 // Handle members of anonymous structs and unions. If we got here,
3405 // and the reference is to a class member indirect field, then this
3406 // must be the subject of a pointer-to-member expression.
3407 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3408 IndirectField && !IndirectField->isCXXClassMember())
3409 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3410 IndirectField);
3411
3412 QualType type = VD->getType();
3413 if (type.isNull())
3414 return ExprError();
3415 ExprValueKind valueKind = VK_PRValue;
3416
3417 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3418 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3419 // is expanded by some outer '...' in the context of the use.
3420 type = type.getNonPackExpansionType();
3421
3422 switch (D->getKind()) {
3423 // Ignore all the non-ValueDecl kinds.
3424#define ABSTRACT_DECL(kind)
3425#define VALUE(type, base)
3426#define DECL(type, base) case Decl::type:
3427#include "clang/AST/DeclNodes.inc"
3428 llvm_unreachable("invalid value decl kind");
3429
3430 // These shouldn't make it here.
3431 case Decl::ObjCAtDefsField:
3432 llvm_unreachable("forming non-member reference to ivar?");
3433
3434 // Enum constants are always r-values and never references.
3435 // Unresolved using declarations are dependent.
3436 case Decl::EnumConstant:
3437 case Decl::UnresolvedUsingValue:
3438 case Decl::OMPDeclareReduction:
3439 case Decl::OMPDeclareMapper:
3440 valueKind = VK_PRValue;
3441 break;
3442
3443 // Fields and indirect fields that got here must be for
3444 // pointer-to-member expressions; we just call them l-values for
3445 // internal consistency, because this subexpression doesn't really
3446 // exist in the high-level semantics.
3447 case Decl::Field:
3448 case Decl::IndirectField:
3449 case Decl::ObjCIvar:
3450 assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3451
3452 // These can't have reference type in well-formed programs, but
3453 // for internal consistency we do this anyway.
3454 type = type.getNonReferenceType();
3455 valueKind = VK_LValue;
3456 break;
3457
3458 // Non-type template parameters are either l-values or r-values
3459 // depending on the type.
3460 case Decl::NonTypeTemplateParm: {
3461 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3462 type = reftype->getPointeeType();
3463 valueKind = VK_LValue; // even if the parameter is an r-value reference
3464 break;
3465 }
3466
3467 // [expr.prim.id.unqual]p2:
3468 // If the entity is a template parameter object for a template
3469 // parameter of type T, the type of the expression is const T.
3470 // [...] The expression is an lvalue if the entity is a [...] template
3471 // parameter object.
3472 if (type->isRecordType()) {
3473 type = type.getUnqualifiedType().withConst();
3474 valueKind = VK_LValue;
3475 break;
3476 }
3477
3478 // For non-references, we need to strip qualifiers just in case
3479 // the template parameter was declared as 'const int' or whatever.
3480 valueKind = VK_PRValue;
3481 type = type.getUnqualifiedType();
3482 break;
3483 }
3484
3485 case Decl::Var:
3486 case Decl::VarTemplateSpecialization:
3487 case Decl::VarTemplatePartialSpecialization:
3488 case Decl::Decomposition:
3489 case Decl::OMPCapturedExpr:
3490 // In C, "extern void blah;" is valid and is an r-value.
3491 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3492 type->isVoidType()) {
3493 valueKind = VK_PRValue;
3494 break;
3495 }
3496 [[fallthrough]];
3497
3498 case Decl::ImplicitParam:
3499 case Decl::ParmVar: {
3500 // These are always l-values.
3501 valueKind = VK_LValue;
3502 type = type.getNonReferenceType();
3503
3504 // FIXME: Does the addition of const really only apply in
3505 // potentially-evaluated contexts? Since the variable isn't actually
3506 // captured in an unevaluated context, it seems that the answer is no.
3507 if (!isUnevaluatedContext()) {
3508 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3509 if (!CapturedType.isNull())
3510 type = CapturedType;
3511 }
3512
3513 break;
3514 }
3515
3516 case Decl::Binding:
3517 // These are always lvalues.
3518 valueKind = VK_LValue;
3519 type = type.getNonReferenceType();
3520 break;
3521
3522 case Decl::Function: {
3523 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3524 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3525 type = Context.BuiltinFnTy;
3526 valueKind = VK_PRValue;
3527 break;
3528 }
3529 }
3530
3531 const FunctionType *fty = type->castAs<FunctionType>();
3532
3533 // If we're referring to a function with an __unknown_anytype
3534 // result type, make the entire expression __unknown_anytype.
3535 if (fty->getReturnType() == Context.UnknownAnyTy) {
3536 type = Context.UnknownAnyTy;
3537 valueKind = VK_PRValue;
3538 break;
3539 }
3540
3541 // Functions are l-values in C++.
3542 if (getLangOpts().CPlusPlus) {
3543 valueKind = VK_LValue;
3544 break;
3545 }
3546
3547 // C99 DR 316 says that, if a function type comes from a
3548 // function definition (without a prototype), that type is only
3549 // used for checking compatibility. Therefore, when referencing
3550 // the function, we pretend that we don't have the full function
3551 // type.
3552 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3553 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3554 fty->getExtInfo());
3555
3556 // Functions are r-values in C.
3557 valueKind = VK_PRValue;
3558 break;
3559 }
3560
3561 case Decl::CXXDeductionGuide:
3562 llvm_unreachable("building reference to deduction guide");
3563
3564 case Decl::MSProperty:
3565 case Decl::MSGuid:
3566 case Decl::TemplateParamObject:
3567 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3568 // capture in OpenMP, or duplicated between host and device?
3569 valueKind = VK_LValue;
3570 break;
3571
3572 case Decl::UnnamedGlobalConstant:
3573 valueKind = VK_LValue;
3574 break;
3575
3576 case Decl::CXXMethod:
3577 // If we're referring to a method with an __unknown_anytype
3578 // result type, make the entire expression __unknown_anytype.
3579 // This should only be possible with a type written directly.
3580 if (const FunctionProtoType *proto =
3581 dyn_cast<FunctionProtoType>(VD->getType()))
3582 if (proto->getReturnType() == Context.UnknownAnyTy) {
3583 type = Context.UnknownAnyTy;
3584 valueKind = VK_PRValue;
3585 break;
3586 }
3587
3588 // C++ methods are l-values if static, r-values if non-static.
3589 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3590 valueKind = VK_LValue;
3591 break;
3592 }
3593 [[fallthrough]];
3594
3595 case Decl::CXXConversion:
3596 case Decl::CXXDestructor:
3597 case Decl::CXXConstructor:
3598 valueKind = VK_PRValue;
3599 break;
3600 }
3601
3602 auto *E =
3603 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3604 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3605 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3606 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3607 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3608 // diagnostics).
3609 if (VD->isInvalidDecl() && E)
3610 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3611 return E;
3612}
3613
3614static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3615 SmallString<32> &Target) {
3616 Target.resize(CharByteWidth * (Source.size() + 1));
3617 char *ResultPtr = &Target[0];
3618 const llvm::UTF8 *ErrorPtr;
3619 bool success =
3620 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3621 (void)success;
3622 assert(success);
3623 Target.resize(ResultPtr - &Target[0]);
3624}
3625
3626ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3627 PredefinedExpr::IdentKind IK) {
3628 // Pick the current block, lambda, captured statement or function.
3629 Decl *currentDecl = nullptr;
3630 if (const BlockScopeInfo *BSI = getCurBlock())
3631 currentDecl = BSI->TheDecl;
3632 else if (const LambdaScopeInfo *LSI = getCurLambda())
3633 currentDecl = LSI->CallOperator;
3634 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3635 currentDecl = CSI->TheCapturedDecl;
3636 else
3637 currentDecl = getCurFunctionOrMethodDecl();
3638
3639 if (!currentDecl) {
3640 Diag(Loc, diag::ext_predef_outside_function);
3641 currentDecl = Context.getTranslationUnitDecl();
3642 }
3643
3644 QualType ResTy;
3645 StringLiteral *SL = nullptr;
3646 if (cast<DeclContext>(currentDecl)->isDependentContext())
3647 ResTy = Context.DependentTy;
3648 else {
3649 // Pre-defined identifiers are of type char[x], where x is the length of
3650 // the string.
3651 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3652 unsigned Length = Str.length();
3653
3654 llvm::APInt LengthI(32, Length + 1);
3655 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3656 ResTy =
3657 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3658 SmallString<32> RawChars;
3659 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3660 Str, RawChars);
3661 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3662 ArrayType::Normal,
3663 /*IndexTypeQuals*/ 0);
3664 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3665 /*Pascal*/ false, ResTy, Loc);
3666 } else {
3667 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3668 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3669 ArrayType::Normal,
3670 /*IndexTypeQuals*/ 0);
3671 SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary,
3672 /*Pascal*/ false, ResTy, Loc);
3673 }
3674 }
3675
3676 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3677 SL);
3678}
3679
3680ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3681 SourceLocation LParen,
3682 SourceLocation RParen,
3683 TypeSourceInfo *TSI) {
3684 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3685}
3686
3687ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3688 SourceLocation LParen,
3689 SourceLocation RParen,
3690 ParsedType ParsedTy) {
3691 TypeSourceInfo *TSI = nullptr;
3692 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3693
3694 if (Ty.isNull())
3695 return ExprError();
3696 if (!TSI)
3697 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3698
3699 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3700}
3701
3702ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3703 PredefinedExpr::IdentKind IK;
3704
3705 switch (Kind) {
3706 default: llvm_unreachable("Unknown simple primary expr!");
3707 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3708 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3709 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3710 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3711 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3712 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3713 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3714 }
3715
3716 return BuildPredefinedExpr(Loc, IK);
3717}
3718
3719ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3720 SmallString<16> CharBuffer;
3721 bool Invalid = false;
3722 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3723 if (Invalid)
3724 return ExprError();
3725
3726 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3727 PP, Tok.getKind());
3728 if (Literal.hadError())
3729 return ExprError();
3730
3731 QualType Ty;
3732 if (Literal.isWide())
3733 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3734 else if (Literal.isUTF8() && getLangOpts().C2x)
3735 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3736 else if (Literal.isUTF8() && getLangOpts().Char8)
3737 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3738 else if (Literal.isUTF16())
3739 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3740 else if (Literal.isUTF32())
3741 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3742 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3743 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3744 else
3745 Ty = Context.CharTy; // 'x' -> char in C++;
3746 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3747
3748 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3749 if (Literal.isWide())
3750 Kind = CharacterLiteral::Wide;
3751 else if (Literal.isUTF16())
3752 Kind = CharacterLiteral::UTF16;
3753 else if (Literal.isUTF32())
3754 Kind = CharacterLiteral::UTF32;
3755 else if (Literal.isUTF8())
3756 Kind = CharacterLiteral::UTF8;
3757
3758 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3759 Tok.getLocation());
3760
3761 if (Literal.getUDSuffix().empty())
3762 return Lit;
3763
3764 // We're building a user-defined literal.
3765 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3766 SourceLocation UDSuffixLoc =
3767 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3768
3769 // Make sure we're allowed user-defined literals here.
3770 if (!UDLScope)
3771 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3772
3773 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3774 // operator "" X (ch)
3775 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3776 Lit, Tok.getLocation());
3777}
3778
3779ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3780 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3781 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3782 Context.IntTy, Loc);
3783}
3784
3785static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3786 QualType Ty, SourceLocation Loc) {
3787 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3788
3789 using llvm::APFloat;
3790 APFloat Val(Format);
3791
3792 APFloat::opStatus result = Literal.GetFloatValue(Val);
3793
3794 // Overflow is always an error, but underflow is only an error if
3795 // we underflowed to zero (APFloat reports denormals as underflow).
3796 if ((result & APFloat::opOverflow) ||
3797 ((result & APFloat::opUnderflow) && Val.isZero())) {
3798 unsigned diagnostic;
3799 SmallString<20> buffer;
3800 if (result & APFloat::opOverflow) {
3801 diagnostic = diag::warn_float_overflow;
3802 APFloat::getLargest(Format).toString(buffer);
3803 } else {
3804 diagnostic = diag::warn_float_underflow;
3805 APFloat::getSmallest(Format).toString(buffer);
3806 }
3807
3808 S.Diag(Loc, diagnostic)
3809 << Ty
3810 << StringRef(buffer.data(), buffer.size());
3811 }
3812
3813 bool isExact = (result == APFloat::opOK);
3814 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3815}
3816
3817bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3818 assert(E && "Invalid expression");
3819
3820 if (E->isValueDependent())
3821 return false;
3822
3823 QualType QT = E->getType();
3824 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3825 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3826 return true;
3827 }
3828
3829 llvm::APSInt ValueAPS;
3830 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3831
3832 if (R.isInvalid())
3833 return true;
3834
3835 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3836 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3837 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3838 << toString(ValueAPS, 10) << ValueIsPositive;
3839 return true;
3840 }
3841
3842 return false;
3843}
3844
3845ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3846 // Fast path for a single digit (which is quite common). A single digit
3847 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3848 if (Tok.getLength() == 1) {
3849 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3850 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3851 }
3852
3853 SmallString<128> SpellingBuffer;
3854 // NumericLiteralParser wants to overread by one character. Add padding to
3855 // the buffer in case the token is copied to the buffer. If getSpelling()
3856 // returns a StringRef to the memory buffer, it should have a null char at
3857 // the EOF, so it is also safe.
3858 SpellingBuffer.resize(Tok.getLength() + 1);
3859
3860 // Get the spelling of the token, which eliminates trigraphs, etc.
3861 bool Invalid = false;
3862 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3863 if (Invalid)
3864 return ExprError();
3865
3866 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3867 PP.getSourceManager(), PP.getLangOpts(),
3868 PP.getTargetInfo(), PP.getDiagnostics());
3869 if (Literal.hadError)
3870 return ExprError();
3871
3872 if (Literal.hasUDSuffix()) {
3873 // We're building a user-defined literal.
3874 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3875 SourceLocation UDSuffixLoc =
3876 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3877
3878 // Make sure we're allowed user-defined literals here.
3879 if (!UDLScope)
3880 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3881
3882 QualType CookedTy;
3883 if (Literal.isFloatingLiteral()) {
3884 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3885 // long double, the literal is treated as a call of the form
3886 // operator "" X (f L)
3887 CookedTy = Context.LongDoubleTy;
3888 } else {
3889 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3890 // unsigned long long, the literal is treated as a call of the form
3891 // operator "" X (n ULL)
3892 CookedTy = Context.UnsignedLongLongTy;
3893 }
3894
3895 DeclarationName OpName =
3896 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3897 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3898 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3899
3900 SourceLocation TokLoc = Tok.getLocation();
3901
3902 // Perform literal operator lookup to determine if we're building a raw
3903 // literal or a cooked one.
3904 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3905 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3906 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3907 /*AllowStringTemplatePack*/ false,
3908 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3909 case LOLR_ErrorNoDiagnostic:
3910 // Lookup failure for imaginary constants isn't fatal, there's still the
3911 // GNU extension producing _Complex types.
3912 break;
3913 case LOLR_Error:
3914 return ExprError();
3915 case LOLR_Cooked: {
3916 Expr *Lit;
3917 if (Literal.isFloatingLiteral()) {
3918 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3919 } else {
3920 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3921 if (Literal.GetIntegerValue(ResultVal))
3922 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3923 << /* Unsigned */ 1;
3924 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3925 Tok.getLocation());
3926 }
3927 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3928 }
3929
3930 case LOLR_Raw: {
3931 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3932 // literal is treated as a call of the form
3933 // operator "" X ("n")
3934 unsigned Length = Literal.getUDSuffixOffset();
3935 QualType StrTy = Context.getConstantArrayType(
3936 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3937 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3938 Expr *Lit =
3939 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3940 StringLiteral::Ordinary,
3941 /*Pascal*/ false, StrTy, &TokLoc, 1);
3942 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3943 }
3944
3945 case LOLR_Template: {
3946 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3947 // template), L is treated as a call fo the form
3948 // operator "" X <'c1', 'c2', ... 'ck'>()
3949 // where n is the source character sequence c1 c2 ... ck.
3950 TemplateArgumentListInfo ExplicitArgs;
3951 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3952 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3953 llvm::APSInt Value(CharBits, CharIsUnsigned);
3954 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3955 Value = TokSpelling[I];
3956 TemplateArgument Arg(Context, Value, Context.CharTy);
3957 TemplateArgumentLocInfo ArgInfo;
3958 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3959 }
3960 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3961 &ExplicitArgs);
3962 }
3963 case LOLR_StringTemplatePack:
3964 llvm_unreachable("unexpected literal operator lookup result");
3965 }
3966 }
3967
3968 Expr *Res;
3969
3970 if (Literal.isFixedPointLiteral()) {
3971 QualType Ty;
3972
3973 if (Literal.isAccum) {
3974 if (Literal.isHalf) {
3975 Ty = Context.ShortAccumTy;
3976 } else if (Literal.isLong) {
3977 Ty = Context.LongAccumTy;
3978 } else {
3979 Ty = Context.AccumTy;
3980 }
3981 } else if (Literal.isFract) {
3982 if (Literal.isHalf) {
3983 Ty = Context.ShortFractTy;
3984 } else if (Literal.isLong) {
3985 Ty = Context.LongFractTy;
3986 } else {
3987 Ty = Context.FractTy;
3988 }
3989 }
3990
3991 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3992
3993 bool isSigned = !Literal.isUnsigned;
3994 unsigned scale = Context.getFixedPointScale(Ty);
3995 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3996
3997 llvm::APInt Val(bit_width, 0, isSigned);
3998 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3999 bool ValIsZero = Val.isZero() && !Overflowed;
4000
4001 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4002 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4003 // Clause 6.4.4 - The value of a constant shall be in the range of
4004 // representable values for its type, with exception for constants of a
4005 // fract type with a value of exactly 1; such a constant shall denote
4006 // the maximal value for the type.
4007 --Val;
4008 else if (Val.ugt(MaxVal) || Overflowed)
4009 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4010
4011 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
4012 Tok.getLocation(), scale);
4013 } else if (Literal.isFloatingLiteral()) {
4014 QualType Ty;
4015 if (Literal.isHalf){
4016 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4017 Ty = Context.HalfTy;
4018 else {
4019 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4020 return ExprError();
4021 }
4022 } else if (Literal.isFloat)
4023 Ty = Context.FloatTy;
4024 else if (Literal.isLong)
4025 Ty = Context.LongDoubleTy;
4026 else if (Literal.isFloat16)
4027 Ty = Context.Float16Ty;
4028 else if (Literal.isFloat128)
4029 Ty = Context.Float128Ty;
4030 else
4031 Ty = Context.DoubleTy;
4032
4033 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4034
4035 if (Ty == Context.DoubleTy) {
4036 if (getLangOpts().SinglePrecisionConstants) {
4037 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4038 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4039 }
4040 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4041 "cl_khr_fp64", getLangOpts())) {
4042 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4043 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4044 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4045 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4046 }
4047 }
4048 } else if (!Literal.isIntegerLiteral()) {
4049 return ExprError();
4050 } else {
4051 QualType Ty;
4052
4053 // 'z/uz' literals are a C++23 feature.
4054 if (Literal.isSizeT)
4055 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4056 ? getLangOpts().CPlusPlus23
4057 ? diag::warn_cxx20_compat_size_t_suffix
4058 : diag::ext_cxx23_size_t_suffix
4059 : diag::err_cxx23_size_t_suffix);
4060
4061 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
4062 // but we do not currently support the suffix in C++ mode because it's not
4063 // entirely clear whether WG21 will prefer this suffix to return a library
4064 // type such as std::bit_int instead of returning a _BitInt.
4065 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
4066 PP.Diag(Tok.getLocation(), getLangOpts().C2x
4067 ? diag::warn_c2x_compat_bitint_suffix
4068 : diag::ext_c2x_bitint_suffix);
4069
4070 // Get the value in the widest-possible width. What is "widest" depends on
4071 // whether the literal is a bit-precise integer or not. For a bit-precise
4072 // integer type, try to scan the source to determine how many bits are
4073 // needed to represent the value. This may seem a bit expensive, but trying
4074 // to get the integer value from an overly-wide APInt is *extremely*
4075 // expensive, so the naive approach of assuming
4076 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4077 unsigned BitsNeeded =
4078 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4079 Literal.getLiteralDigits(), Literal.getRadix())
4080 : Context.getTargetInfo().getIntMaxTWidth();
4081 llvm::APInt ResultVal(BitsNeeded, 0);
4082
4083 if (Literal.GetIntegerValue(ResultVal)) {
4084 // If this value didn't fit into uintmax_t, error and force to ull.
4085 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4086 << /* Unsigned */ 1;
4087 Ty = Context.UnsignedLongLongTy;
4088 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4089 "long long is not intmax_t?");
4090 } else {
4091 // If this value fits into a ULL, try to figure out what else it fits into
4092 // according to the rules of C99 6.4.4.1p5.
4093
4094 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4095 // be an unsigned int.
4096 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4097
4098 // Check from smallest to largest, picking the smallest type we can.
4099 unsigned Width = 0;
4100
4101 // Microsoft specific integer suffixes are explicitly sized.
4102 if (Literal.MicrosoftInteger) {
4103 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4104 Width = 8;
4105 Ty = Context.CharTy;
4106 } else {
4107 Width = Literal.MicrosoftInteger;
4108 Ty = Context.getIntTypeForBitwidth(Width,
4109 /*Signed=*/!Literal.isUnsigned);
4110 }
4111 }
4112
4113 // Bit-precise integer literals are automagically-sized based on the
4114 // width required by the literal.
4115 if (Literal.isBitInt) {
4116 // The signed version has one more bit for the sign value. There are no
4117 // zero-width bit-precise integers, even if the literal value is 0.
4118 Width = std::max(ResultVal.getActiveBits(), 1u) +
4119 (Literal.isUnsigned ? 0u : 1u);
4120
4121 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4122 // and reset the type to the largest supported width.
4123 unsigned int MaxBitIntWidth =
4124 Context.getTargetInfo().getMaxBitIntWidth();
4125 if (Width > MaxBitIntWidth) {
4126 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4127 << Literal.isUnsigned;
4128 Width = MaxBitIntWidth;
4129 }
4130
4131 // Reset the result value to the smaller APInt and select the correct
4132 // type to be used. Note, we zext even for signed values because the
4133 // literal itself is always an unsigned value (a preceeding - is a
4134 // unary operator, not part of the literal).
4135 ResultVal = ResultVal.zextOrTrunc(Width);
4136 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4137 }
4138
4139 // Check C++23 size_t literals.
4140 if (Literal.isSizeT) {
4141 assert(!Literal.MicrosoftInteger &&
4142 "size_t literals can't be Microsoft literals");
4143 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4144 Context.getTargetInfo().getSizeType());
4145
4146 // Does it fit in size_t?
4147 if (ResultVal.isIntN(SizeTSize)) {
4148 // Does it fit in ssize_t?
4149 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4150 Ty = Context.getSignedSizeType();
4151 else if (AllowUnsigned)
4152 Ty = Context.getSizeType();
4153 Width = SizeTSize;
4154 }
4155 }
4156
4157 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4158 !Literal.isSizeT) {
4159 // Are int/unsigned possibilities?
4160 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4161
4162 // Does it fit in a unsigned int?
4163 if (ResultVal.isIntN(IntSize)) {
4164 // Does it fit in a signed int?
4165 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4166 Ty = Context.IntTy;
4167 else if (AllowUnsigned)
4168 Ty = Context.UnsignedIntTy;
4169 Width = IntSize;
4170 }
4171 }
4172
4173 // Are long/unsigned long possibilities?
4174 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4175 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4176
4177 // Does it fit in a unsigned long?
4178 if (ResultVal.isIntN(LongSize)) {
4179 // Does it fit in a signed long?
4180 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4181 Ty = Context.LongTy;
4182 else if (AllowUnsigned)
4183 Ty = Context.UnsignedLongTy;
4184 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4185 // is compatible.
4186 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4187 const unsigned LongLongSize =
4188 Context.getTargetInfo().getLongLongWidth();
4189 Diag(Tok.getLocation(),
4190 getLangOpts().CPlusPlus
4191 ? Literal.isLong
4192 ? diag::warn_old_implicitly_unsigned_long_cxx
4193 : /*C++98 UB*/ diag::
4194 ext_old_implicitly_unsigned_long_cxx
4195 : diag::warn_old_implicitly_unsigned_long)
4196 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4197 : /*will be ill-formed*/ 1);
4198 Ty = Context.UnsignedLongTy;
4199 }
4200 Width = LongSize;
4201 }
4202 }
4203
4204 // Check long long if needed.
4205 if (Ty.isNull() && !Literal.isSizeT) {
4206 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4207
4208 // Does it fit in a unsigned long long?
4209 if (ResultVal.isIntN(LongLongSize)) {
4210 // Does it fit in a signed long long?
4211 // To be compatible with MSVC, hex integer literals ending with the
4212 // LL or i64 suffix are always signed in Microsoft mode.
4213 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4214 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4215 Ty = Context.LongLongTy;
4216 else if (AllowUnsigned)
4217 Ty = Context.UnsignedLongLongTy;
4218 Width = LongLongSize;
4219
4220 // 'long long' is a C99 or C++11 feature, whether the literal
4221 // explicitly specified 'long long' or we needed the extra width.
4222 if (getLangOpts().CPlusPlus)
4223 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4224 ? diag::warn_cxx98_compat_longlong
4225 : diag::ext_cxx11_longlong);
4226 else if (!getLangOpts().C99)
4227 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4228 }
4229 }
4230
4231 // If we still couldn't decide a type, we either have 'size_t' literal
4232 // that is out of range, or a decimal literal that does not fit in a
4233 // signed long long and has no U suffix.
4234 if (Ty.isNull()) {
4235 if (Literal.isSizeT)
4236 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4237 << Literal.isUnsigned;
4238 else
4239 Diag(Tok.getLocation(),
4240 diag::ext_integer_literal_too_large_for_signed);
4241 Ty = Context.UnsignedLongLongTy;
4242 Width = Context.getTargetInfo().getLongLongWidth();
4243 }
4244
4245 if (ResultVal.getBitWidth() != Width)
4246 ResultVal = ResultVal.trunc(Width);
4247 }
4248 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4249 }
4250
4251 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4252 if (Literal.isImaginary) {
4253 Res = new (Context) ImaginaryLiteral(Res,
4254 Context.getComplexType(Res->getType()));
4255
4256 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4257 }
4258 return Res;
4259}
4260
4261ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4262 assert(E && "ActOnParenExpr() missing expr");
4263 QualType ExprTy = E->getType();
4264 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4265 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4266 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4267 return new (Context) ParenExpr(L, R, E);
4268}
4269
4270static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4271 SourceLocation Loc,
4272 SourceRange ArgRange) {
4273 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4274 // scalar or vector data type argument..."
4275 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4276 // type (C99 6.2.5p18) or void.
4277 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4278 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4279 << T << ArgRange;
4280 return true;
4281 }
4282
4283 assert((T->isVoidType() || !T->isIncompleteType()) &&
4284 "Scalar types should always be complete");
4285 return false;
4286}
4287
4288static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4289 SourceLocation Loc,
4290 SourceRange ArgRange,
4291 UnaryExprOrTypeTrait TraitKind) {
4292 // Invalid types must be hard errors for SFINAE in C++.
4293 if (S.LangOpts.CPlusPlus)
4294 return true;
4295
4296 // C99 6.5.3.4p1:
4297 if (T->isFunctionType() &&
4298 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4299 TraitKind == UETT_PreferredAlignOf)) {
4300 // sizeof(function)/alignof(function) is allowed as an extension.
4301 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4302 << getTraitSpelling(TraitKind) << ArgRange;
4303 return false;
4304 }
4305
4306 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4307 // this is an error (OpenCL v1.1 s6.3.k)
4308 if (T->isVoidType()) {
4309 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4310 : diag::ext_sizeof_alignof_void_type;
4311 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4312 return false;
4313 }
4314
4315 return true;
4316}
4317
4318static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4319 SourceLocation Loc,
4320 SourceRange ArgRange,
4321 UnaryExprOrTypeTrait TraitKind) {
4322 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4323 // runtime doesn't allow it.
4324 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4325 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4326 << T << (TraitKind == UETT_SizeOf)
4327 << ArgRange;
4328 return true;
4329 }
4330
4331 return false;
4332}
4333
4334/// Check whether E is a pointer from a decayed array type (the decayed
4335/// pointer type is equal to T) and emit a warning if it is.
4336static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4337 const Expr *E) {
4338 // Don't warn if the operation changed the type.
4339 if (T != E->getType())
4340 return;
4341
4342 // Now look for array decays.
4343 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4344 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4345 return;
4346
4347 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4348 << ICE->getType()
4349 << ICE->getSubExpr()->getType();
4350}
4351
4352/// Check the constraints on expression operands to unary type expression
4353/// and type traits.
4354///
4355/// Completes any types necessary and validates the constraints on the operand
4356/// expression. The logic mostly mirrors the type-based overload, but may modify
4357/// the expression as it completes the type for that expression through template
4358/// instantiation, etc.
4359bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4360 UnaryExprOrTypeTrait ExprKind) {
4361 QualType ExprTy = E->getType();
4362 assert(!ExprTy->isReferenceType());
4363
4364 bool IsUnevaluatedOperand =
4365 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4366 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4367 if (IsUnevaluatedOperand) {
4368 ExprResult Result = CheckUnevaluatedOperand(E);
4369 if (Result.isInvalid())
4370 return true;
4371 E = Result.get();
4372 }
4373
4374 // The operand for sizeof and alignof is in an unevaluated expression context,
4375 // so side effects could result in unintended consequences.
4376 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4377 // used to build SFINAE gadgets.
4378 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4379 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4380 !E->isInstantiationDependent() &&
4381 !E->getType()->isVariableArrayType() &&
4382 E->HasSideEffects(Context, false))
4383 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4384
4385 if (ExprKind == UETT_VecStep)
4386 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4387 E->getSourceRange());
4388
4389 // Explicitly list some types as extensions.
4390 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4391 E->getSourceRange(), ExprKind))
4392 return false;
4393
4394 // WebAssembly tables are always illegal operands to unary expressions and
4395 // type traits.
4396 if (Context.getTargetInfo().getTriple().isWasm() &&
4397 E->getType()->isWebAssemblyTableType()) {
4398 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4399 << getTraitSpelling(ExprKind);
4400 return true;
4401 }
4402
4403 // 'alignof' applied to an expression only requires the base element type of
4404 // the expression to be complete. 'sizeof' requires the expression's type to
4405 // be complete (and will attempt to complete it if it's an array of unknown
4406 // bound).
4407 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4408 if (RequireCompleteSizedType(
4409 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4410 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4411 getTraitSpelling(ExprKind), E->getSourceRange()))
4412 return true;
4413 } else {
4414 if (RequireCompleteSizedExprType(
4415 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4416 getTraitSpelling(ExprKind), E->getSourceRange()))
4417 return true;
4418 }
4419
4420 // Completing the expression's type may have changed it.
4421 ExprTy = E->getType();
4422 assert(!ExprTy->isReferenceType());
4423
4424 if (ExprTy->isFunctionType()) {
4425 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4426 << getTraitSpelling(ExprKind) << E->getSourceRange();
4427 return true;
4428 }
4429
4430 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4431 E->getSourceRange(), ExprKind))
4432 return true;
4433
4434 if (ExprKind == UETT_SizeOf) {
4435 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4436 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4437 QualType OType = PVD->getOriginalType();
4438 QualType Type = PVD->getType();
4439 if (Type->isPointerType() && OType->isArrayType()) {
4440 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4441 << Type << OType;
4442 Diag(PVD->getLocation(), diag::note_declared_at);
4443 }
4444 }
4445 }
4446
4447 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4448 // decays into a pointer and returns an unintended result. This is most
4449 // likely a typo for "sizeof(array) op x".
4450 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4451 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4452 BO->getLHS());
4453 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4454 BO->getRHS());
4455 }
4456 }
4457
4458 return false;
4459}
4460
4461static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4462 // Cannot know anything else if the expression is dependent.
4463 if (E->isTypeDependent())
4464 return false;
4465
4466 if (E->getObjectKind() == OK_BitField) {
4467 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4468 << 1 << E->getSourceRange();
4469 return true;
4470 }
4471
4472 ValueDecl *D = nullptr;
4473 Expr *Inner = E->IgnoreParens();
4474 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4475 D = DRE->getDecl();
4476 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4477 D = ME->getMemberDecl();
4478 }
4479
4480 // If it's a field, require the containing struct to have a
4481 // complete definition so that we can compute the layout.
4482 //
4483 // This can happen in C++11 onwards, either by naming the member
4484 // in a way that is not transformed into a member access expression
4485 // (in an unevaluated operand, for instance), or by naming the member
4486 // in a trailing-return-type.
4487 //
4488 // For the record, since __alignof__ on expressions is a GCC
4489 // extension, GCC seems to permit this but always gives the
4490 // nonsensical answer 0.
4491 //
4492 // We don't really need the layout here --- we could instead just
4493 // directly check for all the appropriate alignment-lowing
4494 // attributes --- but that would require duplicating a lot of
4495 // logic that just isn't worth duplicating for such a marginal
4496 // use-case.
4497 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4498 // Fast path this check, since we at least know the record has a
4499 // definition if we can find a member of it.
4500 if (!FD->getParent()->isCompleteDefinition()) {
4501 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4502 << E->getSourceRange();
4503 return true;
4504 }
4505
4506 // Otherwise, if it's a field, and the field doesn't have
4507 // reference type, then it must have a complete type (or be a
4508 // flexible array member, which we explicitly want to
4509 // white-list anyway), which makes the following checks trivial.
4510 if (!FD->getType()->isReferenceType())
4511 return false;
4512 }
4513
4514 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4515}
4516
4517bool Sema::CheckVecStepExpr(Expr *E) {
4518 E = E->IgnoreParens();
4519
4520 // Cannot know anything else if the expression is dependent.
4521 if (E->isTypeDependent())
4522 return false;
4523
4524 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4525}
4526
4527static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4528 CapturingScopeInfo *CSI) {
4529 assert(T->isVariablyModifiedType());
4530 assert(CSI != nullptr);
4531
4532 // We're going to walk down into the type and look for VLA expressions.
4533 do {
4534 const Type *Ty = T.getTypePtr();
4535 switch (Ty->getTypeClass()) {
4536#define TYPE(Class, Base)
4537#define ABSTRACT_TYPE(Class, Base)
4538#define NON_CANONICAL_TYPE(Class, Base)
4539#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4540#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4541#include "clang/AST/TypeNodes.inc"
4542 T = QualType();
4543 break;
4544 // These types are never variably-modified.
4545 case Type::Builtin:
4546 case Type::Complex:
4547 case Type::Vector:
4548 case Type::ExtVector:
4549 case Type::ConstantMatrix:
4550 case Type::Record:
4551 case Type::Enum:
4552 case Type::TemplateSpecialization:
4553 case Type::ObjCObject:
4554 case Type::ObjCInterface:
4555 case Type::ObjCObjectPointer:
4556 case Type::ObjCTypeParam:
4557 case Type::Pipe:
4558 case Type::BitInt:
4559 llvm_unreachable("type class is never variably-modified!");
4560 case Type::Elaborated:
4561 T = cast<ElaboratedType>(Ty)->getNamedType();
4562 break;
4563 case Type::Adjusted:
4564 T = cast<AdjustedType>(Ty)->getOriginalType();
4565 break;
4566 case Type::Decayed:
4567 T = cast<DecayedType>(Ty)->getPointeeType();
4568 break;
4569 case Type::Pointer:
4570 T = cast<PointerType>(Ty)->getPointeeType();
4571 break;
4572 case Type::BlockPointer:
4573 T = cast<BlockPointerType>(Ty)->getPointeeType();
4574 break;
4575 case Type::LValueReference:
4576 case Type::RValueReference:
4577 T = cast<ReferenceType>(Ty)->getPointeeType();
4578 break;
4579 case Type::MemberPointer:
4580 T = cast<MemberPointerType>(Ty)->getPointeeType();
4581 break;
4582 case Type::ConstantArray:
4583 case Type::IncompleteArray:
4584 // Losing element qualification here is fine.
4585 T = cast<ArrayType>(Ty)->getElementType();
4586 break;
4587 case Type::VariableArray: {
4588 // Losing element qualification here is fine.
4589 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4590
4591 // Unknown size indication requires no size computation.
4592 // Otherwise, evaluate and record it.
4593 auto Size = VAT->getSizeExpr();
4594 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4595 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4596 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4597
4598 T = VAT->getElementType();
4599 break;
4600 }
4601 case Type::FunctionProto:
4602 case Type::FunctionNoProto:
4603 T = cast<FunctionType>(Ty)->getReturnType();
4604 break;
4605 case Type::Paren:
4606 case Type::TypeOf:
4607 case Type::UnaryTransform:
4608 case Type::Attributed:
4609 case Type::BTFTagAttributed:
4610 case Type::SubstTemplateTypeParm:
4611 case Type::MacroQualified:
4612 // Keep walking after single level desugaring.
4613 T = T.getSingleStepDesugaredType(Context);
4614 break;
4615 case Type::Typedef:
4616 T = cast<TypedefType>(Ty)->desugar();
4617 break;
4618 case Type::Decltype:
4619 T = cast<DecltypeType>(Ty)->desugar();
4620 break;
4621 case Type::Using:
4622 T = cast<UsingType>(Ty)->desugar();
4623 break;
4624 case Type::Auto:
4625 case Type::DeducedTemplateSpecialization:
4626 T = cast<DeducedType>(Ty)->getDeducedType();
4627 break;
4628 case Type::TypeOfExpr:
4629 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4630 break;
4631 case Type::Atomic:
4632 T = cast<AtomicType>(Ty)->getValueType();
4633 break;
4634 }
4635 } while (!T.isNull() && T->isVariablyModifiedType());
4636}
4637
4638/// Check the constraints on operands to unary expression and type
4639/// traits.
4640///
4641/// This will complete any types necessary, and validate the various constraints
4642/// on those operands.
4643///
4644/// The UsualUnaryConversions() function is *not* called by this routine.
4645/// C99 6.3.2.1p[2-4] all state:
4646/// Except when it is the operand of the sizeof operator ...
4647///
4648/// C++ [expr.sizeof]p4
4649/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4650/// standard conversions are not applied to the operand of sizeof.
4651///
4652/// This policy is followed for all of the unary trait expressions.
4653bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4654 SourceLocation OpLoc,
4655 SourceRange ExprRange,
4656 UnaryExprOrTypeTrait ExprKind,
4657 StringRef KWName) {
4658 if (ExprType->isDependentType())
4659 return false;
4660
4661 // C++ [expr.sizeof]p2:
4662 // When applied to a reference or a reference type, the result
4663 // is the size of the referenced type.
4664 // C++11 [expr.alignof]p3:
4665 // When alignof is applied to a reference type, the result
4666 // shall be the alignment of the referenced type.
4667 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4668 ExprType = Ref->getPointeeType();
4669
4670 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4671 // When alignof or _Alignof is applied to an array type, the result
4672 // is the alignment of the element type.
4673 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4674 ExprKind == UETT_OpenMPRequiredSimdAlign)
4675 ExprType = Context.getBaseElementType(ExprType);
4676
4677 if (ExprKind == UETT_VecStep)
4678 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4679
4680 // Explicitly list some types as extensions.
4681 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4682 ExprKind))
4683 return false;
4684
4685 if (RequireCompleteSizedType(
4686 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4687 KWName, ExprRange))
4688 return true;
4689
4690 if (ExprType->isFunctionType()) {
4691 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4692 return true;
4693 }
4694
4695 // WebAssembly tables are always illegal operands to unary expressions and
4696 // type traits.
4697 if (Context.getTargetInfo().getTriple().isWasm() &&
4698 ExprType->isWebAssemblyTableType()) {
4699 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4700 << getTraitSpelling(ExprKind);
4701 return true;
4702 }
4703
4704 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4705 ExprKind))
4706 return true;
4707
4708 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4709 if (auto *TT = ExprType->getAs<TypedefType>()) {
4710 for (auto I = FunctionScopes.rbegin(),
4711 E = std::prev(FunctionScopes.rend());
4712 I != E; ++I) {
4713 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4714 if (CSI == nullptr)
4715 break;
4716 DeclContext *DC = nullptr;
4717 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4718 DC = LSI->CallOperator;
4719 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4720 DC = CRSI->TheCapturedDecl;
4721 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4722 DC = BSI->TheDecl;
4723 if (DC) {
4724 if (DC->containsDecl(TT->getDecl()))
4725 break;
4726 captureVariablyModifiedType(Context, ExprType, CSI);
4727 }
4728 }
4729 }
4730 }
4731
4732 return false;
4733}
4734
4735/// Build a sizeof or alignof expression given a type operand.
4736ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4737 SourceLocation OpLoc,
4738 UnaryExprOrTypeTrait ExprKind,
4739 SourceRange R) {
4740 if (!TInfo)
4741 return ExprError();
4742
4743 QualType T = TInfo->getType();
4744
4745 if (!T->isDependentType() &&
4746 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4747 getTraitSpelling(ExprKind)))
4748 return ExprError();
4749
4750 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4751 // properly deal with VLAs in nested calls of sizeof and typeof.
4752 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4753 TInfo->getType()->isVariablyModifiedType())
4754 TInfo = TransformToPotentiallyEvaluated(TInfo);
4755
4756 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4757 return new (Context) UnaryExprOrTypeTraitExpr(
4758 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4759}
4760
4761/// Build a sizeof or alignof expression given an expression
4762/// operand.
4763ExprResult
4764Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4765 UnaryExprOrTypeTrait ExprKind) {
4766 ExprResult PE = CheckPlaceholderExpr(E);
4767 if (PE.isInvalid())
4768 return ExprError();
4769
4770 E = PE.get();
4771
4772 // Verify that the operand is valid.
4773 bool isInvalid = false;
4774 if (E->isTypeDependent()) {
4775 // Delay type-checking for type-dependent expressions.
4776 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4777 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4778 } else if (ExprKind == UETT_VecStep) {
4779 isInvalid = CheckVecStepExpr(E);
4780 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4781 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4782 isInvalid = true;
4783 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4784 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4785 isInvalid = true;
4786 } else {
4787 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4788 }
4789
4790 if (isInvalid)
4791 return ExprError();
4792
4793 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4794 PE = TransformToPotentiallyEvaluated(E);
4795 if (PE.isInvalid()) return ExprError();
4796 E = PE.get();
4797 }
4798
4799 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4800 return new (Context) UnaryExprOrTypeTraitExpr(
4801 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4802}
4803
4804/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4805/// expr and the same for @c alignof and @c __alignof
4806/// Note that the ArgRange is invalid if isType is false.
4807ExprResult
4808Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4809 UnaryExprOrTypeTrait ExprKind, bool IsType,
4810 void *TyOrEx, SourceRange ArgRange) {
4811 // If error parsing type, ignore.
4812 if (!TyOrEx) return ExprError();
4813
4814 if (IsType) {
4815 TypeSourceInfo *TInfo;
4816 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4817 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4818 }
4819
4820 Expr *ArgEx = (Expr *)TyOrEx;
4821 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4822 return Result;
4823}
4824
4825bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4826 SourceLocation OpLoc, SourceRange R) {
4827 if (!TInfo)
4828 return true;
4829 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4830 UETT_AlignOf, KWName);
4831}
4832
4833/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4834/// _Alignas(type-name) .
4835/// [dcl.align] An alignment-specifier of the form
4836/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4837///
4838/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4839/// _Alignas(_Alignof(type-name)).
4840bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4841 SourceLocation OpLoc, SourceRange R) {
4842 TypeSourceInfo *TInfo;
4843 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),
4844 &TInfo);
4845 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4846}
4847
4848static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4849 bool IsReal) {
4850 if (V.get()->isTypeDependent())
4851 return S.Context.DependentTy;
4852
4853 // _Real and _Imag are only l-values for normal l-values.
4854 if (V.get()->getObjectKind() != OK_Ordinary) {
4855 V = S.DefaultLvalueConversion(V.get());
4856 if (V.isInvalid())
4857 return QualType();
4858 }
4859
4860 // These operators return the element type of a complex type.
4861 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4862 return CT->getElementType();
4863
4864 // Otherwise they pass through real integer and floating point types here.
4865 if (V.get()->getType()->isArithmeticType())
4866 return V.get()->getType();
4867
4868 // Test for placeholders.
4869 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4870 if (PR.isInvalid()) return QualType();
4871 if (PR.get() != V.get()) {
4872 V = PR;
4873 return CheckRealImagOperand(S, V, Loc, IsReal);
4874 }
4875
4876 // Reject anything else.
4877 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4878 << (IsReal ? "__real" : "__imag");
4879 return QualType();
4880}
4881
4882
4883
4884ExprResult
4885Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4886 tok::TokenKind Kind, Expr *Input) {
4887 UnaryOperatorKind Opc;
4888 switch (Kind) {
4889 default: llvm_unreachable("Unknown unary op!");
4890 case tok::plusplus: Opc = UO_PostInc; break;
4891 case tok::minusminus: Opc = UO_PostDec; break;
4892 }
4893
4894 // Since this might is a postfix expression, get rid of ParenListExprs.
4895 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4896 if (Result.isInvalid()) return ExprError();
4897 Input = Result.get();
4898
4899 return BuildUnaryOp(S, OpLoc, Opc, Input);
4900}
4901
4902/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4903///
4904/// \return true on error
4905static bool checkArithmeticOnObjCPointer(Sema &S,
4906 SourceLocation opLoc,
4907 Expr *op) {
4908 assert(op->getType()->isObjCObjectPointerType());
4909 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4910 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4911 return false;
4912
4913 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4914 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4915 << op->getSourceRange();
4916 return true;
4917}
4918
4919static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4920 auto *BaseNoParens = Base->IgnoreParens();
4921 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4922 return MSProp->getPropertyDecl()->getType()->isArrayType();
4923 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4924}
4925
4926// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4927// Typically this is DependentTy, but can sometimes be more precise.
4928//
4929// There are cases when we could determine a non-dependent type:
4930// - LHS and RHS may have non-dependent types despite being type-dependent
4931// (e.g. unbounded array static members of the current instantiation)
4932// - one may be a dependent-sized array with known element type
4933// - one may be a dependent-typed valid index (enum in current instantiation)
4934//
4935// We *always* return a dependent type, in such cases it is DependentTy.
4936// This avoids creating type-dependent expressions with non-dependent types.
4937// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4938static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4939 const ASTContext &Ctx) {
4940 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4941 QualType LTy = LHS->getType(), RTy = RHS->getType();
4942 QualType Result = Ctx.DependentTy;
4943 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4944 if (const PointerType *PT = LTy->getAs<PointerType>())
4945 Result = PT->getPointeeType();
4946 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4947 Result = AT->getElementType();
4948 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4949 if (const PointerType *PT = RTy->getAs<PointerType>())
4950 Result = PT->getPointeeType();
4951 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4952 Result = AT->getElementType();
4953 }
4954 // Ensure we return a dependent type.
4955 return Result->isDependentType() ? Result : Ctx.DependentTy;
4956}
4957
4958static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4959
4960ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4961 SourceLocation lbLoc,
4962 MultiExprArg ArgExprs,
4963 SourceLocation rbLoc) {
4964
4965 if (base && !base->getType().isNull() &&
4966 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4967 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4968 SourceLocation(), /*Length*/ nullptr,
4969 /*Stride=*/nullptr, rbLoc);
4970
4971 // Since this might be a postfix expression, get rid of ParenListExprs.
4972 if (isa<ParenListExpr>(base)) {
4973 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4974 if (result.isInvalid())
4975 return ExprError();
4976 base = result.get();
4977 }
4978
4979 // Check if base and idx form a MatrixSubscriptExpr.
4980 //
4981 // Helper to check for comma expressions, which are not allowed as indices for
4982 // matrix subscript expressions.
4983 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4984 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4985 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4986 << SourceRange(base->getBeginLoc(), rbLoc);
4987 return true;
4988 }
4989 return false;
4990 };
4991 // The matrix subscript operator ([][])is considered a single operator.
4992 // Separating the index expressions by parenthesis is not allowed.
4993 if (base && !base->getType().isNull() &&
4994 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4995 !isa<MatrixSubscriptExpr>(base)) {
4996 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4997 << SourceRange(base->getBeginLoc(), rbLoc);
4998 return ExprError();
4999 }
5000 // If the base is a MatrixSubscriptExpr, try to create a new
5001 // MatrixSubscriptExpr.
5002 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5003 if (matSubscriptE) {
5004 assert(ArgExprs.size() == 1);
5005 if (CheckAndReportCommaError(ArgExprs.front()))
5006 return ExprError();
5007
5008 assert(matSubscriptE->isIncomplete() &&
5009 "base has to be an incomplete matrix subscript");
5010 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5011 matSubscriptE->getRowIdx(),
5012 ArgExprs.front(), rbLoc);
5013 }
5014 if (base->getType()->isWebAssemblyTableType()) {
5015 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5016 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5017 return ExprError();
5018 }
5019
5020 // Handle any non-overload placeholder types in the base and index
5021 // expressions. We can't handle overloads here because the other
5022 // operand might be an overloadable type, in which case the overload
5023 // resolution for the operator overload should get the first crack
5024 // at the overload.
5025 bool IsMSPropertySubscript = false;
5026 if (base->getType()->isNonOverloadPlaceholderType()) {
5027 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5028 if (!IsMSPropertySubscript) {
5029 ExprResult result = CheckPlaceholderExpr(base);
5030 if (result.isInvalid())
5031 return ExprError();
5032 base = result.get();
5033 }
5034 }
5035
5036 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5037 if (base->getType()->isMatrixType()) {
5038 assert(ArgExprs.size() == 1);
5039 if (CheckAndReportCommaError(ArgExprs.front()))
5040 return ExprError();
5041
5042 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5043 rbLoc);
5044 }
5045
5046 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5047 Expr *idx = ArgExprs[0];
5048 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5049 (isa<CXXOperatorCallExpr>(idx) &&
5050 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5051 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5052 << SourceRange(base->getBeginLoc(), rbLoc);
5053 }
5054 }
5055
5056 if (ArgExprs.size() == 1 &&
5057 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5058 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5059 if (result.isInvalid())
5060 return ExprError();
5061 ArgExprs[0] = result.get();
5062 } else {
5063 if (checkArgsForPlaceholders(*this, ArgExprs))
5064 return ExprError();
5065 }
5066
5067 // Build an unanalyzed expression if either operand is type-dependent.
5068 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5069 (base->isTypeDependent() ||
5070 Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
5071 !isa<PackExpansionExpr>(ArgExprs[0])) {
5072 return new (Context) ArraySubscriptExpr(
5073 base, ArgExprs.front(),
5074 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5075 VK_LValue, OK_Ordinary, rbLoc);
5076 }
5077
5078 // MSDN, property (C++)
5079 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5080 // This attribute can also be used in the declaration of an empty array in a
5081 // class or structure definition. For example:
5082 // __declspec(property(get=GetX, put=PutX)) int x[];
5083 // The above statement indicates that x[] can be used with one or more array
5084 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5085 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5086 if (IsMSPropertySubscript) {
5087 assert(ArgExprs.size() == 1);
5088 // Build MS property subscript expression if base is MS property reference
5089 // or MS property subscript.
5090 return new (Context)
5091 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5092 VK_LValue, OK_Ordinary, rbLoc);
5093 }
5094
5095 // Use C++ overloaded-operator rules if either operand has record
5096 // type. The spec says to do this if either type is *overloadable*,
5097 // but enum types can't declare subscript operators or conversion
5098 // operators, so there's nothing interesting for overload resolution
5099 // to do if there aren't any record types involved.
5100 //
5101 // ObjC pointers have their own subscripting logic that is not tied
5102 // to overload resolution and so should not take this path.
5103 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5104 ((base->getType()->isRecordType() ||
5105 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5106 ArgExprs[0]->getType()->isRecordType())))) {
5107 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5108 }
5109
5110 ExprResult Res =
5111 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5112
5113 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5114 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5115
5116 return Res;
5117}
5118
5119ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5120 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
5121 InitializationKind Kind =
5122 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
5123 InitializationSequence InitSeq(*this, Entity, Kind, E);
5124 return InitSeq.Perform(*this, Entity, Kind, E);
5125}
5126
5127ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5128 Expr *ColumnIdx,
5129 SourceLocation RBLoc) {
5130 ExprResult BaseR = CheckPlaceholderExpr(Base);
5131 if (BaseR.isInvalid())
5132 return BaseR;
5133 Base = BaseR.get();
5134
5135 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5136 if (RowR.isInvalid())
5137 return RowR;
5138 RowIdx = RowR.get();
5139
5140 if (!ColumnIdx)
5141 return new (Context) MatrixSubscriptExpr(
5142 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5143
5144 // Build an unanalyzed expression if any of the operands is type-dependent.
5145 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5146 ColumnIdx->isTypeDependent())
5147 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5148 Context.DependentTy, RBLoc);
5149
5150 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5151 if (ColumnR.isInvalid())
5152 return ColumnR;
5153 ColumnIdx = ColumnR.get();
5154
5155 // Check that IndexExpr is an integer expression. If it is a constant
5156 // expression, check that it is less than Dim (= the number of elements in the
5157 // corresponding dimension).
5158 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5159 bool IsColumnIdx) -> Expr * {
5160 if (!IndexExpr->getType()->isIntegerType() &&
5161 !IndexExpr->isTypeDependent()) {
5162 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5163 << IsColumnIdx;
5164 return nullptr;
5165 }
5166
5167 if (std::optional<llvm::APSInt> Idx =
5168 IndexExpr->getIntegerConstantExpr(Context)) {
5169 if ((*Idx < 0 || *Idx >= Dim)) {
5170 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5171 << IsColumnIdx << Dim;
5172 return nullptr;
5173 }
5174 }
5175
5176 ExprResult ConvExpr =
5177 tryConvertExprToType(IndexExpr, Context.getSizeType());
5178 assert(!ConvExpr.isInvalid() &&
5179 "should be able to convert any integer type to size type");
5180 return ConvExpr.get();
5181 };
5182
5183 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5184 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5185 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5186 if (!RowIdx || !ColumnIdx)
5187 return ExprError();
5188
5189 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5190 MTy->getElementType(), RBLoc);
5191}
5192
5193void Sema::CheckAddressOfNoDeref(const Expr *E) {
5194 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5195 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5196
5197 // For expressions like `&(*s).b`, the base is recorded and what should be
5198 // checked.
5199 const MemberExpr *Member = nullptr;
5200 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5201 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5202
5203 LastRecord.PossibleDerefs.erase(StrippedExpr);
5204}
5205
5206void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5207 if (isUnevaluatedContext())
5208 return;
5209
5210 QualType ResultTy = E->getType();
5211 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5212
5213 // Bail if the element is an array since it is not memory access.
5214 if (isa<ArrayType>(ResultTy))
5215 return;
5216
5217 if (ResultTy->hasAttr(attr::NoDeref)) {
5218 LastRecord.PossibleDerefs.insert(E);
5219 return;
5220 }
5221
5222 // Check if the base type is a pointer to a member access of a struct
5223 // marked with noderef.
5224 const Expr *Base = E->getBase();
5225 QualType BaseTy = Base->getType();
5226 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5227 // Not a pointer access
5228 return;
5229
5230 const MemberExpr *Member = nullptr;
5231 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5232 Member->isArrow())
5233 Base = Member->getBase();
5234
5235 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5236 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5237 LastRecord.PossibleDerefs.insert(E);
5238 }
5239}
5240
5241ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5242 Expr *LowerBound,
5243 SourceLocation ColonLocFirst,
5244 SourceLocation ColonLocSecond,
5245 Expr *Length, Expr *Stride,
5246 SourceLocation RBLoc) {
5247 if (Base->hasPlaceholderType() &&
5248 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5249 ExprResult Result = CheckPlaceholderExpr(Base);
5250 if (Result.isInvalid())
5251 return ExprError();
5252 Base = Result.get();
5253 }
5254 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5255 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5256 if (Result.isInvalid())
5257 return ExprError();
5258 Result = DefaultLvalueConversion(Result.get());
5259 if (Result.isInvalid())
5260 return ExprError();
5261 LowerBound = Result.get();
5262 }
5263 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5264 ExprResult Result = CheckPlaceholderExpr(Length);
5265 if (Result.isInvalid())
5266 return ExprError();
5267 Result = DefaultLvalueConversion(Result.get());
5268 if (Result.isInvalid())
5269 return ExprError();
5270 Length = Result.get();
5271 }
5272 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5273 ExprResult Result = CheckPlaceholderExpr(Stride);
5274 if (Result.isInvalid())
5275 return ExprError();
5276 Result = DefaultLvalueConversion(Result.get());
5277 if (Result.isInvalid())
5278 return ExprError();
5279 Stride = Result.get();
5280 }
5281
5282 // Build an unanalyzed expression if either operand is type-dependent.
5283 if (Base->isTypeDependent() ||
5284 (LowerBound &&
5285 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5286 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5287 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5288 return new (Context) OMPArraySectionExpr(
5289 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5290 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5291 }
5292
5293 // Perform default conversions.
5294 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5295 QualType ResultTy;
5296 if (OriginalTy->isAnyPointerType()) {
5297 ResultTy = OriginalTy->getPointeeType();
5298 } else if (OriginalTy->isArrayType()) {
5299 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5300 } else {
5301 return ExprError(
5302 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5303 << Base->getSourceRange());
5304 }
5305 // C99 6.5.2.1p1
5306 if (LowerBound) {
5307 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5308 LowerBound);
5309 if (Res.isInvalid())
5310 return ExprError(Diag(LowerBound->getExprLoc(),
5311 diag::err_omp_typecheck_section_not_integer)
5312 << 0 << LowerBound->getSourceRange());
5313 LowerBound = Res.get();
5314
5315 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5316 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5317 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5318 << 0 << LowerBound->getSourceRange();
5319 }
5320 if (Length) {
5321 auto Res =
5322 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5323 if (Res.isInvalid())
5324 return ExprError(Diag(Length->getExprLoc(),
5325 diag::err_omp_typecheck_section_not_integer)
5326 << 1 << Length->getSourceRange());
5327 Length = Res.get();
5328
5329 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5330 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5331 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5332 << 1 << Length->getSourceRange();
5333 }
5334 if (Stride) {
5335 ExprResult Res =
5336 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5337 if (Res.isInvalid())
5338 return ExprError(Diag(Stride->getExprLoc(),
5339 diag::err_omp_typecheck_section_not_integer)
5340 << 1 << Stride->getSourceRange());
5341 Stride = Res.get();
5342
5343 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5344 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5345 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5346 << 1 << Stride->getSourceRange();
5347 }
5348
5349 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5350 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5351 // type. Note that functions are not objects, and that (in C99 parlance)
5352 // incomplete types are not object types.
5353 if (ResultTy->isFunctionType()) {
5354 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5355 << ResultTy << Base->getSourceRange();
5356 return ExprError();
5357 }
5358
5359 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5360 diag::err_omp_section_incomplete_type, Base))
5361 return ExprError();
5362
5363 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5364 Expr::EvalResult Result;
5365 if (LowerBound->EvaluateAsInt(Result, Context)) {
5366 // OpenMP 5.0, [2.1.5 Array Sections]
5367 // The array section must be a subset of the original array.
5368 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5369 if (LowerBoundValue.isNegative()) {
5370 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5371 << LowerBound->getSourceRange();
5372 return ExprError();
5373 }
5374 }
5375 }
5376
5377 if (Length) {
5378 Expr::EvalResult Result;
5379 if (Length->EvaluateAsInt(Result, Context)) {
5380 // OpenMP 5.0, [2.1.5 Array Sections]
5381 // The length must evaluate to non-negative integers.
5382 llvm::APSInt LengthValue = Result.Val.getInt();
5383 if (LengthValue.isNegative()) {
5384 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5385 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5386 << Length->getSourceRange();
5387 return ExprError();
5388 }
5389 }
5390 } else if (ColonLocFirst.isValid() &&
5391 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5392 !OriginalTy->isVariableArrayType()))) {
5393 // OpenMP 5.0, [2.1.5 Array Sections]
5394 // When the size of the array dimension is not known, the length must be
5395 // specified explicitly.
5396 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5397 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5398 return ExprError();
5399 }
5400
5401 if (Stride) {
5402 Expr::EvalResult Result;
5403 if (Stride->EvaluateAsInt(Result, Context)) {
5404 // OpenMP 5.0, [2.1.5 Array Sections]
5405 // The stride must evaluate to a positive integer.
5406 llvm::APSInt StrideValue = Result.Val.getInt();
5407 if (!StrideValue.isStrictlyPositive()) {
5408 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5409 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5410 << Stride->getSourceRange();
5411 return ExprError();
5412 }
5413 }
5414 }
5415
5416 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5417 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5418 if (Result.isInvalid())
5419 return ExprError();
5420 Base = Result.get();
5421 }
5422 return new (Context) OMPArraySectionExpr(
5423 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5424 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5425}
5426
5427ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5428 SourceLocation RParenLoc,
5429 ArrayRef<Expr *> Dims,
5430 ArrayRef<SourceRange> Brackets) {
5431 if (Base->hasPlaceholderType()) {
5432 ExprResult Result = CheckPlaceholderExpr(Base);
5433 if (Result.isInvalid())
5434 return ExprError();
5435 Result = DefaultLvalueConversion(Result.get());
5436 if (Result.isInvalid())
5437 return ExprError();
5438 Base = Result.get();
5439 }
5440 QualType BaseTy = Base->getType();
5441 // Delay analysis of the types/expressions if instantiation/specialization is
5442 // required.
5443 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5444 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5445 LParenLoc, RParenLoc, Dims, Brackets);
5446 if (!BaseTy->isPointerType() ||
5447 (!Base->isTypeDependent() &&
5448 BaseTy->getPointeeType()->isIncompleteType()))
5449 return ExprError(Diag(Base->getExprLoc(),
5450 diag::err_omp_non_pointer_type_array_shaping_base)
5451 << Base->getSourceRange());
5452
5453 SmallVector<Expr *, 4> NewDims;
5454 bool ErrorFound = false;
5455 for (Expr *Dim : Dims) {
5456 if (Dim->hasPlaceholderType()) {
5457 ExprResult Result = CheckPlaceholderExpr(Dim);
5458 if (Result.isInvalid()) {
5459 ErrorFound = true;
5460 continue;
5461 }
5462 Result = DefaultLvalueConversion(Result.get());
5463 if (Result.isInvalid()) {
5464 ErrorFound = true;
5465 continue;
5466 }
5467 Dim = Result.get();
5468 }
5469 if (!Dim->isTypeDependent()) {
5470 ExprResult Result =
5471 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5472 if (Result.isInvalid()) {
5473 ErrorFound = true;
5474 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5475 << Dim->getSourceRange();
5476 continue;
5477 }
5478 Dim = Result.get();
5479 Expr::EvalResult EvResult;
5480 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5481 // OpenMP 5.0, [2.1.4 Array Shaping]
5482 // Each si is an integral type expression that must evaluate to a
5483 // positive integer.
5484 llvm::APSInt Value = EvResult.Val.getInt();
5485 if (!Value.isStrictlyPositive()) {
5486 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5487 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5488 << Dim->getSourceRange();
5489 ErrorFound = true;
5490 continue;
5491 }
5492 }
5493 }
5494 NewDims.push_back(Dim);
5495 }
5496 if (ErrorFound)
5497 return ExprError();
5498 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5499 LParenLoc, RParenLoc, NewDims, Brackets);
5500}
5501
5502ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5503 SourceLocation LLoc, SourceLocation RLoc,
5504 ArrayRef<OMPIteratorData> Data) {
5505 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5506 bool IsCorrect = true;
5507 for (const OMPIteratorData &D : Data) {
5508 TypeSourceInfo *TInfo = nullptr;
5509 SourceLocation StartLoc;
5510 QualType DeclTy;
5511 if (!D.Type.getAsOpaquePtr()) {
5512 // OpenMP 5.0, 2.1.6 Iterators
5513 // In an iterator-specifier, if the iterator-type is not specified then
5514 // the type of that iterator is of int type.
5515 DeclTy = Context.IntTy;
5516 StartLoc = D.DeclIdentLoc;
5517 } else {
5518 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5519 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5520 }
5521
5522 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5523 DeclTy->containsUnexpandedParameterPack() ||
5524 DeclTy->isInstantiationDependentType();
5525 if (!IsDeclTyDependent) {
5526 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5527 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5528 // The iterator-type must be an integral or pointer type.
5529 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5530 << DeclTy;
5531 IsCorrect = false;
5532 continue;
5533 }
5534 if (DeclTy.isConstant(Context)) {
5535 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5536 // The iterator-type must not be const qualified.
5537 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5538 << DeclTy;
5539 IsCorrect = false;
5540 continue;
5541 }
5542 }
5543
5544 // Iterator declaration.
5545 assert(D.DeclIdent && "Identifier expected.");
5546 // Always try to create iterator declarator to avoid extra error messages
5547 // about unknown declarations use.
5548 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5549 D.DeclIdent, DeclTy, TInfo, SC_None);
5550 VD->setImplicit();
5551 if (S) {
5552 // Check for conflicting previous declaration.
5553 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5554 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5555 ForVisibleRedeclaration);
5556 Previous.suppressDiagnostics();
5557 LookupName(Previous, S);
5558
5559 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5560 /*AllowInlineNamespace=*/false);
5561 if (!Previous.empty()) {
5562 NamedDecl *Old = Previous.getRepresentativeDecl();
5563 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5564 Diag(Old->getLocation(), diag::note_previous_definition);
5565 } else {
5566 PushOnScopeChains(VD, S);
5567 }
5568 } else {
5569 CurContext->addDecl(VD);
5570 }
5571
5572 /// Act on the iterator variable declaration.
5573 ActOnOpenMPIteratorVarDecl(VD);
5574
5575 Expr *Begin = D.Range.Begin;
5576 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5577 ExprResult BeginRes =
5578 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5579 Begin = BeginRes.get();
5580 }
5581 Expr *End = D.Range.End;
5582 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5583 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5584 End = EndRes.get();
5585 }
5586 Expr *Step = D.Range.Step;
5587 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5588 if (!Step->getType()->isIntegralType(Context)) {
5589 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5590 << Step << Step->getSourceRange();
5591 IsCorrect = false;
5592 continue;
5593 }
5594 std::optional<llvm::APSInt> Result =
5595 Step->getIntegerConstantExpr(Context);
5596 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5597 // If the step expression of a range-specification equals zero, the
5598 // behavior is unspecified.
5599 if (Result && Result->isZero()) {
5600 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5601 << Step << Step->getSourceRange();
5602 IsCorrect = false;
5603 continue;
5604 }
5605 }
5606 if (!Begin || !End || !IsCorrect) {
5607 IsCorrect = false;
5608 continue;
5609 }
5610 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5611 IDElem.IteratorDecl = VD;
5612 IDElem.AssignmentLoc = D.AssignLoc;
5613 IDElem.Range.Begin = Begin;
5614 IDElem.Range.End = End;
5615 IDElem.Range.Step = Step;
5616 IDElem.ColonLoc = D.ColonLoc;
5617 IDElem.SecondColonLoc = D.SecColonLoc;
5618 }
5619 if (!IsCorrect) {
5620 // Invalidate all created iterator declarations if error is found.
5621 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5622 if (Decl *ID = D.IteratorDecl)
5623 ID->setInvalidDecl();
5624 }
5625 return ExprError();
5626 }
5627 SmallVector<OMPIteratorHelperData, 4> Helpers;
5628 if (!CurContext->isDependentContext()) {
5629 // Build number of ityeration for each iteration range.
5630 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5631 // ((Begini-Stepi-1-Endi) / -Stepi);
5632 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5633 // (Endi - Begini)
5634 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5635 D.Range.Begin);
5636 if(!Res.isUsable()) {
5637 IsCorrect = false;
5638 continue;
5639 }
5640 ExprResult St, St1;
5641 if (D.Range.Step) {
5642 St = D.Range.Step;
5643 // (Endi - Begini) + Stepi
5644 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5645 if (!Res.isUsable()) {
5646 IsCorrect = false;
5647 continue;
5648 }
5649 // (Endi - Begini) + Stepi - 1
5650 Res =
5651 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5652 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5653 if (!Res.isUsable()) {
5654 IsCorrect = false;
5655 continue;
5656 }
5657 // ((Endi - Begini) + Stepi - 1) / Stepi
5658 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5659 if (!Res.isUsable()) {
5660 IsCorrect = false;
5661 continue;
5662 }
5663 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5664 // (Begini - Endi)
5665 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5666 D.Range.Begin, D.Range.End);
5667 if (!Res1.isUsable()) {
5668 IsCorrect = false;
5669 continue;
5670 }
5671 // (Begini - Endi) - Stepi
5672 Res1 =
5673 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5674 if (!Res1.isUsable()) {
5675 IsCorrect = false;
5676 continue;
5677 }
5678 // (Begini - Endi) - Stepi - 1
5679 Res1 =
5680 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5681 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5682 if (!Res1.isUsable()) {
5683 IsCorrect = false;
5684 continue;
5685 }
5686 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5687 Res1 =
5688 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5689 if (!Res1.isUsable()) {
5690 IsCorrect = false;
5691 continue;
5692 }
5693 // Stepi > 0.
5694 ExprResult CmpRes =
5695 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5696 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5697 if (!CmpRes.isUsable()) {
5698 IsCorrect = false;
5699 continue;
5700 }
5701 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5702 Res.get(), Res1.get());
5703 if (!Res.isUsable()) {
5704 IsCorrect = false;
5705 continue;
5706 }
5707 }
5708 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5709 if (!Res.isUsable()) {
5710 IsCorrect = false;
5711 continue;
5712 }
5713
5714 // Build counter update.
5715 // Build counter.
5716 auto *CounterVD =
5717 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5718 D.IteratorDecl->getBeginLoc(), nullptr,
5719 Res.get()->getType(), nullptr, SC_None);
5720 CounterVD->setImplicit();
5721 ExprResult RefRes =
5722 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5723 D.IteratorDecl->getBeginLoc());
5724 // Build counter update.
5725 // I = Begini + counter * Stepi;
5726 ExprResult UpdateRes;
5727 if (D.Range.Step) {
5728 UpdateRes = CreateBuiltinBinOp(
5729 D.AssignmentLoc, BO_Mul,
5730 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5731 } else {
5732 UpdateRes = DefaultLvalueConversion(RefRes.get());
5733 }
5734 if (!UpdateRes.isUsable()) {
5735 IsCorrect = false;
5736 continue;
5737 }
5738 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5739 UpdateRes.get());
5740 if (!UpdateRes.isUsable()) {
5741 IsCorrect = false;
5742 continue;
5743 }
5744 ExprResult VDRes =
5745 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5746 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5747 D.IteratorDecl->getBeginLoc());
5748 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5749 UpdateRes.get());
5750 if (!UpdateRes.isUsable()) {
5751 IsCorrect = false;
5752 continue;
5753 }
5754 UpdateRes =
5755 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5756 if (!UpdateRes.isUsable()) {
5757 IsCorrect = false;
5758 continue;
5759 }
5760 ExprResult CounterUpdateRes =
5761 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5762 if (!CounterUpdateRes.isUsable()) {
5763 IsCorrect = false;
5764 continue;
5765 }
5766 CounterUpdateRes =
5767 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5768 if (!CounterUpdateRes.isUsable()) {
5769 IsCorrect = false;
5770 continue;
5771 }
5772 OMPIteratorHelperData &HD = Helpers.emplace_back();
5773 HD.CounterVD = CounterVD;
5774 HD.Upper = Res.get();
5775 HD.Update = UpdateRes.get();
5776 HD.CounterUpdate = CounterUpdateRes.get();
5777 }
5778 } else {
5779 Helpers.assign(ID.size(), {});
5780 }
5781 if (!IsCorrect) {
5782 // Invalidate all created iterator declarations if error is found.
5783 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5784 if (Decl *ID = D.IteratorDecl)
5785 ID->setInvalidDecl();
5786 }
5787 return ExprError();
5788 }
5789 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5790 LLoc, RLoc, ID, Helpers);
5791}
5792
5793ExprResult
5794Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5795 Expr *Idx, SourceLocation RLoc) {
5796 Expr *LHSExp = Base;
5797 Expr *RHSExp = Idx;
5798
5799 ExprValueKind VK = VK_LValue;
5800 ExprObjectKind OK = OK_Ordinary;
5801
5802 // Per C++ core issue 1213, the result is an xvalue if either operand is
5803 // a non-lvalue array, and an lvalue otherwise.
5804 if (getLangOpts().CPlusPlus11) {
5805 for (auto *Op : {LHSExp, RHSExp}) {
5806 Op = Op->IgnoreImplicit();
5807 if (Op->getType()->isArrayType() && !Op->isLValue())
5808 VK = VK_XValue;
5809 }
5810 }
5811
5812 // Perform default conversions.
5813 if (!LHSExp->getType()->getAs<VectorType>()) {
5814 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5815 if (Result.isInvalid())
5816 return ExprError();
5817 LHSExp = Result.get();
5818 }
5819 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5820 if (Result.isInvalid())
5821 return ExprError();
5822 RHSExp = Result.get();
5823
5824 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5825
5826 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5827 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5828 // in the subscript position. As a result, we need to derive the array base
5829 // and index from the expression types.
5830 Expr *BaseExpr, *IndexExpr;
5831 QualType ResultType;
5832 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5833 BaseExpr = LHSExp;
5834 IndexExpr = RHSExp;
5835 ResultType =
5836 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5837 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5838 BaseExpr = LHSExp;
5839 IndexExpr = RHSExp;
5840 ResultType = PTy->getPointeeType();
5841 } else if (const ObjCObjectPointerType *PTy =
5842 LHSTy->getAs<ObjCObjectPointerType>()) {
5843 BaseExpr = LHSExp;
5844 IndexExpr = RHSExp;
5845
5846 // Use custom logic if this should be the pseudo-object subscript
5847 // expression.
5848 if (!LangOpts.isSubscriptPointerArithmetic())
5849 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5850 nullptr);
5851
5852 ResultType = PTy->getPointeeType();
5853 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5854 // Handle the uncommon case of "123[Ptr]".
5855 BaseExpr = RHSExp;
5856 IndexExpr = LHSExp;
5857 ResultType = PTy->getPointeeType();
5858 } else if (const ObjCObjectPointerType *PTy =
5859 RHSTy->getAs<ObjCObjectPointerType>()) {
5860 // Handle the uncommon case of "123[Ptr]".
5861 BaseExpr = RHSExp;
5862 IndexExpr = LHSExp;
5863 ResultType = PTy->getPointeeType();
5864 if (!LangOpts.isSubscriptPointerArithmetic()) {
5865 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5866 << ResultType << BaseExpr->getSourceRange();
5867 return ExprError();
5868 }
5869 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5870 BaseExpr = LHSExp; // vectors: V[123]
5871 IndexExpr = RHSExp;
5872 // We apply C++ DR1213 to vector subscripting too.
5873 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5874 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5875 if (Materialized.isInvalid())
5876 return ExprError();
5877 LHSExp = Materialized.get();
5878 }
5879 VK = LHSExp->getValueKind();
5880 if (VK != VK_PRValue)
5881 OK = OK_VectorComponent;
5882
5883 ResultType = VTy->getElementType();
5884 QualType BaseType = BaseExpr->getType();
5885 Qualifiers BaseQuals = BaseType.getQualifiers();
5886 Qualifiers MemberQuals = ResultType.getQualifiers();
5887 Qualifiers Combined = BaseQuals + MemberQuals;
5888 if (Combined != MemberQuals)
5889 ResultType = Context.getQualifiedType(ResultType, Combined);
5890 } else if (LHSTy->isBuiltinType() &&
5891 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5892 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5893 if (BTy->isSVEBool())
5894 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5895 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5896
5897 BaseExpr = LHSExp;
5898 IndexExpr = RHSExp;
5899 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5900 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5901 if (Materialized.isInvalid())
5902 return ExprError();
5903 LHSExp = Materialized.get();
5904 }
5905 VK = LHSExp->getValueKind();
5906 if (VK != VK_PRValue)
5907 OK = OK_VectorComponent;
5908
5909 ResultType = BTy->getSveEltType(Context);
5910
5911 QualType BaseType = BaseExpr->getType();
5912 Qualifiers BaseQuals = BaseType.getQualifiers();
5913 Qualifiers MemberQuals = ResultType.getQualifiers();
5914 Qualifiers Combined = BaseQuals + MemberQuals;
5915 if (Combined != MemberQuals)
5916 ResultType = Context.getQualifiedType(ResultType, Combined);
5917 } else if (LHSTy->isArrayType()) {
5918 // If we see an array that wasn't promoted by
5919 // DefaultFunctionArrayLvalueConversion, it must be an array that
5920 // wasn't promoted because of the C90 rule that doesn't
5921 // allow promoting non-lvalue arrays. Warn, then
5922 // force the promotion here.
5923 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5924 << LHSExp->getSourceRange();
5925 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5926 CK_ArrayToPointerDecay).get();
5927 LHSTy = LHSExp->getType();
5928
5929 BaseExpr = LHSExp;
5930 IndexExpr = RHSExp;
5931 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5932 } else if (RHSTy->isArrayType()) {
5933 // Same as previous, except for 123[f().a] case
5934 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5935 << RHSExp->getSourceRange();
5936 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5937 CK_ArrayToPointerDecay).get();
5938 RHSTy = RHSExp->getType();
5939
5940 BaseExpr = RHSExp;
5941 IndexExpr = LHSExp;
5942 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5943 } else {
5944 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5945 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5946 }
5947 // C99 6.5.2.1p1
5948 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5949 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5950 << IndexExpr->getSourceRange());
5951
5952 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5953 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5954 && !IndexExpr->isTypeDependent())
5955 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5956
5957 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5958 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5959 // type. Note that Functions are not objects, and that (in C99 parlance)
5960 // incomplete types are not object types.
5961 if (ResultType->isFunctionType()) {
5962 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5963 << ResultType << BaseExpr->getSourceRange();
5964 return ExprError();
5965 }
5966
5967 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5968 // GNU extension: subscripting on pointer to void
5969 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5970 << BaseExpr->getSourceRange();
5971
5972 // C forbids expressions of unqualified void type from being l-values.
5973 // See IsCForbiddenLValueType.
5974 if (!ResultType.hasQualifiers())
5975 VK = VK_PRValue;
5976 } else if (!ResultType->isDependentType() &&
5977 !ResultType.isWebAssemblyReferenceType() &&
5978 RequireCompleteSizedType(
5979 LLoc, ResultType,
5980 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5981 return ExprError();
5982
5983 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5984 !ResultType.isCForbiddenLValueType());
5985
5986 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5987 FunctionScopes.size() > 1) {
5988 if (auto *TT =
5989 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5990 for (auto I = FunctionScopes.rbegin(),
5991 E = std::prev(FunctionScopes.rend());
5992 I != E; ++I) {
5993 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5994 if (CSI == nullptr)
5995 break;
5996 DeclContext *DC = nullptr;
5997 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5998 DC = LSI->CallOperator;
5999 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
6000 DC = CRSI->TheCapturedDecl;
6001 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
6002 DC = BSI->TheDecl;
6003 if (DC) {
6004 if (DC->containsDecl(TT->getDecl()))
6005 break;
6006 captureVariablyModifiedType(
6007 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
6008 }
6009 }
6010 }
6011 }
6012
6013 return new (Context)
6014 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
6015}
6016
6017bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6018 ParmVarDecl *Param, Expr *RewrittenInit,
6019 bool SkipImmediateInvocations) {
6020 if (Param->hasUnparsedDefaultArg()) {
6021 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
6022 // If we've already cleared out the location for the default argument,
6023 // that means we're parsing it right now.
6024 if (!UnparsedDefaultArgLocs.count(Param)) {
6025 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
6026 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
6027 Param->setInvalidDecl();
6028 return true;
6029 }
6030
6031 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
6032 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
6033 Diag(UnparsedDefaultArgLocs[Param],
6034 diag::note_default_argument_declared_here);
6035 return true;
6036 }
6037
6038 if (Param->hasUninstantiatedDefaultArg()) {
6039 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
6040 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6041 return true;
6042 }
6043
6044 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
6045 assert(Init && "default argument but no initializer?");
6046
6047 // If the default expression creates temporaries, we need to
6048 // push them to the current stack of expression temporaries so they'll
6049 // be properly destroyed.
6050 // FIXME: We should really be rebuilding the default argument with new
6051 // bound temporaries; see the comment in PR5810.
6052 // We don't need to do that with block decls, though, because
6053 // blocks in default argument expression can never capture anything.
6054 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
6055 // Set the "needs cleanups" bit regardless of whether there are
6056 // any explicit objects.
6057 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
6058 // Append all the objects to the cleanup list. Right now, this
6059 // should always be a no-op, because blocks in default argument
6060 // expressions should never be able to capture anything.
6061 assert(!InitWithCleanup->getNumObjects() &&
6062 "default argument expression has capturing blocks?");
6063 }
6064 // C++ [expr.const]p15.1:
6065 // An expression or conversion is in an immediate function context if it is
6066 // potentially evaluated and [...] its innermost enclosing non-block scope
6067 // is a function parameter scope of an immediate function.
6068 EnterExpressionEvaluationContext EvalContext(
6069 *this,
6070 FD->isImmediateFunction()
6071 ? ExpressionEvaluationContext::ImmediateFunctionContext
6072 : ExpressionEvaluationContext::PotentiallyEvaluated,
6073 Param);
6074 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6075 SkipImmediateInvocations;
6076 runWithSufficientStackSpace(CallLoc, [&] {
6077 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
6078 });
6079 return false;
6080}
6081
6082struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
6083 const ASTContext &Context;
6084 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
6085
6086 bool HasImmediateCalls = false;
6087 bool shouldVisitImplicitCode() const { return true; }
6088
6089 bool VisitCallExpr(CallExpr *E) {
6090 if (const FunctionDecl *FD = E->getDirectCallee())
6091 HasImmediateCalls |= FD->isImmediateFunction();
6092 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6093 }
6094
6095 // SourceLocExpr are not immediate invocations
6096 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
6097 // need to be rebuilt so that they refer to the correct SourceLocation and
6098 // DeclContext.
6099 bool VisitSourceLocExpr(SourceLocExpr *E) {
6100 HasImmediateCalls = true;
6101 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6102 }
6103
6104 // A nested lambda might have parameters with immediate invocations
6105 // in their default arguments.
6106 // The compound statement is not visited (as it does not constitute a
6107 // subexpression).
6108 // FIXME: We should consider visiting and transforming captures
6109 // with init expressions.
6110 bool VisitLambdaExpr(LambdaExpr *E) {
6111 return VisitCXXMethodDecl(E->getCallOperator());
6112 }
6113
6114 // Blocks don't support default parameters, and, as for lambdas,
6115 // we don't consider their body a subexpression.
6116 bool VisitBlockDecl(BlockDecl *B) { return false; }
6117
6118 bool VisitCompoundStmt(CompoundStmt *B) { return false; }
6119
6120 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6121 return TraverseStmt(E->getExpr());
6122 }
6123
6124 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
6125 return TraverseStmt(E->getExpr());
6126 }
6127};
6128
6129struct EnsureImmediateInvocationInDefaultArgs
6130 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
6131 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
6132 : TreeTransform(SemaRef) {}
6133
6134 // Lambda can only have immediate invocations in the default
6135 // args of their parameters, which is transformed upon calling the closure.
6136 // The body is not a subexpression, so we have nothing to do.
6137 // FIXME: Immediate calls in capture initializers should be transformed.
6138 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
6139 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
6140
6141 // Make sure we don't rebuild the this pointer as it would
6142 // cause it to incorrectly point it to the outermost class
6143 // in the case of nested struct initialization.
6144 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
6145};
6146
6147ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6148 FunctionDecl *FD, ParmVarDecl *Param,
6149 Expr *Init) {
6150 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
6151
6152 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6153
6154 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6155 InitializationContext =
6156 OutermostDeclarationWithDelayedImmediateInvocations();
6157 if (!InitializationContext.has_value())
6158 InitializationContext.emplace(CallLoc, Param, CurContext);
6159
6160 if (!Init && !Param->hasUnparsedDefaultArg()) {
6161 // Mark that we are replacing a default argument first.
6162 // If we are instantiating a template we won't have to
6163 // retransform immediate calls.
6164 // C++ [expr.const]p15.1:
6165 // An expression or conversion is in an immediate function context if it
6166 // is potentially evaluated and [...] its innermost enclosing non-block
6167 // scope is a function parameter scope of an immediate function.
6168 EnterExpressionEvaluationContext EvalContext(
6169 *this,
6170 FD->isImmediateFunction()
6171 ? ExpressionEvaluationContext::ImmediateFunctionContext
6172 : ExpressionEvaluationContext::PotentiallyEvaluated,
6173 Param);
6174
6175 if (Param->hasUninstantiatedDefaultArg()) {
6176 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6177 return ExprError();
6178 }
6179 // CWG2631
6180 // An immediate invocation that is not evaluated where it appears is
6181 // evaluated and checked for whether it is a constant expression at the
6182 // point where the enclosing initializer is used in a function call.
6183 ImmediateCallVisitor V(getASTContext());
6184 if (!NestedDefaultChecking)
6185 V.TraverseDecl(Param);
6186 if (V.HasImmediateCalls) {
6187 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6188 CallLoc, Param, CurContext};
6189 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6190 ExprResult Res;
6191 runWithSufficientStackSpace(CallLoc, [&] {
6192 Res = Immediate.TransformInitializer(Param->getInit(),
6193 /*NotCopy=*/false);
6194 });
6195 if (Res.isInvalid())
6196 return ExprError();
6197 Res = ConvertParamDefaultArgument(Param, Res.get(),
6198 Res.get()->getBeginLoc());
6199 if (Res.isInvalid())
6200 return ExprError();
6201 Init = Res.get();
6202 }
6203 }
6204
6205 if (CheckCXXDefaultArgExpr(
6206 CallLoc, FD, Param, Init,
6207 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6208 return ExprError();
6209
6210 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6211 Init, InitializationContext->Context);
6212}
6213
6214ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6215 assert(Field->hasInClassInitializer());
6216
6217 // If we might have already tried and failed to instantiate, don't try again.
6218 if (Field->isInvalidDecl())
6219 return ExprError();
6220
6221 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6222
6223 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6224
6225 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6226 InitializationContext =
6227 OutermostDeclarationWithDelayedImmediateInvocations();
6228 if (!InitializationContext.has_value())
6229 InitializationContext.emplace(Loc, Field, CurContext);
6230
6231 Expr *Init = nullptr;
6232
6233 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6234
6235 EnterExpressionEvaluationContext EvalContext(
6236 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6237
6238 if (!Field->getInClassInitializer()) {
6239 // Maybe we haven't instantiated the in-class initializer. Go check the
6240 // pattern FieldDecl to see if it has one.
6241 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6242 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6243 DeclContext::lookup_result Lookup =
6244 ClassPattern->lookup(Field->getDeclName());
6245
6246 FieldDecl *Pattern = nullptr;
6247 for (auto *L : Lookup) {
6248 if ((Pattern = dyn_cast<FieldDecl>(L)))
6249 break;
6250 }
6251 assert(Pattern && "We must have set the Pattern!");
6252 if (!Pattern->hasInClassInitializer() ||
6253 InstantiateInClassInitializer(Loc, Field, Pattern,
6254 getTemplateInstantiationArgs(Field))) {
6255 Field->setInvalidDecl();
6256 return ExprError();
6257 }
6258 }
6259 }
6260
6261 // CWG2631
6262 // An immediate invocation that is not evaluated where it appears is
6263 // evaluated and checked for whether it is a constant expression at the
6264 // point where the enclosing initializer is used in a [...] a constructor
6265 // definition, or an aggregate initialization.
6266 ImmediateCallVisitor V(getASTContext());
6267 if (!NestedDefaultChecking)
6268 V.TraverseDecl(Field);
6269 if (V.HasImmediateCalls) {
6270 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6271 CurContext};
6272 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6273 NestedDefaultChecking;
6274
6275 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6276 ExprResult Res;
6277 runWithSufficientStackSpace(Loc, [&] {
6278 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
6279 /*CXXDirectInit=*/false);
6280 });
6281 if (!Res.isInvalid())
6282 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6283 if (Res.isInvalid()) {
6284 Field->setInvalidDecl();
6285 return ExprError();
6286 }
6287 Init = Res.get();
6288 }
6289
6290 if (Field->getInClassInitializer()) {
6291 Expr *E = Init ? Init : Field->getInClassInitializer();
6292 if (!NestedDefaultChecking)
6293 runWithSufficientStackSpace(Loc, [&] {
6294 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6295 });
6296 // C++11 [class.base.init]p7:
6297 // The initialization of each base and member constitutes a
6298 // full-expression.
6299 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6300 if (Res.isInvalid()) {
6301 Field->setInvalidDecl();
6302 return ExprError();
6303 }
6304 Init = Res.get();
6305
6306 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6307 Field, InitializationContext->Context,
6308 Init);
6309 }
6310
6311 // DR1351:
6312 // If the brace-or-equal-initializer of a non-static data member
6313 // invokes a defaulted default constructor of its class or of an
6314 // enclosing class in a potentially evaluated subexpression, the
6315 // program is ill-formed.
6316 //
6317 // This resolution is unworkable: the exception specification of the
6318 // default constructor can be needed in an unevaluated context, in
6319 // particular, in the operand of a noexcept-expression, and we can be
6320 // unable to compute an exception specification for an enclosed class.
6321 //
6322 // Any attempt to resolve the exception specification of a defaulted default
6323 // constructor before the initializer is lexically complete will ultimately
6324 // come here at which point we can diagnose it.
6325 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6326 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6327 << OutermostClass << Field;
6328 Diag(Field->getEndLoc(),
6329 diag::note_default_member_initializer_not_yet_parsed);
6330 // Recover by marking the field invalid, unless we're in a SFINAE context.
6331 if (!isSFINAEContext())
6332 Field->setInvalidDecl();
6333 return ExprError();
6334}
6335
6336Sema::VariadicCallType
6337Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6338 Expr *Fn) {
6339 if (Proto && Proto->isVariadic()) {
6340 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6341 return VariadicConstructor;
6342 else if (Fn && Fn->getType()->isBlockPointerType())
6343 return VariadicBlock;
6344 else if (FDecl) {
6345 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6346 if (Method->isInstance())
6347 return VariadicMethod;
6348 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6349 return VariadicMethod;
6350 return VariadicFunction;
6351 }
6352 return VariadicDoesNotApply;
6353}
6354
6355namespace {
6356class FunctionCallCCC final : public FunctionCallFilterCCC {
6357public:
6358 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6359 unsigned NumArgs, MemberExpr *ME)
6360 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6361 FunctionName(FuncName) {}
6362
6363 bool ValidateCandidate(const TypoCorrection &candidate) override {
6364 if (!candidate.getCorrectionSpecifier() ||
6365 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6366 return false;
6367 }
6368
6369 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6370 }
6371
6372 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6373 return std::make_unique<FunctionCallCCC>(*this);
6374 }
6375
6376private:
6377 const IdentifierInfo *const FunctionName;
6378};
6379}
6380
6381static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6382 FunctionDecl *FDecl,
6383 ArrayRef<Expr *> Args) {
6384 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6385 DeclarationName FuncName = FDecl->getDeclName();
6386 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6387
6388 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6389 if (TypoCorrection Corrected = S.CorrectTypo(
6390 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6391 S.getScopeForContext(S.CurContext), nullptr, CCC,
6392 Sema::CTK_ErrorRecovery)) {
6393 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6394 if (Corrected.isOverloaded()) {
6395 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6396 OverloadCandidateSet::iterator Best;
6397 for (NamedDecl *CD : Corrected) {
6398 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6399 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6400 OCS);
6401 }
6402 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6403 case OR_Success:
6404 ND = Best->FoundDecl;
6405 Corrected.setCorrectionDecl(ND);
6406 break;
6407 default:
6408 break;
6409 }
6410 }
6411 ND = ND->getUnderlyingDecl();
6412 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6413 return Corrected;
6414 }
6415 }
6416 return TypoCorrection();
6417}
6418
6419/// ConvertArgumentsForCall - Converts the arguments specified in
6420/// Args/NumArgs to the parameter types of the function FDecl with
6421/// function prototype Proto. Call is the call expression itself, and
6422/// Fn is the function expression. For a C++ member function, this
6423/// routine does not attempt to convert the object argument. Returns
6424/// true if the call is ill-formed.
6425bool
6426Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6427 FunctionDecl *FDecl,
6428 const FunctionProtoType *Proto,
6429 ArrayRef<Expr *> Args,
6430 SourceLocation RParenLoc,
6431 bool IsExecConfig) {
6432 // Bail out early if calling a builtin with custom typechecking.
6433 if (FDecl)
6434 if (unsigned ID = FDecl->getBuiltinID())
6435 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6436 return false;
6437
6438 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6439 // assignment, to the types of the corresponding parameter, ...
6440 unsigned NumParams = Proto->getNumParams();
6441 bool Invalid = false;
6442 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6443 unsigned FnKind = Fn->getType()->isBlockPointerType()
6444 ? 1 /* block */
6445 : (IsExecConfig ? 3 /* kernel function (exec config) */
6446 : 0 /* function */);
6447
6448 // If too few arguments are available (and we don't have default
6449 // arguments for the remaining parameters), don't make the call.
6450 if (Args.size() < NumParams) {
6451 if (Args.size() < MinArgs) {
6452 TypoCorrection TC;
6453 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6454 unsigned diag_id =
6455 MinArgs == NumParams && !Proto->isVariadic()
6456 ? diag::err_typecheck_call_too_few_args_suggest
6457 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6458 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6459 << static_cast<unsigned>(Args.size())
6460 << TC.getCorrectionRange());
6461 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6462 Diag(RParenLoc,
6463 MinArgs == NumParams && !Proto->isVariadic()
6464 ? diag::err_typecheck_call_too_few_args_one
6465 : diag::err_typecheck_call_too_few_args_at_least_one)
6466 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6467 else
6468 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6469 ? diag::err_typecheck_call_too_few_args
6470 : diag::err_typecheck_call_too_few_args_at_least)
6471 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6472 << Fn->getSourceRange();
6473
6474 // Emit the location of the prototype.
6475 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6476 Diag(FDecl->getLocation(), diag::note_callee_decl)
6477 << FDecl << FDecl->getParametersSourceRange();
6478
6479 return true;
6480 }
6481 // We reserve space for the default arguments when we create
6482 // the call expression, before calling ConvertArgumentsForCall.
6483 assert((Call->getNumArgs() == NumParams) &&
6484 "We should have reserved space for the default arguments before!");
6485 }
6486
6487 // If too many are passed and not variadic, error on the extras and drop
6488 // them.
6489 if (Args.size() > NumParams) {
6490 if (!Proto->isVariadic()) {
6491 TypoCorrection TC;
6492 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6493 unsigned diag_id =
6494 MinArgs == NumParams && !Proto->isVariadic()
6495 ? diag::err_typecheck_call_too_many_args_suggest
6496 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6497 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6498 << static_cast<unsigned>(Args.size())
6499 << TC.getCorrectionRange());
6500 } else if (NumParams == 1 && FDecl &&
6501 FDecl->getParamDecl(0)->getDeclName())
6502 Diag(Args[NumParams]->getBeginLoc(),
6503 MinArgs == NumParams
6504 ? diag::err_typecheck_call_too_many_args_one
6505 : diag::err_typecheck_call_too_many_args_at_most_one)
6506 << FnKind << FDecl->getParamDecl(0)
6507 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6508 << SourceRange(Args[NumParams]->getBeginLoc(),
6509 Args.back()->getEndLoc());
6510 else
6511 Diag(Args[NumParams]->getBeginLoc(),
6512 MinArgs == NumParams
6513 ? diag::err_typecheck_call_too_many_args
6514 : diag::err_typecheck_call_too_many_args_at_most)
6515 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6516 << Fn->getSourceRange()
6517 << SourceRange(Args[NumParams]->getBeginLoc(),
6518 Args.back()->getEndLoc());
6519
6520 // Emit the location of the prototype.
6521 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6522 Diag(FDecl->getLocation(), diag::note_callee_decl)
6523 << FDecl << FDecl->getParametersSourceRange();
6524
6525 // This deletes the extra arguments.
6526 Call->shrinkNumArgs(NumParams);
6527 return true;
6528 }
6529 }
6530 SmallVector<Expr *, 8> AllArgs;
6531 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6532
6533 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6534 AllArgs, CallType);
6535 if (Invalid)
6536 return true;
6537 unsigned TotalNumArgs = AllArgs.size();
6538 for (unsigned i = 0; i < TotalNumArgs; ++i)
6539 Call->setArg(i, AllArgs[i]);
6540
6541 Call->computeDependence();
6542 return false;
6543}
6544
6545bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6546 const FunctionProtoType *Proto,
6547 unsigned FirstParam, ArrayRef<Expr *> Args,
6548 SmallVectorImpl<Expr *> &AllArgs,
6549 VariadicCallType CallType, bool AllowExplicit,
6550 bool IsListInitialization) {
6551 unsigned NumParams = Proto->getNumParams();
6552 bool Invalid = false;
6553 size_t ArgIx = 0;
6554 // Continue to check argument types (even if we have too few/many args).
6555 for (unsigned i = FirstParam; i < NumParams; i++) {
6556 QualType ProtoArgType = Proto->getParamType(i);
6557
6558 Expr *Arg;
6559 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6560 if (ArgIx < Args.size()) {
6561 Arg = Args[ArgIx++];
6562
6563 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6564 diag::err_call_incomplete_argument, Arg))
6565 return true;
6566
6567 // Strip the unbridged-cast placeholder expression off, if applicable.
6568 bool CFAudited = false;
6569 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6570 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6571 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6572 Arg = stripARCUnbridgedCast(Arg);
6573 else if (getLangOpts().ObjCAutoRefCount &&
6574 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6575 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6576 CFAudited = true;
6577
6578 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6579 ProtoArgType->isBlockPointerType())
6580 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6581 BE->getBlockDecl()->setDoesNotEscape();
6582
6583 InitializedEntity Entity =
6584 Param ? InitializedEntity::InitializeParameter(Context, Param,
6585 ProtoArgType)
6586 : InitializedEntity::InitializeParameter(
6587 Context, ProtoArgType, Proto->isParamConsumed(i));
6588
6589 // Remember that parameter belongs to a CF audited API.
6590 if (CFAudited)
6591 Entity.setParameterCFAudited();
6592
6593 ExprResult ArgE = PerformCopyInitialization(
6594 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6595 if (ArgE.isInvalid())
6596 return true;
6597
6598 Arg = ArgE.getAs<Expr>();
6599 } else {
6600 assert(Param && "can't use default arguments without a known callee");
6601
6602 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6603 if (ArgExpr.isInvalid())
6604 return true;
6605
6606 Arg = ArgExpr.getAs<Expr>();
6607 }
6608
6609 // Check for array bounds violations for each argument to the call. This
6610 // check only triggers warnings when the argument isn't a more complex Expr
6611 // with its own checking, such as a BinaryOperator.
6612 CheckArrayAccess(Arg);
6613
6614 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6615 CheckStaticArrayArgument(CallLoc, Param, Arg);
6616
6617 AllArgs.push_back(Arg);
6618 }
6619
6620 // If this is a variadic call, handle args passed through "...".
6621 if (CallType != VariadicDoesNotApply) {
6622 // Assume that extern "C" functions with variadic arguments that
6623 // return __unknown_anytype aren't *really* variadic.
6624 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6625 FDecl->isExternC()) {
6626 for (Expr *A : Args.slice(ArgIx)) {
6627 QualType paramType; // ignored
6628 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6629 Invalid |= arg.isInvalid();
6630 AllArgs.push_back(arg.get());
6631 }
6632
6633 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6634 } else {
6635 for (Expr *A : Args.slice(ArgIx)) {
6636 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6637 Invalid |= Arg.isInvalid();
6638 AllArgs.push_back(Arg.get());
6639 }
6640 }
6641
6642 // Check for array bounds violations.
6643 for (Expr *A : Args.slice(ArgIx))
6644 CheckArrayAccess(A);
6645 }
6646 return Invalid;
6647}
6648
6649static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6650 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6651 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6652 TL = DTL.getOriginalLoc();
6653 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6654 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6655 << ATL.getLocalSourceRange();
6656}
6657
6658/// CheckStaticArrayArgument - If the given argument corresponds to a static
6659/// array parameter, check that it is non-null, and that if it is formed by
6660/// array-to-pointer decay, the underlying array is sufficiently large.
6661///
6662/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6663/// array type derivation, then for each call to the function, the value of the
6664/// corresponding actual argument shall provide access to the first element of
6665/// an array with at least as many elements as specified by the size expression.
6666void
6667Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6668 ParmVarDecl *Param,
6669 const Expr *ArgExpr) {
6670 // Static array parameters are not supported in C++.
6671 if (!Param || getLangOpts().CPlusPlus)
6672 return;
6673
6674 QualType OrigTy = Param->getOriginalType();
6675
6676 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6677 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6678 return;
6679
6680 if (ArgExpr->isNullPointerConstant(Context,
6681 Expr::NPC_NeverValueDependent)) {
6682 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6683 DiagnoseCalleeStaticArrayParam(*this, Param);
6684 return;
6685 }
6686
6687 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6688 if (!CAT)
6689 return;
6690
6691 const ConstantArrayType *ArgCAT =
6692 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6693 if (!ArgCAT)
6694 return;
6695
6696 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6697 ArgCAT->getElementType())) {
6698 if (ArgCAT->getSize().ult(CAT->getSize())) {
6699 Diag(CallLoc, diag::warn_static_array_too_small)
6700 << ArgExpr->getSourceRange()
6701 << (unsigned)ArgCAT->getSize().getZExtValue()
6702 << (unsigned)CAT->getSize().getZExtValue() << 0;
6703 DiagnoseCalleeStaticArrayParam(*this, Param);
6704 }
6705 return;
6706 }
6707
6708 std::optional<CharUnits> ArgSize =
6709 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6710 std::optional<CharUnits> ParmSize =
6711 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6712 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6713 Diag(CallLoc, diag::warn_static_array_too_small)
6714 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6715 << (unsigned)ParmSize->getQuantity() << 1;
6716 DiagnoseCalleeStaticArrayParam(*this, Param);
6717 }
6718}
6719
6720/// Given a function expression of unknown-any type, try to rebuild it
6721/// to have a function type.
6722static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6723
6724/// Is the given type a placeholder that we need to lower out
6725/// immediately during argument processing?
6726static bool isPlaceholderToRemoveAsArg(QualType type) {
6727 // Placeholders are never sugared.
6728 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6729 if (!placeholder) return false;
6730
6731 switch (placeholder->getKind()) {
6732 // Ignore all the non-placeholder types.
6733#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6734 case BuiltinType::Id:
6735#include "clang/Basic/OpenCLImageTypes.def"
6736#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6737 case BuiltinType::Id:
6738#include "clang/Basic/OpenCLExtensionTypes.def"
6739 // In practice we'll never use this, since all SVE types are sugared
6740 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6741#define SVE_TYPE(Name, Id, SingletonId) \
6742 case BuiltinType::Id:
6743#include "clang/Basic/AArch64SVEACLETypes.def"
6744#define PPC_VECTOR_TYPE(Name, Id, Size) \
6745 case BuiltinType::Id:
6746#include "clang/Basic/PPCTypes.def"
6747#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6748#include "clang/Basic/RISCVVTypes.def"
6749#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6750#include "clang/Basic/WebAssemblyReferenceTypes.def"
6751#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6752#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6753#include "clang/AST/BuiltinTypes.def"
6754 return false;
6755
6756 // We cannot lower out overload sets; they might validly be resolved
6757 // by the call machinery.
6758 case BuiltinType::Overload:
6759 return false;
6760
6761 // Unbridged casts in ARC can be handled in some call positions and
6762 // should be left in place.
6763 case BuiltinType::ARCUnbridgedCast:
6764 return false;
6765
6766 // Pseudo-objects should be converted as soon as possible.
6767 case BuiltinType::PseudoObject:
6768 return true;
6769
6770 // The debugger mode could theoretically but currently does not try
6771 // to resolve unknown-typed arguments based on known parameter types.
6772 case BuiltinType::UnknownAny:
6773 return true;
6774
6775 // These are always invalid as call arguments and should be reported.
6776 case BuiltinType::BoundMember:
6777 case BuiltinType::BuiltinFn:
6778 case BuiltinType::IncompleteMatrixIdx:
6779 case BuiltinType::OMPArraySection:
6780 case BuiltinType::OMPArrayShaping:
6781 case BuiltinType::OMPIterator:
6782 return true;
6783
6784 }
6785 llvm_unreachable("bad builtin type kind");
6786}
6787
6788/// Check an argument list for placeholders that we won't try to
6789/// handle later.
6790static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6791 // Apply this processing to all the arguments at once instead of
6792 // dying at the first failure.
6793 bool hasInvalid = false;
6794 for (size_t i = 0, e = args.size(); i != e; i++) {
6795 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6796 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6797 if (result.isInvalid()) hasInvalid = true;
6798 else args[i] = result.get();
6799 }
6800 }
6801 return hasInvalid;
6802}
6803
6804/// If a builtin function has a pointer argument with no explicit address
6805/// space, then it should be able to accept a pointer to any address
6806/// space as input. In order to do this, we need to replace the
6807/// standard builtin declaration with one that uses the same address space
6808/// as the call.
6809///
6810/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6811/// it does not contain any pointer arguments without
6812/// an address space qualifer. Otherwise the rewritten
6813/// FunctionDecl is returned.
6814/// TODO: Handle pointer return types.
6815static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6816 FunctionDecl *FDecl,
6817 MultiExprArg ArgExprs) {
6818
6819 QualType DeclType = FDecl->getType();
6820 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6821
6822 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6823 ArgExprs.size() < FT->getNumParams())
6824 return nullptr;
6825
6826 bool NeedsNewDecl = false;
6827 unsigned i = 0;
6828 SmallVector<QualType, 8> OverloadParams;
6829
6830 for (QualType ParamType : FT->param_types()) {
6831
6832 // Convert array arguments to pointer to simplify type lookup.
6833 ExprResult ArgRes =
6834 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6835 if (ArgRes.isInvalid())
6836 return nullptr;
6837 Expr *Arg = ArgRes.get();
6838 QualType ArgType = Arg->getType();
6839 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6840 !ArgType->isPointerType() ||
6841 !ArgType->getPointeeType().hasAddressSpace() ||
6842 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6843 OverloadParams.push_back(ParamType);
6844 continue;
6845 }
6846
6847 QualType PointeeType = ParamType->getPointeeType();
6848 if (PointeeType.hasAddressSpace())
6849 continue;
6850
6851 NeedsNewDecl = true;
6852 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6853
6854 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6855 OverloadParams.push_back(Context.getPointerType(PointeeType));
6856 }
6857
6858 if (!NeedsNewDecl)
6859 return nullptr;
6860
6861 FunctionProtoType::ExtProtoInfo EPI;
6862 EPI.Variadic = FT->isVariadic();
6863 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6864 OverloadParams, EPI);
6865 DeclContext *Parent = FDecl->getParent();
6866 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6867 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6868 FDecl->getIdentifier(), OverloadTy,
6869 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6870 false,
6871 /*hasPrototype=*/true);
6872 SmallVector<ParmVarDecl*, 16> Params;
6873 FT = cast<FunctionProtoType>(OverloadTy);
6874 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6875 QualType ParamType = FT->getParamType(i);
6876 ParmVarDecl *Parm =
6877 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6878 SourceLocation(), nullptr, ParamType,
6879 /*TInfo=*/nullptr, SC_None, nullptr);
6880 Parm->setScopeInfo(0, i);
6881 Params.push_back(Parm);
6882 }
6883 OverloadDecl->setParams(Params);
6884 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6885 return OverloadDecl;
6886}
6887
6888static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6889 FunctionDecl *Callee,
6890 MultiExprArg ArgExprs) {
6891 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6892 // similar attributes) really don't like it when functions are called with an
6893 // invalid number of args.
6894 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6895 /*PartialOverloading=*/false) &&
6896 !Callee->isVariadic())
6897 return;
6898 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6899 return;
6900
6901 if (const EnableIfAttr *Attr =
6902 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6903 S.Diag(Fn->getBeginLoc(),
6904 isa<CXXMethodDecl>(Callee)
6905 ? diag::err_ovl_no_viable_member_function_in_call
6906 : diag::err_ovl_no_viable_function_in_call)
6907 << Callee << Callee->getSourceRange();
6908 S.Diag(Callee->getLocation(),
6909 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6910 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6911 return;
6912 }
6913}
6914
6915static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6916 const UnresolvedMemberExpr *const UME, Sema &S) {
6917
6918 const auto GetFunctionLevelDCIfCXXClass =
6919 [](Sema &S) -> const CXXRecordDecl * {
6920 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6921 if (!DC || !DC->getParent())
6922 return nullptr;
6923
6924 // If the call to some member function was made from within a member
6925 // function body 'M' return return 'M's parent.
6926 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6927 return MD->getParent()->getCanonicalDecl();
6928 // else the call was made from within a default member initializer of a
6929 // class, so return the class.
6930 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6931 return RD->getCanonicalDecl();
6932 return nullptr;
6933 };
6934 // If our DeclContext is neither a member function nor a class (in the
6935 // case of a lambda in a default member initializer), we can't have an
6936 // enclosing 'this'.
6937
6938 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6939 if (!CurParentClass)
6940 return false;
6941
6942 // The naming class for implicit member functions call is the class in which
6943 // name lookup starts.
6944 const CXXRecordDecl *const NamingClass =
6945 UME->getNamingClass()->getCanonicalDecl();
6946 assert(NamingClass && "Must have naming class even for implicit access");
6947
6948 // If the unresolved member functions were found in a 'naming class' that is
6949 // related (either the same or derived from) to the class that contains the
6950 // member function that itself contained the implicit member access.
6951
6952 return CurParentClass == NamingClass ||
6953 CurParentClass->isDerivedFrom(NamingClass);
6954}
6955
6956static void
6957tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6958 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6959
6960 if (!UME)
6961 return;
6962
6963 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6964 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6965 // already been captured, or if this is an implicit member function call (if
6966 // it isn't, an attempt to capture 'this' should already have been made).
6967 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6968 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6969 return;
6970
6971 // Check if the naming class in which the unresolved members were found is
6972 // related (same as or is a base of) to the enclosing class.
6973
6974 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6975 return;
6976
6977
6978 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6979 // If the enclosing function is not dependent, then this lambda is
6980 // capture ready, so if we can capture this, do so.
6981 if (!EnclosingFunctionCtx->isDependentContext()) {
6982 // If the current lambda and all enclosing lambdas can capture 'this' -
6983 // then go ahead and capture 'this' (since our unresolved overload set
6984 // contains at least one non-static member function).
6985 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6986 S.CheckCXXThisCapture(CallLoc);
6987 } else if (S.CurContext->isDependentContext()) {
6988 // ... since this is an implicit member reference, that might potentially
6989 // involve a 'this' capture, mark 'this' for potential capture in
6990 // enclosing lambdas.
6991 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6992 CurLSI->addPotentialThisCapture(CallLoc);
6993 }
6994}
6995
6996// Once a call is fully resolved, warn for unqualified calls to specific
6997// C++ standard functions, like move and forward.
6998static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6999 // We are only checking unary move and forward so exit early here.
7000 if (Call->getNumArgs() != 1)
7001 return;
7002
7003 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
7004 if (!E || isa<UnresolvedLookupExpr>(E))
7005 return;
7006 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
7007 if (!DRE || !DRE->getLocation().isValid())
7008 return;
7009
7010 if (DRE->getQualifier())
7011 return;
7012
7013 const FunctionDecl *FD = Call->getDirectCallee();
7014 if (!FD)
7015 return;
7016
7017 // Only warn for some functions deemed more frequent or problematic.
7018 unsigned BuiltinID = FD->getBuiltinID();
7019 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
7020 return;
7021
7022 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
7023 << FD->getQualifiedNameAsString()
7024 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
7025}
7026
7027ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7028 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7029 Expr *ExecConfig) {
7030 ExprResult Call =
7031 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7032 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
7033 if (Call.isInvalid())
7034 return Call;
7035
7036 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
7037 // language modes.
7038 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
7039 if (ULE->hasExplicitTemplateArgs() &&
7040 ULE->decls_begin() == ULE->decls_end()) {
7041 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
7042 ? diag::warn_cxx17_compat_adl_only_template_id
7043 : diag::ext_adl_only_template_id)
7044 << ULE->getName();
7045 }
7046 }
7047
7048 if (LangOpts.OpenMP)
7049 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
7050 ExecConfig);
7051 if (LangOpts.CPlusPlus) {
7052 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
7053 if (CE)
7054 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
7055 }
7056 return Call;
7057}
7058
7059/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7060/// This provides the location of the left/right parens and a list of comma
7061/// locations.
7062ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7063 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7064 Expr *ExecConfig, bool IsExecConfig,
7065 bool AllowRecovery) {
7066 // Since this might be a postfix expression, get rid of ParenListExprs.
7067 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
7068 if (Result.isInvalid()) return ExprError();
7069 Fn = Result.get();
7070
7071 if (checkArgsForPlaceholders(*this, ArgExprs))
7072 return ExprError();
7073
7074 if (getLangOpts().CPlusPlus) {
7075 // If this is a pseudo-destructor expression, build the call immediately.
7076 if (isa<CXXPseudoDestructorExpr>(Fn)) {
7077 if (!ArgExprs.empty()) {
7078 // Pseudo-destructor calls should not have any arguments.
7079 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
7080 << FixItHint::CreateRemoval(
7081 SourceRange(ArgExprs.front()->getBeginLoc(),
7082 ArgExprs.back()->getEndLoc()));
7083 }
7084
7085 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
7086 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7087 }
7088 if (Fn->getType() == Context.PseudoObjectTy) {
7089 ExprResult result = CheckPlaceholderExpr(Fn);
7090 if (result.isInvalid()) return ExprError();
7091 Fn = result.get();
7092 }
7093
7094 // Determine whether this is a dependent call inside a C++ template,
7095 // in which case we won't do any semantic analysis now.
7096 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
7097 if (ExecConfig) {
7098 return CUDAKernelCallExpr::Create(Context, Fn,
7099 cast<CallExpr>(ExecConfig), ArgExprs,
7100 Context.DependentTy, VK_PRValue,
7101 RParenLoc, CurFPFeatureOverrides());
7102 } else {
7103
7104 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7105 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
7106 Fn->getBeginLoc());
7107
7108 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7109 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7110 }
7111 }
7112
7113 // Determine whether this is a call to an object (C++ [over.call.object]).
7114 if (Fn->getType()->isRecordType())
7115 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
7116 RParenLoc);
7117
7118 if (Fn->getType() == Context.UnknownAnyTy) {
7119 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7120 if (result.isInvalid()) return ExprError();
7121 Fn = result.get();
7122 }
7123
7124 if (Fn->getType() == Context.BoundMemberTy) {
7125 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7126 RParenLoc, ExecConfig, IsExecConfig,
7127 AllowRecovery);
7128 }
7129 }
7130
7131 // Check for overloaded calls. This can happen even in C due to extensions.
7132 if (Fn->getType() == Context.OverloadTy) {
7133 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
7134
7135 // We aren't supposed to apply this logic if there's an '&' involved.
7136 if (!find.HasFormOfMemberPointer) {
7137 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
7138 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7139 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7140 OverloadExpr *ovl = find.Expression;
7141 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
7142 return BuildOverloadedCallExpr(
7143 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7144 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
7145 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7146 RParenLoc, ExecConfig, IsExecConfig,
7147 AllowRecovery);
7148 }
7149 }
7150
7151 // If we're directly calling a function, get the appropriate declaration.
7152 if (Fn->getType() == Context.UnknownAnyTy) {
7153 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7154 if (result.isInvalid()) return ExprError();
7155 Fn = result.get();
7156 }
7157
7158 Expr *NakedFn = Fn->IgnoreParens();
7159
7160 bool CallingNDeclIndirectly = false;
7161 NamedDecl *NDecl = nullptr;
7162 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7163 if (UnOp->getOpcode() == UO_AddrOf) {
7164 CallingNDeclIndirectly = true;
7165 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7166 }
7167 }
7168
7169 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7170 NDecl = DRE->getDecl();
7171
7172 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7173 if (FDecl && FDecl->getBuiltinID()) {
7174 // Rewrite the function decl for this builtin by replacing parameters
7175 // with no explicit address space with the address space of the arguments
7176 // in ArgExprs.
7177 if ((FDecl =
7178 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7179 NDecl = FDecl;
7180 Fn = DeclRefExpr::Create(
7181 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7182 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7183 nullptr, DRE->isNonOdrUse());
7184 }
7185 }
7186 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7187 NDecl = ME->getMemberDecl();
7188
7189 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7190 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7191 FD, /*Complain=*/true, Fn->getBeginLoc()))
7192 return ExprError();
7193
7194 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7195
7196 // If this expression is a call to a builtin function in HIP device
7197 // compilation, allow a pointer-type argument to default address space to be
7198 // passed as a pointer-type parameter to a non-default address space.
7199 // If Arg is declared in the default address space and Param is declared
7200 // in a non-default address space, perform an implicit address space cast to
7201 // the parameter type.
7202 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7203 FD->getBuiltinID()) {
7204 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7205 ParmVarDecl *Param = FD->getParamDecl(Idx);
7206 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7207 !ArgExprs[Idx]->getType()->isPointerType())
7208 continue;
7209
7210 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7211 auto ArgTy = ArgExprs[Idx]->getType();
7212 auto ArgPtTy = ArgTy->getPointeeType();
7213 auto ArgAS = ArgPtTy.getAddressSpace();
7214
7215 // Add address space cast if target address spaces are different
7216 bool NeedImplicitASC =
7217 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7218 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7219 // or from specific AS which has target AS matching that of Param.
7220 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
7221 if (!NeedImplicitASC)
7222 continue;
7223
7224 // First, ensure that the Arg is an RValue.
7225 if (ArgExprs[Idx]->isGLValue()) {
7226 ArgExprs[Idx] = ImplicitCastExpr::Create(
7227 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7228 nullptr, VK_PRValue, FPOptionsOverride());
7229 }
7230
7231 // Construct a new arg type with address space of Param
7232 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7233 ArgPtQuals.setAddressSpace(ParamAS);
7234 auto NewArgPtTy =
7235 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7236 auto NewArgTy =
7237 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7238 ArgTy.getQualifiers());
7239
7240 // Finally perform an implicit address space cast
7241 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7242 CK_AddressSpaceConversion)
7243 .get();
7244 }
7245 }
7246 }
7247
7248 if (Context.isDependenceAllowed() &&
7249 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7250 assert(!getLangOpts().CPlusPlus);
7251 assert((Fn->containsErrors() ||
7252 llvm::any_of(ArgExprs,
7253 [](clang::Expr *E) { return E->containsErrors(); })) &&
7254 "should only occur in error-recovery path.");
7255 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7256 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7257 }
7258 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7259 ExecConfig, IsExecConfig);
7260}
7261
7262/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7263// with the specified CallArgs
7264Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7265 MultiExprArg CallArgs) {
7266 StringRef Name = Context.BuiltinInfo.getName(Id);
7267 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7268 Sema::LookupOrdinaryName);
7269 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7270
7271 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7272 assert(BuiltInDecl && "failed to find builtin declaration");
7273
7274 ExprResult DeclRef =
7275 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7276 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7277
7278 ExprResult Call =
7279 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7280
7281 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7282 return Call.get();
7283}
7284
7285/// Parse a __builtin_astype expression.
7286///
7287/// __builtin_astype( value, dst type )
7288///
7289ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7290 SourceLocation BuiltinLoc,
7291 SourceLocation RParenLoc) {
7292 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7293 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7294}
7295
7296/// Create a new AsTypeExpr node (bitcast) from the arguments.
7297ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7298 SourceLocation BuiltinLoc,
7299 SourceLocation RParenLoc) {
7300 ExprValueKind VK = VK_PRValue;
7301 ExprObjectKind OK = OK_Ordinary;
7302 QualType SrcTy = E->getType();
7303 if (!SrcTy->isDependentType() &&
7304 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7305 return ExprError(
7306 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7307 << DestTy << SrcTy << E->getSourceRange());
7308 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7309}
7310
7311/// ActOnConvertVectorExpr - create a new convert-vector expression from the
7312/// provided arguments.
7313///
7314/// __builtin_convertvector( value, dst type )
7315///
7316ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7317 SourceLocation BuiltinLoc,
7318 SourceLocation RParenLoc) {
7319 TypeSourceInfo *TInfo;
7320 GetTypeFromParser(ParsedDestTy, &TInfo);
7321 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7322}
7323
7324/// BuildResolvedCallExpr - Build a call to a resolved expression,
7325/// i.e. an expression not of \p OverloadTy. The expression should
7326/// unary-convert to an expression of function-pointer or
7327/// block-pointer type.
7328///
7329/// \param NDecl the declaration being called, if available
7330ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7331 SourceLocation LParenLoc,
7332 ArrayRef<Expr *> Args,
7333 SourceLocation RParenLoc, Expr *Config,
7334 bool IsExecConfig, ADLCallKind UsesADL) {
7335 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7336 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7337
7338 // Functions with 'interrupt' attribute cannot be called directly.
7339 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7340 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7341 return ExprError();
7342 }
7343
7344 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7345 // so there's some risk when calling out to non-interrupt handler functions
7346 // that the callee might not preserve them. This is easy to diagnose here,
7347 // but can be very challenging to debug.
7348 // Likewise, X86 interrupt handlers may only call routines with attribute
7349 // no_caller_saved_registers since there is no efficient way to
7350 // save and restore the non-GPR state.
7351 if (auto *Caller = getCurFunctionDecl()) {
7352 if (Caller->hasAttr<ARMInterruptAttr>()) {
7353 bool VFP = Context.getTargetInfo().hasFeature("vfp");
7354 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7355 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7356 if (FDecl)
7357 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7358 }
7359 }
7360 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
7361 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
7362 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
7363 if (FDecl)
7364 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7365 }
7366 }
7367
7368 // Promote the function operand.
7369 // We special-case function promotion here because we only allow promoting
7370 // builtin functions to function pointers in the callee of a call.
7371 ExprResult Result;
7372 QualType ResultTy;
7373 if (BuiltinID &&
7374 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7375 // Extract the return type from the (builtin) function pointer type.
7376 // FIXME Several builtins still have setType in
7377 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7378 // Builtins.def to ensure they are correct before removing setType calls.
7379 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7380 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7381 ResultTy = FDecl->getCallResultType();
7382 } else {
7383 Result = CallExprUnaryConversions(Fn);
7384 ResultTy = Context.BoolTy;
7385 }
7386 if (Result.isInvalid())
7387 return ExprError();
7388 Fn = Result.get();
7389
7390 // Check for a valid function type, but only if it is not a builtin which
7391 // requires custom type checking. These will be handled by
7392 // CheckBuiltinFunctionCall below just after creation of the call expression.
7393 const FunctionType *FuncT = nullptr;
7394 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7395 retry:
7396 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7397 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7398 // have type pointer to function".
7399 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7400 if (!FuncT)
7401 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7402 << Fn->getType() << Fn->getSourceRange());
7403 } else if (const BlockPointerType *BPT =
7404 Fn->getType()->getAs<BlockPointerType>()) {
7405 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7406 } else {
7407 // Handle calls to expressions of unknown-any type.
7408 if (Fn->getType() == Context.UnknownAnyTy) {
7409 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7410 if (rewrite.isInvalid())
7411 return ExprError();
7412 Fn = rewrite.get();
7413 goto retry;
7414 }
7415
7416 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7417 << Fn->getType() << Fn->getSourceRange());
7418 }
7419 }
7420
7421 // Get the number of parameters in the function prototype, if any.
7422 // We will allocate space for max(Args.size(), NumParams) arguments
7423 // in the call expression.
7424 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7425 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7426
7427 CallExpr *TheCall;
7428 if (Config) {
7429 assert(UsesADL == ADLCallKind::NotADL &&
7430 "CUDAKernelCallExpr should not use ADL");
7431 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7432 Args, ResultTy, VK_PRValue, RParenLoc,
7433 CurFPFeatureOverrides(), NumParams);
7434 } else {
7435 TheCall =
7436 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7437 CurFPFeatureOverrides(), NumParams, UsesADL);
7438 }
7439
7440 if (!Context.isDependenceAllowed()) {
7441 // Forget about the nulled arguments since typo correction
7442 // do not handle them well.
7443 TheCall->shrinkNumArgs(Args.size());
7444 // C cannot always handle TypoExpr nodes in builtin calls and direct
7445 // function calls as their argument checking don't necessarily handle
7446 // dependent types properly, so make sure any TypoExprs have been
7447 // dealt with.
7448 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7449 if (!Result.isUsable()) return ExprError();
7450 CallExpr *TheOldCall = TheCall;
7451 TheCall = dyn_cast<CallExpr>(Result.get());
7452 bool CorrectedTypos = TheCall != TheOldCall;
7453 if (!TheCall) return Result;
7454 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7455
7456 // A new call expression node was created if some typos were corrected.
7457 // However it may not have been constructed with enough storage. In this
7458 // case, rebuild the node with enough storage. The waste of space is
7459 // immaterial since this only happens when some typos were corrected.
7460 if (CorrectedTypos && Args.size() < NumParams) {
7461 if (Config)
7462 TheCall = CUDAKernelCallExpr::Create(
7463 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7464 RParenLoc, CurFPFeatureOverrides(), NumParams);
7465 else
7466 TheCall =
7467 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7468 CurFPFeatureOverrides(), NumParams, UsesADL);
7469 }
7470 // We can now handle the nulled arguments for the default arguments.
7471 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7472 }
7473
7474 // Bail out early if calling a builtin with custom type checking.
7475 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7476 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7477
7478 if (getLangOpts().CUDA) {
7479 if (Config) {
7480 // CUDA: Kernel calls must be to global functions
7481 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7482 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7483 << FDecl << Fn->getSourceRange());
7484
7485 // CUDA: Kernel function must have 'void' return type
7486 if (!FuncT->getReturnType()->isVoidType() &&
7487 !FuncT->getReturnType()->getAs<AutoType>() &&
7488 !FuncT->getReturnType()->isInstantiationDependentType())
7489 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7490 << Fn->getType() << Fn->getSourceRange());
7491 } else {
7492 // CUDA: Calls to global functions must be configured
7493 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7494 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7495 << FDecl << Fn->getSourceRange());
7496 }
7497 }
7498
7499 // Check for a valid return type
7500 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7501 FDecl))
7502 return ExprError();
7503
7504 // We know the result type of the call, set it.
7505 TheCall->setType(FuncT->getCallResultType(Context));
7506 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7507
7508 // WebAssembly tables can't be used as arguments.
7509 if (Context.getTargetInfo().getTriple().isWasm()) {
7510 for (const Expr *Arg : Args) {
7511 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7512 return ExprError(Diag(Arg->getExprLoc(),
7513 diag::err_wasm_table_as_function_parameter));
7514 }
7515 }
7516 }
7517
7518 if (Proto) {
7519 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7520 IsExecConfig))
7521 return ExprError();
7522 } else {
7523 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7524
7525 if (FDecl) {
7526 // Check if we have too few/too many template arguments, based
7527 // on our knowledge of the function definition.
7528 const FunctionDecl *Def = nullptr;
7529 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7530 Proto = Def->getType()->getAs<FunctionProtoType>();
7531 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7532 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7533 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7534 }
7535
7536 // If the function we're calling isn't a function prototype, but we have
7537 // a function prototype from a prior declaratiom, use that prototype.
7538 if (!FDecl->hasPrototype())
7539 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7540 }
7541
7542 // If we still haven't found a prototype to use but there are arguments to
7543 // the call, diagnose this as calling a function without a prototype.
7544 // However, if we found a function declaration, check to see if
7545 // -Wdeprecated-non-prototype was disabled where the function was declared.
7546 // If so, we will silence the diagnostic here on the assumption that this
7547 // interface is intentional and the user knows what they're doing. We will
7548 // also silence the diagnostic if there is a function declaration but it
7549 // was implicitly defined (the user already gets diagnostics about the
7550 // creation of the implicit function declaration, so the additional warning
7551 // is not helpful).
7552 if (!Proto && !Args.empty() &&
7553 (!FDecl || (!FDecl->isImplicit() &&
7554 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7555 FDecl->getLocation()))))
7556 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7557 << (FDecl != nullptr) << FDecl;
7558
7559 // Promote the arguments (C99 6.5.2.2p6).
7560 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7561 Expr *Arg = Args[i];
7562
7563 if (Proto && i < Proto->getNumParams()) {
7564 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7565 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7566 ExprResult ArgE =
7567 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7568 if (ArgE.isInvalid())
7569 return true;
7570
7571 Arg = ArgE.getAs<Expr>();
7572
7573 } else {
7574 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7575
7576 if (ArgE.isInvalid())
7577 return true;
7578
7579 Arg = ArgE.getAs<Expr>();
7580 }
7581
7582 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7583 diag::err_call_incomplete_argument, Arg))
7584 return ExprError();
7585
7586 TheCall->setArg(i, Arg);
7587 }
7588 TheCall->computeDependence();
7589 }
7590
7591 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7592 if (!Method->isStatic())
7593 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7594 << Fn->getSourceRange());
7595
7596 // Check for sentinels
7597 if (NDecl)
7598 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7599
7600 // Warn for unions passing across security boundary (CMSE).
7601 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7602 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7603 if (const auto *RT =
7604 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7605 if (RT->getDecl()->isOrContainsUnion())
7606 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7607 << 0 << i;
7608 }
7609 }
7610 }
7611
7612 // Do special checking on direct calls to functions.
7613 if (FDecl) {
7614 if (CheckFunctionCall(FDecl, TheCall, Proto))
7615 return ExprError();
7616
7617 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7618
7619 if (BuiltinID)
7620 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7621 } else if (NDecl) {
7622 if (CheckPointerCall(NDecl, TheCall, Proto))
7623 return ExprError();
7624 } else {
7625 if (CheckOtherCall(TheCall, Proto))
7626 return ExprError();
7627 }
7628
7629 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7630}
7631
7632ExprResult
7633Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7634 SourceLocation RParenLoc, Expr *InitExpr) {
7635 assert(Ty && "ActOnCompoundLiteral(): missing type");
7636 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7637
7638 TypeSourceInfo *TInfo;
7639 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7640 if (!TInfo)
7641 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7642
7643 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7644}
7645
7646ExprResult
7647Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7648 SourceLocation RParenLoc, Expr *LiteralExpr) {
7649 QualType literalType = TInfo->getType();
7650
7651 if (literalType->isArrayType()) {
7652 if (RequireCompleteSizedType(
7653 LParenLoc, Context.getBaseElementType(literalType),
7654 diag::err_array_incomplete_or_sizeless_type,
7655 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7656 return ExprError();
7657 if (literalType->isVariableArrayType()) {
7658 // C2x 6.7.9p4: An entity of variable length array type shall not be
7659 // initialized except by an empty initializer.
7660 //
7661 // The C extension warnings are issued from ParseBraceInitializer() and
7662 // do not need to be issued here. However, we continue to issue an error
7663 // in the case there are initializers or we are compiling C++. We allow
7664 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7665 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7666 // FIXME: should we allow this construct in C++ when it makes sense to do
7667 // so?
7668 std::optional<unsigned> NumInits;
7669 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7670 NumInits = ILE->getNumInits();
7671 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7672 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7673 diag::err_variable_object_no_init))
7674 return ExprError();
7675 }
7676 } else if (!literalType->isDependentType() &&
7677 RequireCompleteType(LParenLoc, literalType,
7678 diag::err_typecheck_decl_incomplete_type,
7679 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7680 return ExprError();
7681
7682 InitializedEntity Entity
7683 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7684 InitializationKind Kind
7685 = InitializationKind::CreateCStyleCast(LParenLoc,
7686 SourceRange(LParenLoc, RParenLoc),
7687 /*InitList=*/true);
7688 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7689 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7690 &literalType);
7691 if (Result.isInvalid())
7692 return ExprError();
7693 LiteralExpr = Result.get();
7694
7695 bool isFileScope = !CurContext->isFunctionOrMethod();
7696
7697 // In C, compound literals are l-values for some reason.
7698 // For GCC compatibility, in C++, file-scope array compound literals with
7699 // constant initializers are also l-values, and compound literals are
7700 // otherwise prvalues.
7701 //
7702 // (GCC also treats C++ list-initialized file-scope array prvalues with
7703 // constant initializers as l-values, but that's non-conforming, so we don't
7704 // follow it there.)
7705 //
7706 // FIXME: It would be better to handle the lvalue cases as materializing and
7707 // lifetime-extending a temporary object, but our materialized temporaries
7708 // representation only supports lifetime extension from a variable, not "out
7709 // of thin air".
7710 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7711 // is bound to the result of applying array-to-pointer decay to the compound
7712 // literal.
7713 // FIXME: GCC supports compound literals of reference type, which should
7714 // obviously have a value kind derived from the kind of reference involved.
7715 ExprValueKind VK =
7716 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7717 ? VK_PRValue
7718 : VK_LValue;
7719
7720 if (isFileScope)
7721 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7722 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7723 Expr *Init = ILE->getInit(i);
7724 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7725 }
7726
7727 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7728 VK, LiteralExpr, isFileScope);
7729 if (isFileScope) {
7730 if (!LiteralExpr->isTypeDependent() &&
7731 !LiteralExpr->isValueDependent() &&
7732 !literalType->isDependentType()) // C99 6.5.2.5p3
7733 if (CheckForConstantInitializer(LiteralExpr, literalType))
7734 return ExprError();
7735 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7736 literalType.getAddressSpace() != LangAS::Default) {
7737 // Embedded-C extensions to C99 6.5.2.5:
7738 // "If the compound literal occurs inside the body of a function, the
7739 // type name shall not be qualified by an address-space qualifier."
7740 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7741 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7742 return ExprError();
7743 }
7744
7745 if (!isFileScope && !getLangOpts().CPlusPlus) {
7746 // Compound literals that have automatic storage duration are destroyed at
7747 // the end of the scope in C; in C++, they're just temporaries.
7748
7749 // Emit diagnostics if it is or contains a C union type that is non-trivial
7750 // to destruct.
7751 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7752 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7753 NTCUC_CompoundLiteral, NTCUK_Destruct);
7754
7755 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7756 if (literalType.isDestructedType()) {
7757 Cleanup.setExprNeedsCleanups(true);
7758 ExprCleanupObjects.push_back(E);
7759 getCurFunction()->setHasBranchProtectedScope();
7760 }
7761 }
7762
7763 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7764 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7765 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7766 E->getInitializer()->getExprLoc());
7767
7768 return MaybeBindToTemporary(E);
7769}
7770
7771ExprResult
7772Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7773 SourceLocation RBraceLoc) {
7774 // Only produce each kind of designated initialization diagnostic once.
7775 SourceLocation FirstDesignator;
7776 bool DiagnosedArrayDesignator = false;
7777 bool DiagnosedNestedDesignator = false;
7778 bool DiagnosedMixedDesignator = false;
7779
7780 // Check that any designated initializers are syntactically valid in the
7781 // current language mode.
7782 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7783 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7784 if (FirstDesignator.isInvalid())
7785 FirstDesignator = DIE->getBeginLoc();
7786
7787 if (!getLangOpts().CPlusPlus)
7788 break;
7789
7790 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7791 DiagnosedNestedDesignator = true;
7792 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7793 << DIE->getDesignatorsSourceRange();
7794 }
7795
7796 for (auto &Desig : DIE->designators()) {
7797 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7798 DiagnosedArrayDesignator = true;
7799 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7800 << Desig.getSourceRange();
7801 }
7802 }
7803
7804 if (!DiagnosedMixedDesignator &&
7805 !isa<DesignatedInitExpr>(InitArgList[0])) {
7806 DiagnosedMixedDesignator = true;
7807 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7808 << DIE->getSourceRange();
7809 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7810 << InitArgList[0]->getSourceRange();
7811 }
7812 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7813 isa<DesignatedInitExpr>(InitArgList[0])) {
7814 DiagnosedMixedDesignator = true;
7815 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7816 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7817 << DIE->getSourceRange();
7818 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7819 << InitArgList[I]->getSourceRange();
7820 }
7821 }
7822
7823 if (FirstDesignator.isValid()) {
7824 // Only diagnose designated initiaization as a C++20 extension if we didn't
7825 // already diagnose use of (non-C++20) C99 designator syntax.
7826 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7827 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7828 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7829 ? diag::warn_cxx17_compat_designated_init
7830 : diag::ext_cxx_designated_init);
7831 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7832 Diag(FirstDesignator, diag::ext_designated_init);
7833 }
7834 }
7835
7836 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7837}
7838
7839ExprResult
7840Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7841 SourceLocation RBraceLoc) {
7842 // Semantic analysis for initializers is done by ActOnDeclarator() and
7843 // CheckInitializer() - it requires knowledge of the object being initialized.
7844
7845 // Immediately handle non-overload placeholders. Overloads can be
7846 // resolved contextually, but everything else here can't.
7847 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7848 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7849 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7850
7851 // Ignore failures; dropping the entire initializer list because
7852 // of one failure would be terrible for indexing/etc.
7853 if (result.isInvalid()) continue;
7854
7855 InitArgList[I] = result.get();
7856 }
7857 }
7858
7859 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7860 RBraceLoc);
7861 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7862 return E;
7863}
7864
7865/// Do an explicit extend of the given block pointer if we're in ARC.
7866void Sema::maybeExtendBlockObject(ExprResult &E) {
7867 assert(E.get()->getType()->isBlockPointerType());
7868 assert(E.get()->isPRValue());
7869
7870 // Only do this in an r-value context.
7871 if (!getLangOpts().ObjCAutoRefCount) return;
7872
7873 E = ImplicitCastExpr::Create(
7874 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7875 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7876 Cleanup.setExprNeedsCleanups(true);
7877}
7878
7879/// Prepare a conversion of the given expression to an ObjC object
7880/// pointer type.
7881CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7882 QualType type = E.get()->getType();
7883 if (type->isObjCObjectPointerType()) {
7884 return CK_BitCast;
7885 } else if (type->isBlockPointerType()) {
7886 maybeExtendBlockObject(E);
7887 return CK_BlockPointerToObjCPointerCast;
7888 } else {
7889 assert(type->isPointerType());
7890 return CK_CPointerToObjCPointerCast;
7891 }
7892}
7893
7894/// Prepares for a scalar cast, performing all the necessary stages
7895/// except the final cast and returning the kind required.
7896CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7897 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7898 // Also, callers should have filtered out the invalid cases with
7899 // pointers. Everything else should be possible.
7900
7901 QualType SrcTy = Src.get()->getType();
7902 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7903 return CK_NoOp;
7904
7905 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7906 case Type::STK_MemberPointer:
7907 llvm_unreachable("member pointer type in C");
7908
7909 case Type::STK_CPointer:
7910 case Type::STK_BlockPointer:
7911 case Type::STK_ObjCObjectPointer:
7912 switch (DestTy->getScalarTypeKind()) {
7913 case Type::STK_CPointer: {
7914 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7915 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7916 if (SrcAS != DestAS)
7917 return CK_AddressSpaceConversion;
7918 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7919 return CK_NoOp;
7920 return CK_BitCast;
7921 }
7922 case Type::STK_BlockPointer:
7923 return (SrcKind == Type::STK_BlockPointer
7924 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7925 case Type::STK_ObjCObjectPointer:
7926 if (SrcKind == Type::STK_ObjCObjectPointer)
7927 return CK_BitCast;
7928 if (SrcKind == Type::STK_CPointer)
7929 return CK_CPointerToObjCPointerCast;
7930 maybeExtendBlockObject(Src);
7931 return CK_BlockPointerToObjCPointerCast;
7932 case Type::STK_Bool:
7933 return CK_PointerToBoolean;
7934 case Type::STK_Integral:
7935 return CK_PointerToIntegral;
7936 case Type::STK_Floating:
7937 case Type::STK_FloatingComplex:
7938 case Type::STK_IntegralComplex:
7939 case Type::STK_MemberPointer:
7940 case Type::STK_FixedPoint:
7941 llvm_unreachable("illegal cast from pointer");
7942 }
7943 llvm_unreachable("Should have returned before this");
7944
7945 case Type::STK_FixedPoint:
7946 switch (DestTy->getScalarTypeKind()) {
7947 case Type::STK_FixedPoint:
7948 return CK_FixedPointCast;
7949 case Type::STK_Bool:
7950 return CK_FixedPointToBoolean;
7951 case Type::STK_Integral:
7952 return CK_FixedPointToIntegral;
7953 case Type::STK_Floating:
7954 return CK_FixedPointToFloating;
7955 case Type::STK_IntegralComplex:
7956 case Type::STK_FloatingComplex:
7957 Diag(Src.get()->getExprLoc(),
7958 diag::err_unimplemented_conversion_with_fixed_point_type)
7959 << DestTy;
7960 return CK_IntegralCast;
7961 case Type::STK_CPointer:
7962 case Type::STK_ObjCObjectPointer:
7963 case Type::STK_BlockPointer:
7964 case Type::STK_MemberPointer:
7965 llvm_unreachable("illegal cast to pointer type");
7966 }
7967 llvm_unreachable("Should have returned before this");
7968
7969 case Type::STK_Bool: // casting from bool is like casting from an integer
7970 case Type::STK_Integral:
7971 switch (DestTy->getScalarTypeKind()) {
7972 case Type::STK_CPointer:
7973 case Type::STK_ObjCObjectPointer:
7974 case Type::STK_BlockPointer:
7975 if (Src.get()->isNullPointerConstant(Context,
7976 Expr::NPC_ValueDependentIsNull))
7977 return CK_NullToPointer;
7978 return CK_IntegralToPointer;
7979 case Type::STK_Bool:
7980 return CK_IntegralToBoolean;
7981 case Type::STK_Integral:
7982 return CK_IntegralCast;
7983 case Type::STK_Floating:
7984 return CK_IntegralToFloating;
7985 case Type::STK_IntegralComplex:
7986 Src = ImpCastExprToType(Src.get(),
7987 DestTy->castAs<ComplexType>()->getElementType(),
7988 CK_IntegralCast);
7989 return CK_IntegralRealToComplex;
7990 case Type::STK_FloatingComplex:
7991 Src = ImpCastExprToType(Src.get(),
7992 DestTy->castAs<ComplexType>()->getElementType(),
7993 CK_IntegralToFloating);
7994 return CK_FloatingRealToComplex;
7995 case Type::STK_MemberPointer:
7996 llvm_unreachable("member pointer type in C");
7997 case Type::STK_FixedPoint:
7998 return CK_IntegralToFixedPoint;
7999 }
8000 llvm_unreachable("Should have returned before this");
8001
8002 case Type::STK_Floating:
8003 switch (DestTy->getScalarTypeKind()) {
8004 case Type::STK_Floating:
8005 return CK_FloatingCast;
8006 case Type::STK_Bool:
8007 return CK_FloatingToBoolean;
8008 case Type::STK_Integral:
8009 return CK_FloatingToIntegral;
8010 case Type::STK_FloatingComplex:
8011 Src = ImpCastExprToType(Src.get(),
8012 DestTy->castAs<ComplexType>()->getElementType(),
8013 CK_FloatingCast);
8014 return CK_FloatingRealToComplex;
8015 case Type::STK_IntegralComplex:
8016 Src = ImpCastExprToType(Src.get(),
8017 DestTy->castAs<ComplexType>()->getElementType(),
8018 CK_FloatingToIntegral);
8019 return CK_IntegralRealToComplex;
8020 case Type::STK_CPointer:
8021 case Type::STK_ObjCObjectPointer:
8022 case Type::STK_BlockPointer:
8023 llvm_unreachable("valid float->pointer cast?");
8024 case Type::STK_MemberPointer:
8025 llvm_unreachable("member pointer type in C");
8026 case Type::STK_FixedPoint:
8027 return CK_FloatingToFixedPoint;
8028 }
8029 llvm_unreachable("Should have returned before this");
8030
8031 case Type::STK_FloatingComplex:
8032 switch (DestTy->getScalarTypeKind()) {
8033 case Type::STK_FloatingComplex:
8034 return CK_FloatingComplexCast;
8035 case Type::STK_IntegralComplex:
8036 return CK_FloatingComplexToIntegralComplex;
8037 case Type::STK_Floating: {
8038 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8039 if (Context.hasSameType(ET, DestTy))
8040 return CK_FloatingComplexToReal;
8041 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
8042 return CK_FloatingCast;
8043 }
8044 case Type::STK_Bool:
8045 return CK_FloatingComplexToBoolean;
8046 case Type::STK_Integral:
8047 Src = ImpCastExprToType(Src.get(),
8048 SrcTy->castAs<ComplexType>()->getElementType(),
8049 CK_FloatingComplexToReal);
8050 return CK_FloatingToIntegral;
8051 case Type::STK_CPointer:
8052 case Type::STK_ObjCObjectPointer:
8053 case Type::STK_BlockPointer:
8054 llvm_unreachable("valid complex float->pointer cast?");
8055 case Type::STK_MemberPointer:
8056 llvm_unreachable("member pointer type in C");
8057 case Type::STK_FixedPoint:
8058 Diag(Src.get()->getExprLoc(),
8059 diag::err_unimplemented_conversion_with_fixed_point_type)
8060 << SrcTy;
8061 return CK_IntegralCast;
8062 }
8063 llvm_unreachable("Should have returned before this");
8064
8065 case Type::STK_IntegralComplex:
8066 switch (DestTy->getScalarTypeKind()) {
8067 case Type::STK_FloatingComplex:
8068 return CK_IntegralComplexToFloatingComplex;
8069 case Type::STK_IntegralComplex:
8070 return CK_IntegralComplexCast;
8071 case Type::STK_Integral: {
8072 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8073 if (Context.hasSameType(ET, DestTy))
8074 return CK_IntegralComplexToReal;
8075 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
8076 return CK_IntegralCast;
8077 }
8078 case Type::STK_Bool:
8079 return CK_IntegralComplexToBoolean;
8080 case Type::STK_Floating:
8081 Src = ImpCastExprToType(Src.get(),
8082 SrcTy->castAs<ComplexType>()->getElementType(),
8083 CK_IntegralComplexToReal);
8084 return CK_IntegralToFloating;
8085 case Type::STK_CPointer:
8086 case Type::STK_ObjCObjectPointer:
8087 case Type::STK_BlockPointer:
8088 llvm_unreachable("valid complex int->pointer cast?");
8089 case Type::STK_MemberPointer:
8090 llvm_unreachable("member pointer type in C");
8091 case Type::STK_FixedPoint:
8092 Diag(Src.get()->getExprLoc(),
8093 diag::err_unimplemented_conversion_with_fixed_point_type)
8094 << SrcTy;
8095 return CK_IntegralCast;
8096 }
8097 llvm_unreachable("Should have returned before this");
8098 }
8099
8100 llvm_unreachable("Unhandled scalar cast");
8101}
8102
8103static bool breakDownVectorType(QualType type, uint64_t &len,
8104 QualType &eltType) {
8105 // Vectors are simple.
8106 if (const VectorType *vecType = type->getAs<VectorType>()) {
8107 len = vecType->getNumElements();
8108 eltType = vecType->getElementType();
8109 assert(eltType->isScalarType());
8110 return true;
8111 }
8112
8113 // We allow lax conversion to and from non-vector types, but only if
8114 // they're real types (i.e. non-complex, non-pointer scalar types).
8115 if (!type->isRealType()) return false;
8116
8117 len = 1;
8118 eltType = type;
8119 return true;
8120}
8121
8122/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
8123/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
8124/// allowed?
8125///
8126/// This will also return false if the two given types do not make sense from
8127/// the perspective of SVE bitcasts.
8128bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8129 assert(srcTy->isVectorType() || destTy->isVectorType());
8130
8131 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8132 if (!FirstType->isSVESizelessBuiltinType())
8133 return false;
8134
8135 const auto *VecTy = SecondType->getAs<VectorType>();
8136 return VecTy &&
8137 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
8138 };
8139
8140 return ValidScalableConversion(srcTy, destTy) ||
8141 ValidScalableConversion(destTy, srcTy);
8142}
8143
8144/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
8145/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
8146/// VLS type) allowed?
8147///
8148/// This will also return false if the two given types do not make sense from
8149/// the perspective of RVV bitcasts.
8150bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
8151 assert(srcTy->isVectorType() || destTy->isVectorType());
8152
8153 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8154 if (!FirstType->isRVVSizelessBuiltinType())
8155 return false;
8156
8157 const auto *VecTy = SecondType->getAs<VectorType>();
8158 return VecTy &&
8159 VecTy->getVectorKind() == VectorType::RVVFixedLengthDataVector;
8160 };
8161
8162 return ValidScalableConversion(srcTy, destTy) ||
8163 ValidScalableConversion(destTy, srcTy);
8164}
8165
8166/// Are the two types matrix types and do they have the same dimensions i.e.
8167/// do they have the same number of rows and the same number of columns?
8168bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8169 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8170 return false;
8171
8172 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8173 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8174
8175 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8176 matSrcType->getNumColumns() == matDestType->getNumColumns();
8177}
8178
8179bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8180 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8181
8182 uint64_t SrcLen, DestLen;
8183 QualType SrcEltTy, DestEltTy;
8184 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8185 return false;
8186 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8187 return false;
8188
8189 // ASTContext::getTypeSize will return the size rounded up to a
8190 // power of 2, so instead of using that, we need to use the raw
8191 // element size multiplied by the element count.
8192 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8193 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8194
8195 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8196}
8197
8198// This returns true if at least one of the types is an altivec vector.
8199bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8200 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8201 "expected at least one type to be a vector here");
8202
8203 bool IsSrcTyAltivec =
8204 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8205 VectorType::AltiVecVector) ||
8206 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8207 VectorType::AltiVecBool) ||
8208 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8209 VectorType::AltiVecPixel));
8210
8211 bool IsDestTyAltivec = DestTy->isVectorType() &&
8212 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8213 VectorType::AltiVecVector) ||
8214 (DestTy->castAs<VectorType>()->getVectorKind() ==
8215 VectorType::AltiVecBool) ||
8216 (DestTy->castAs<VectorType>()->getVectorKind() ==
8217 VectorType::AltiVecPixel));
8218
8219 return (IsSrcTyAltivec || IsDestTyAltivec);
8220}
8221
8222/// Are the two types lax-compatible vector types? That is, given
8223/// that one of them is a vector, do they have equal storage sizes,
8224/// where the storage size is the number of elements times the element
8225/// size?
8226///
8227/// This will also return false if either of the types is neither a
8228/// vector nor a real type.
8229bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8230 assert(destTy->isVectorType() || srcTy->isVectorType());
8231
8232 // Disallow lax conversions between scalars and ExtVectors (these
8233 // conversions are allowed for other vector types because common headers
8234 // depend on them). Most scalar OP ExtVector cases are handled by the
8235 // splat path anyway, which does what we want (convert, not bitcast).
8236 // What this rules out for ExtVectors is crazy things like char4*float.
8237 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8238 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8239
8240 return areVectorTypesSameSize(srcTy, destTy);
8241}
8242
8243/// Is this a legal conversion between two types, one of which is
8244/// known to be a vector type?
8245bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8246 assert(destTy->isVectorType() || srcTy->isVectorType());
8247
8248 switch (Context.getLangOpts().getLaxVectorConversions()) {
8249 case LangOptions::LaxVectorConversionKind::None:
8250 return false;
8251
8252 case LangOptions::LaxVectorConversionKind::Integer:
8253 if (!srcTy->isIntegralOrEnumerationType()) {
8254 auto *Vec = srcTy->getAs<VectorType>();
8255 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8256 return false;
8257 }
8258 if (!destTy->isIntegralOrEnumerationType()) {
8259 auto *Vec = destTy->getAs<VectorType>();
8260 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8261 return false;
8262 }
8263 // OK, integer (vector) -> integer (vector) bitcast.
8264 break;
8265
8266 case LangOptions::LaxVectorConversionKind::All:
8267 break;
8268 }
8269
8270 return areLaxCompatibleVectorTypes(srcTy, destTy);
8271}
8272
8273bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8274 CastKind &Kind) {
8275 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8276 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8277 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8278 << DestTy << SrcTy << R;
8279 }
8280 } else if (SrcTy->isMatrixType()) {
8281 return Diag(R.getBegin(),
8282 diag::err_invalid_conversion_between_matrix_and_type)
8283 << SrcTy << DestTy << R;
8284 } else if (DestTy->isMatrixType()) {
8285 return Diag(R.getBegin(),
8286 diag::err_invalid_conversion_between_matrix_and_type)
8287 << DestTy << SrcTy << R;
8288 }
8289
8290 Kind = CK_MatrixCast;
8291 return false;
8292}
8293
8294bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8295 CastKind &Kind) {
8296 assert(VectorTy->isVectorType() && "Not a vector type!");
8297
8298 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8299 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8300 return Diag(R.getBegin(),
8301 Ty->isVectorType() ?
8302 diag::err_invalid_conversion_between_vectors :
8303 diag::err_invalid_conversion_between_vector_and_integer)
8304 << VectorTy << Ty << R;
8305 } else
8306 return Diag(R.getBegin(),
8307 diag::err_invalid_conversion_between_vector_and_scalar)
8308 << VectorTy << Ty << R;
8309
8310 Kind = CK_BitCast;
8311 return false;
8312}
8313
8314ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8315 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8316
8317 if (DestElemTy == SplattedExpr->getType())
8318 return SplattedExpr;
8319
8320 assert(DestElemTy->isFloatingType() ||
8321 DestElemTy->isIntegralOrEnumerationType());
8322
8323 CastKind CK;
8324 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8325 // OpenCL requires that we convert `true` boolean expressions to -1, but
8326 // only when splatting vectors.
8327 if (DestElemTy->isFloatingType()) {
8328 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8329 // in two steps: boolean to signed integral, then to floating.
8330 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8331 CK_BooleanToSignedIntegral);
8332 SplattedExpr = CastExprRes.get();
8333 CK = CK_IntegralToFloating;
8334 } else {
8335 CK = CK_BooleanToSignedIntegral;
8336 }
8337 } else {
8338 ExprResult CastExprRes = SplattedExpr;
8339 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8340 if (CastExprRes.isInvalid())
8341 return ExprError();
8342 SplattedExpr = CastExprRes.get();
8343 }
8344 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8345}
8346
8347ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8348 Expr *CastExpr, CastKind &Kind) {
8349 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8350
8351 QualType SrcTy = CastExpr->getType();
8352
8353 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8354 // an ExtVectorType.
8355 // In OpenCL, casts between vectors of different types are not allowed.
8356 // (See OpenCL 6.2).
8357 if (SrcTy->isVectorType()) {
8358 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8359 (getLangOpts().OpenCL &&
8360 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8361 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8362 << DestTy << SrcTy << R;
8363 return ExprError();
8364 }
8365 Kind = CK_BitCast;
8366 return CastExpr;
8367 }
8368
8369 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8370 // conversion will take place first from scalar to elt type, and then
8371 // splat from elt type to vector.
8372 if (SrcTy->isPointerType())
8373 return Diag(R.getBegin(),
8374 diag::err_invalid_conversion_between_vector_and_scalar)
8375 << DestTy << SrcTy << R;
8376
8377 Kind = CK_VectorSplat;
8378 return prepareVectorSplat(DestTy, CastExpr);
8379}
8380
8381ExprResult
8382Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8383 Declarator &D, ParsedType &Ty,
8384 SourceLocation RParenLoc, Expr *CastExpr) {
8385 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8386 "ActOnCastExpr(): missing type or expr");
8387
8388 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
8389 if (D.isInvalidType())
8390 return ExprError();
8391
8392 if (getLangOpts().CPlusPlus) {
8393 // Check that there are no default arguments (C++ only).
8394 CheckExtraCXXDefaultArguments(D);
8395 } else {
8396 // Make sure any TypoExprs have been dealt with.
8397 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
8398 if (!Res.isUsable())
8399 return ExprError();
8400 CastExpr = Res.get();
8401 }
8402
8403 checkUnusedDeclAttributes(D);
8404
8405 QualType castType = castTInfo->getType();
8406 Ty = CreateParsedType(castType, castTInfo);
8407
8408 bool isVectorLiteral = false;
8409
8410 // Check for an altivec or OpenCL literal,
8411 // i.e. all the elements are integer constants.
8412 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8413 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8414 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8415 && castType->isVectorType() && (PE || PLE)) {
8416 if (PLE && PLE->getNumExprs() == 0) {
8417 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8418 return ExprError();
8419 }
8420 if (PE || PLE->getNumExprs() == 1) {
8421 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8422 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8423 isVectorLiteral = true;
8424 }
8425 else
8426 isVectorLiteral = true;
8427 }
8428
8429 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8430 // then handle it as such.
8431 if (isVectorLiteral)
8432 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8433
8434 // If the Expr being casted is a ParenListExpr, handle it specially.
8435 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8436 // sequence of BinOp comma operators.
8437 if (isa<ParenListExpr>(CastExpr)) {
8438 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8439 if (Result.isInvalid()) return ExprError();
8440 CastExpr = Result.get();
8441 }
8442
8443 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8444 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8445
8446 CheckTollFreeBridgeCast(castType, CastExpr);
8447
8448 CheckObjCBridgeRelatedCast(castType, CastExpr);
8449
8450 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8451
8452 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8453}
8454
8455ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8456 SourceLocation RParenLoc, Expr *E,
8457 TypeSourceInfo *TInfo) {
8458 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8459 "Expected paren or paren list expression");
8460
8461 Expr **exprs;
8462 unsigned numExprs;
8463 Expr *subExpr;
8464 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8465 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8466 LiteralLParenLoc = PE->getLParenLoc();
8467 LiteralRParenLoc = PE->getRParenLoc();
8468 exprs = PE->getExprs();
8469 numExprs = PE->getNumExprs();
8470 } else { // isa<ParenExpr> by assertion at function entrance
8471 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8472 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8473 subExpr = cast<ParenExpr>(E)->getSubExpr();
8474 exprs = &subExpr;
8475 numExprs = 1;
8476 }
8477
8478 QualType Ty = TInfo->getType();
8479 assert(Ty->isVectorType() && "Expected vector type");
8480
8481 SmallVector<Expr *, 8> initExprs;
8482 const VectorType *VTy = Ty->castAs<VectorType>();
8483 unsigned numElems = VTy->getNumElements();
8484
8485 // '(...)' form of vector initialization in AltiVec: the number of
8486 // initializers must be one or must match the size of the vector.
8487 // If a single value is specified in the initializer then it will be
8488 // replicated to all the components of the vector
8489 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8490 VTy->getElementType()))
8491 return ExprError();
8492 if (ShouldSplatAltivecScalarInCast(VTy)) {
8493 // The number of initializers must be one or must match the size of the
8494 // vector. If a single value is specified in the initializer then it will
8495 // be replicated to all the components of the vector
8496 if (numExprs == 1) {
8497 QualType ElemTy = VTy->getElementType();
8498 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8499 if (Literal.isInvalid())
8500 return ExprError();
8501 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8502 PrepareScalarCast(Literal, ElemTy));
8503 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8504 }
8505 else if (numExprs < numElems) {
8506 Diag(E->getExprLoc(),
8507 diag::err_incorrect_number_of_vector_initializers);
8508 return ExprError();
8509 }
8510 else
8511 initExprs.append(exprs, exprs + numExprs);
8512 }
8513 else {
8514 // For OpenCL, when the number of initializers is a single value,
8515 // it will be replicated to all components of the vector.
8516 if (getLangOpts().OpenCL &&
8517 VTy->getVectorKind() == VectorType::GenericVector &&
8518 numExprs == 1) {
8519 QualType ElemTy = VTy->getElementType();
8520 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8521 if (Literal.isInvalid())
8522 return ExprError();
8523 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8524 PrepareScalarCast(Literal, ElemTy));
8525 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8526 }
8527
8528 initExprs.append(exprs, exprs + numExprs);
8529 }
8530 // FIXME: This means that pretty-printing the final AST will produce curly
8531 // braces instead of the original commas.
8532 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8533 initExprs, LiteralRParenLoc);
8534 initE->setType(Ty);
8535 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8536}
8537
8538/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8539/// the ParenListExpr into a sequence of comma binary operators.
8540ExprResult
8541Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8542 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8543 if (!E)
8544 return OrigExpr;
8545
8546 ExprResult Result(E->getExpr(0));
8547
8548 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8549 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8550 E->getExpr(i));
8551
8552 if (Result.isInvalid()) return ExprError();
8553
8554 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8555}
8556
8557ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8558 SourceLocation R,
8559 MultiExprArg Val) {
8560 return ParenListExpr::Create(Context, L, Val, R);
8561}
8562
8563/// Emit a specialized diagnostic when one expression is a null pointer
8564/// constant and the other is not a pointer. Returns true if a diagnostic is
8565/// emitted.
8566bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8567 SourceLocation QuestionLoc) {
8568 Expr *NullExpr = LHSExpr;
8569 Expr *NonPointerExpr = RHSExpr;
8570 Expr::NullPointerConstantKind NullKind =
8571 NullExpr->isNullPointerConstant(Context,
8572 Expr::NPC_ValueDependentIsNotNull);
8573
8574 if (NullKind == Expr::NPCK_NotNull) {
8575 NullExpr = RHSExpr;
8576 NonPointerExpr = LHSExpr;
8577 NullKind =
8578 NullExpr->isNullPointerConstant(Context,
8579 Expr::NPC_ValueDependentIsNotNull);
8580 }
8581
8582 if (NullKind == Expr::NPCK_NotNull)
8583 return false;
8584
8585 if (NullKind == Expr::NPCK_ZeroExpression)
8586 return false;
8587
8588 if (NullKind == Expr::NPCK_ZeroLiteral) {
8589 // In this case, check to make sure that we got here from a "NULL"
8590 // string in the source code.
8591 NullExpr = NullExpr->IgnoreParenImpCasts();
8592 SourceLocation loc = NullExpr->getExprLoc();
8593 if (!findMacroSpelling(loc, "NULL"))
8594 return false;
8595 }
8596
8597 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8598 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8599 << NonPointerExpr->getType() << DiagType
8600 << NonPointerExpr->getSourceRange();
8601 return true;
8602}
8603
8604/// Return false if the condition expression is valid, true otherwise.
8605static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8606 QualType CondTy = Cond->getType();
8607
8608 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8609 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8610 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8611 << CondTy << Cond->getSourceRange();
8612 return true;
8613 }
8614
8615 // C99 6.5.15p2
8616 if (CondTy->isScalarType()) return false;
8617
8618 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8619 << CondTy << Cond->getSourceRange();
8620 return true;
8621}
8622
8623/// Return false if the NullExpr can be promoted to PointerTy,
8624/// true otherwise.
8625static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8626 QualType PointerTy) {
8627 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8628 !NullExpr.get()->isNullPointerConstant(S.Context,
8629 Expr::NPC_ValueDependentIsNull))
8630 return true;
8631
8632 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8633 return false;
8634}
8635
8636/// Checks compatibility between two pointers and return the resulting
8637/// type.
8638static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8639 ExprResult &RHS,
8640 SourceLocation Loc) {
8641 QualType LHSTy = LHS.get()->getType();
8642 QualType RHSTy = RHS.get()->getType();
8643
8644 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8645 // Two identical pointers types are always compatible.
8646 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8647 }
8648
8649 QualType lhptee, rhptee;
8650
8651 // Get the pointee types.
8652 bool IsBlockPointer = false;
8653 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8654 lhptee = LHSBTy->getPointeeType();
8655 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8656 IsBlockPointer = true;
8657 } else {
8658 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8659 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8660 }
8661
8662 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8663 // differently qualified versions of compatible types, the result type is
8664 // a pointer to an appropriately qualified version of the composite
8665 // type.
8666
8667 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8668 // clause doesn't make sense for our extensions. E.g. address space 2 should
8669 // be incompatible with address space 3: they may live on different devices or
8670 // anything.
8671 Qualifiers lhQual = lhptee.getQualifiers();
8672 Qualifiers rhQual = rhptee.getQualifiers();
8673
8674 LangAS ResultAddrSpace = LangAS::Default;
8675 LangAS LAddrSpace = lhQual.getAddressSpace();
8676 LangAS RAddrSpace = rhQual.getAddressSpace();
8677
8678 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8679 // spaces is disallowed.
8680 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8681 ResultAddrSpace = LAddrSpace;
8682 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8683 ResultAddrSpace = RAddrSpace;
8684 else {
8685 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8686 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8687 << RHS.get()->getSourceRange();
8688 return QualType();
8689 }
8690
8691 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8692 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8693 lhQual.removeCVRQualifiers();
8694 rhQual.removeCVRQualifiers();
8695
8696 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8697 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8698 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8699 // qual types are compatible iff
8700 // * corresponded types are compatible
8701 // * CVR qualifiers are equal
8702 // * address spaces are equal
8703 // Thus for conditional operator we merge CVR and address space unqualified
8704 // pointees and if there is a composite type we return a pointer to it with
8705 // merged qualifiers.
8706 LHSCastKind =
8707 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8708 RHSCastKind =
8709 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8710 lhQual.removeAddressSpace();
8711 rhQual.removeAddressSpace();
8712
8713 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8714 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8715
8716 QualType CompositeTy = S.Context.mergeTypes(
8717 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8718 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8719
8720 if (CompositeTy.isNull()) {
8721 // In this situation, we assume void* type. No especially good
8722 // reason, but this is what gcc does, and we do have to pick
8723 // to get a consistent AST.
8724 QualType incompatTy;
8725 incompatTy = S.Context.getPointerType(
8726 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8727 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8728 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8729
8730 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8731 // for casts between types with incompatible address space qualifiers.
8732 // For the following code the compiler produces casts between global and
8733 // local address spaces of the corresponded innermost pointees:
8734 // local int *global *a;
8735 // global int *global *b;
8736 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8737 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8738 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8739 << RHS.get()->getSourceRange();
8740
8741 return incompatTy;
8742 }
8743
8744 // The pointer types are compatible.
8745 // In case of OpenCL ResultTy should have the address space qualifier
8746 // which is a superset of address spaces of both the 2nd and the 3rd
8747 // operands of the conditional operator.
8748 QualType ResultTy = [&, ResultAddrSpace]() {
8749 if (S.getLangOpts().OpenCL) {
8750 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8751 CompositeQuals.setAddressSpace(ResultAddrSpace);
8752 return S.Context
8753 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8754 .withCVRQualifiers(MergedCVRQual);
8755 }
8756 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8757 }();
8758 if (IsBlockPointer)
8759 ResultTy = S.Context.getBlockPointerType(ResultTy);
8760 else
8761 ResultTy = S.Context.getPointerType(ResultTy);
8762
8763 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8764 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8765 return ResultTy;
8766}
8767
8768/// Return the resulting type when the operands are both block pointers.
8769static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8770 ExprResult &LHS,
8771 ExprResult &RHS,
8772 SourceLocation Loc) {
8773 QualType LHSTy = LHS.get()->getType();
8774 QualType RHSTy = RHS.get()->getType();
8775
8776 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8777 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8778 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8779 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8780 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8781 return destType;
8782 }
8783 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8784 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8785 << RHS.get()->getSourceRange();
8786 return QualType();
8787 }
8788
8789 // We have 2 block pointer types.
8790 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8791}
8792
8793/// Return the resulting type when the operands are both pointers.
8794static QualType
8795checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8796 ExprResult &RHS,
8797 SourceLocation Loc) {
8798 // get the pointer types
8799 QualType LHSTy = LHS.get()->getType();
8800 QualType RHSTy = RHS.get()->getType();
8801
8802 // get the "pointed to" types
8803 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8804 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8805
8806 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8807 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8808 // Figure out necessary qualifiers (C99 6.5.15p6)
8809 QualType destPointee
8810 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8811 QualType destType = S.Context.getPointerType(destPointee);
8812 // Add qualifiers if necessary.
8813 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8814 // Promote to void*.
8815 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8816 return destType;
8817 }
8818 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8819 QualType destPointee
8820 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8821 QualType destType = S.Context.getPointerType(destPointee);
8822 // Add qualifiers if necessary.
8823 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8824 // Promote to void*.
8825 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8826 return destType;
8827 }
8828
8829 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8830}
8831
8832/// Return false if the first expression is not an integer and the second
8833/// expression is not a pointer, true otherwise.
8834static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8835 Expr* PointerExpr, SourceLocation Loc,
8836 bool IsIntFirstExpr) {
8837 if (!PointerExpr->getType()->isPointerType() ||
8838 !Int.get()->getType()->isIntegerType())
8839 return false;
8840
8841 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8842 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8843
8844 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8845 << Expr1->getType() << Expr2->getType()
8846 << Expr1->getSourceRange() << Expr2->getSourceRange();
8847 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8848 CK_IntegralToPointer);
8849 return true;
8850}
8851
8852/// Simple conversion between integer and floating point types.
8853///
8854/// Used when handling the OpenCL conditional operator where the
8855/// condition is a vector while the other operands are scalar.
8856///
8857/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8858/// types are either integer or floating type. Between the two
8859/// operands, the type with the higher rank is defined as the "result
8860/// type". The other operand needs to be promoted to the same type. No
8861/// other type promotion is allowed. We cannot use
8862/// UsualArithmeticConversions() for this purpose, since it always
8863/// promotes promotable types.
8864static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8865 ExprResult &RHS,
8866 SourceLocation QuestionLoc) {
8867 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8868 if (LHS.isInvalid())
8869 return QualType();
8870 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8871 if (RHS.isInvalid())
8872 return QualType();
8873
8874 // For conversion purposes, we ignore any qualifiers.
8875 // For example, "const float" and "float" are equivalent.
8876 QualType LHSType =
8877 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8878 QualType RHSType =
8879 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8880
8881 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8882 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8883 << LHSType << LHS.get()->getSourceRange();
8884 return QualType();
8885 }
8886
8887 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8888 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8889 << RHSType << RHS.get()->getSourceRange();
8890 return QualType();
8891 }
8892
8893 // If both types are identical, no conversion is needed.
8894 if (LHSType == RHSType)
8895 return LHSType;
8896
8897 // Now handle "real" floating types (i.e. float, double, long double).
8898 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8899 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8900 /*IsCompAssign = */ false);
8901
8902 // Finally, we have two differing integer types.
8903 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8904 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8905}
8906
8907/// Convert scalar operands to a vector that matches the
8908/// condition in length.
8909///
8910/// Used when handling the OpenCL conditional operator where the
8911/// condition is a vector while the other operands are scalar.
8912///
8913/// We first compute the "result type" for the scalar operands
8914/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8915/// into a vector of that type where the length matches the condition
8916/// vector type. s6.11.6 requires that the element types of the result
8917/// and the condition must have the same number of bits.
8918static QualType
8919OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8920 QualType CondTy, SourceLocation QuestionLoc) {
8921 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8922 if (ResTy.isNull()) return QualType();
8923
8924 const VectorType *CV = CondTy->getAs<VectorType>();
8925 assert(CV);
8926
8927 // Determine the vector result type
8928 unsigned NumElements = CV->getNumElements();
8929 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8930
8931 // Ensure that all types have the same number of bits
8932 if (S.Context.getTypeSize(CV->getElementType())
8933 != S.Context.getTypeSize(ResTy)) {
8934 // Since VectorTy is created internally, it does not pretty print
8935 // with an OpenCL name. Instead, we just print a description.
8936 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8937 SmallString<64> Str;
8938 llvm::raw_svector_ostream OS(Str);
8939 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8940 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8941 << CondTy << OS.str();
8942 return QualType();
8943 }
8944
8945 // Convert operands to the vector result type
8946 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8947 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8948
8949 return VectorTy;
8950}
8951
8952/// Return false if this is a valid OpenCL condition vector
8953static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8954 SourceLocation QuestionLoc) {
8955 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8956 // integral type.
8957 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8958 assert(CondTy);
8959 QualType EleTy = CondTy->getElementType();
8960 if (EleTy->isIntegerType()) return false;
8961
8962 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8963 << Cond->getType() << Cond->getSourceRange();
8964 return true;
8965}
8966
8967/// Return false if the vector condition type and the vector
8968/// result type are compatible.
8969///
8970/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8971/// number of elements, and their element types have the same number
8972/// of bits.
8973static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8974 SourceLocation QuestionLoc) {
8975 const VectorType *CV = CondTy->getAs<VectorType>();
8976 const VectorType *RV = VecResTy->getAs<VectorType>();
8977 assert(CV && RV);
8978
8979 if (CV->getNumElements() != RV->getNumElements()) {
8980 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8981 << CondTy << VecResTy;
8982 return true;
8983 }
8984
8985 QualType CVE = CV->getElementType();
8986 QualType RVE = RV->getElementType();
8987
8988 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8989 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8990 << CondTy << VecResTy;
8991 return true;
8992 }
8993
8994 return false;
8995}
8996
8997/// Return the resulting type for the conditional operator in
8998/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8999/// s6.3.i) when the condition is a vector type.
9000static QualType
9001OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
9002 ExprResult &LHS, ExprResult &RHS,
9003 SourceLocation QuestionLoc) {
9004 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
9005 if (Cond.isInvalid())
9006 return QualType();
9007 QualType CondTy = Cond.get()->getType();
9008
9009 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
9010 return QualType();
9011
9012 // If either operand is a vector then find the vector type of the
9013 // result as specified in OpenCL v1.1 s6.3.i.
9014 if (LHS.get()->getType()->isVectorType() ||
9015 RHS.get()->getType()->isVectorType()) {
9016 bool IsBoolVecLang =
9017 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9018 QualType VecResTy =
9019 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
9020 /*isCompAssign*/ false,
9021 /*AllowBothBool*/ true,
9022 /*AllowBoolConversions*/ false,
9023 /*AllowBooleanOperation*/ IsBoolVecLang,
9024 /*ReportInvalid*/ true);
9025 if (VecResTy.isNull())
9026 return QualType();
9027 // The result type must match the condition type as specified in
9028 // OpenCL v1.1 s6.11.6.
9029 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9030 return QualType();
9031 return VecResTy;
9032 }
9033
9034 // Both operands are scalar.
9035 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9036}
9037
9038/// Return true if the Expr is block type
9039static bool checkBlockType(Sema &S, const Expr *E) {
9040 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9041 QualType Ty = CE->getCallee()->getType();
9042 if (Ty->isBlockPointerType()) {
9043 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
9044 return true;
9045 }
9046 }
9047 return false;
9048}
9049
9050/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9051/// In that case, LHS = cond.
9052/// C99 6.5.15
9053QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9054 ExprResult &RHS, ExprValueKind &VK,
9055 ExprObjectKind &OK,
9056 SourceLocation QuestionLoc) {
9057
9058 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
9059 if (!LHSResult.isUsable()) return QualType();
9060 LHS = LHSResult;
9061
9062 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
9063 if (!RHSResult.isUsable()) return QualType();
9064 RHS = RHSResult;
9065
9066 // C++ is sufficiently different to merit its own checker.
9067 if (getLangOpts().CPlusPlus)
9068 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
9069
9070 VK = VK_PRValue;
9071 OK = OK_Ordinary;
9072
9073 if (Context.isDependenceAllowed() &&
9074 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9075 RHS.get()->isTypeDependent())) {
9076 assert(!getLangOpts().CPlusPlus);
9077 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9078 RHS.get()->containsErrors()) &&
9079 "should only occur in error-recovery path.");
9080 return Context.DependentTy;
9081 }
9082
9083 // The OpenCL operator with a vector condition is sufficiently
9084 // different to merit its own checker.
9085 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9086 Cond.get()->getType()->isExtVectorType())
9087 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
9088
9089 // First, check the condition.
9090 Cond = UsualUnaryConversions(Cond.get());
9091 if (Cond.isInvalid())
9092 return QualType();
9093 if (checkCondition(*this, Cond.get(), QuestionLoc))
9094 return QualType();
9095
9096 // Now check the two expressions.
9097 if (LHS.get()->getType()->isVectorType() ||
9098 RHS.get()->getType()->isVectorType())
9099 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
9100 /*AllowBothBool*/ true,
9101 /*AllowBoolConversions*/ false,
9102 /*AllowBooleanOperation*/ false,
9103 /*ReportInvalid*/ true);
9104
9105 QualType ResTy =
9106 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
9107 if (LHS.isInvalid() || RHS.isInvalid())
9108 return QualType();
9109
9110 // WebAssembly tables are not allowed as conditional LHS or RHS.
9111 QualType LHSTy = LHS.get()->getType();
9112 QualType RHSTy = RHS.get()->getType();
9113 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9114 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9115 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9116 return QualType();
9117 }
9118
9119 // Diagnose attempts to convert between __ibm128, __float128 and long double
9120 // where such conversions currently can't be handled.
9121 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
9122 Diag(QuestionLoc,
9123 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9124 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9125 return QualType();
9126 }
9127
9128 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9129 // selection operator (?:).
9130 if (getLangOpts().OpenCL &&
9131 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
9132 return QualType();
9133 }
9134
9135 // If both operands have arithmetic type, do the usual arithmetic conversions
9136 // to find a common type: C99 6.5.15p3,5.
9137 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9138 // Disallow invalid arithmetic conversions, such as those between bit-
9139 // precise integers types of different sizes, or between a bit-precise
9140 // integer and another type.
9141 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9142 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9143 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9144 << RHS.get()->getSourceRange();
9145 return QualType();
9146 }
9147
9148 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9149 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9150
9151 return ResTy;
9152 }
9153
9154 // And if they're both bfloat (which isn't arithmetic), that's fine too.
9155 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
9156 return Context.getCommonSugaredType(LHSTy, RHSTy);
9157 }
9158
9159 // If both operands are the same structure or union type, the result is that
9160 // type.
9161 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
9162 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
9163 if (LHSRT->getDecl() == RHSRT->getDecl())
9164 // "If both the operands have structure or union type, the result has
9165 // that type." This implies that CV qualifiers are dropped.
9166 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9167 RHSTy.getUnqualifiedType());
9168 // FIXME: Type of conditional expression must be complete in C mode.
9169 }
9170
9171 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9172 // The following || allows only one side to be void (a GCC-ism).
9173 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9174 QualType ResTy;
9175 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9176 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
9177 } else if (RHSTy->isVoidType()) {
9178 ResTy = RHSTy;
9179 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9180 << RHS.get()->getSourceRange();
9181 } else {
9182 ResTy = LHSTy;
9183 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9184 << LHS.get()->getSourceRange();
9185 }
9186 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9187 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9188 return ResTy;
9189 }
9190
9191 // C2x 6.5.15p7:
9192 // ... if both the second and third operands have nullptr_t type, the
9193 // result also has that type.
9194 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9195 return ResTy;
9196
9197 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9198 // the type of the other operand."
9199 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9200 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9201
9202 // All objective-c pointer type analysis is done here.
9203 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
9204 QuestionLoc);
9205 if (LHS.isInvalid() || RHS.isInvalid())
9206 return QualType();
9207 if (!compositeType.isNull())
9208 return compositeType;
9209
9210
9211 // Handle block pointer types.
9212 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9213 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9214 QuestionLoc);
9215
9216 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9217 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9218 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9219 QuestionLoc);
9220
9221 // GCC compatibility: soften pointer/integer mismatch. Note that
9222 // null pointers have been filtered out by this point.
9223 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9224 /*IsIntFirstExpr=*/true))
9225 return RHSTy;
9226 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9227 /*IsIntFirstExpr=*/false))
9228 return LHSTy;
9229
9230 // Allow ?: operations in which both operands have the same
9231 // built-in sizeless type.
9232 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
9233 return Context.getCommonSugaredType(LHSTy, RHSTy);
9234
9235 // Emit a better diagnostic if one of the expressions is a null pointer
9236 // constant and the other is not a pointer type. In this case, the user most
9237 // likely forgot to take the address of the other expression.
9238 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9239 return QualType();
9240
9241 // Otherwise, the operands are not compatible.
9242 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9243 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9244 << RHS.get()->getSourceRange();
9245 return QualType();
9246}
9247
9248/// FindCompositeObjCPointerType - Helper method to find composite type of
9249/// two objective-c pointer types of the two input expressions.
9250QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9251 SourceLocation QuestionLoc) {
9252 QualType LHSTy = LHS.get()->getType();
9253 QualType RHSTy = RHS.get()->getType();
9254
9255 // Handle things like Class and struct objc_class*. Here we case the result
9256 // to the pseudo-builtin, because that will be implicitly cast back to the
9257 // redefinition type if an attempt is made to access its fields.
9258 if (LHSTy->isObjCClassType() &&
9259 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
9260 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9261 return LHSTy;
9262 }
9263 if (RHSTy->isObjCClassType() &&
9264 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
9265 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9266 return RHSTy;
9267 }
9268 // And the same for struct objc_object* / id
9269 if (LHSTy->isObjCIdType() &&
9270 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
9271 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9272 return LHSTy;
9273 }
9274 if (RHSTy->isObjCIdType() &&
9275 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
9276 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9277 return RHSTy;
9278 }
9279 // And the same for struct objc_selector* / SEL
9280 if (Context.isObjCSelType(LHSTy) &&
9281 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
9282 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9283 return LHSTy;
9284 }
9285 if (Context.isObjCSelType(RHSTy) &&
9286 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
9287 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9288 return RHSTy;
9289 }
9290 // Check constraints for Objective-C object pointers types.
9291 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9292
9293 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9294 // Two identical object pointer types are always compatible.
9295 return LHSTy;
9296 }
9297 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9298 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9299 QualType compositeType = LHSTy;
9300
9301 // If both operands are interfaces and either operand can be
9302 // assigned to the other, use that type as the composite
9303 // type. This allows
9304 // xxx ? (A*) a : (B*) b
9305 // where B is a subclass of A.
9306 //
9307 // Additionally, as for assignment, if either type is 'id'
9308 // allow silent coercion. Finally, if the types are
9309 // incompatible then make sure to use 'id' as the composite
9310 // type so the result is acceptable for sending messages to.
9311
9312 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9313 // It could return the composite type.
9314 if (!(compositeType =
9315 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9316 // Nothing more to do.
9317 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9318 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9319 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9320 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9321 } else if ((LHSOPT->isObjCQualifiedIdType() ||
9322 RHSOPT->isObjCQualifiedIdType()) &&
9323 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
9324 true)) {
9325 // Need to handle "id<xx>" explicitly.
9326 // GCC allows qualified id and any Objective-C type to devolve to
9327 // id. Currently localizing to here until clear this should be
9328 // part of ObjCQualifiedIdTypesAreCompatible.
9329 compositeType = Context.getObjCIdType();
9330 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9331 compositeType = Context.getObjCIdType();
9332 } else {
9333 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9334 << LHSTy << RHSTy
9335 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9336 QualType incompatTy = Context.getObjCIdType();
9337 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9338 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9339 return incompatTy;
9340 }
9341 // The object pointer types are compatible.
9342 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9343 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9344 return compositeType;
9345 }
9346 // Check Objective-C object pointer types and 'void *'
9347 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9348 if (getLangOpts().ObjCAutoRefCount) {
9349 // ARC forbids the implicit conversion of object pointers to 'void *',
9350 // so these types are not compatible.
9351 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9352 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9353 LHS = RHS = true;
9354 return QualType();
9355 }
9356 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9357 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9358 QualType destPointee
9359 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9360 QualType destType = Context.getPointerType(destPointee);
9361 // Add qualifiers if necessary.
9362 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9363 // Promote to void*.
9364 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9365 return destType;
9366 }
9367 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9368 if (getLangOpts().ObjCAutoRefCount) {
9369 // ARC forbids the implicit conversion of object pointers to 'void *',
9370 // so these types are not compatible.
9371 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9372 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9373 LHS = RHS = true;
9374 return QualType();
9375 }
9376 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9377 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9378 QualType destPointee
9379 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9380 QualType destType = Context.getPointerType(destPointee);
9381 // Add qualifiers if necessary.
9382 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9383 // Promote to void*.
9384 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9385 return destType;
9386 }
9387 return QualType();
9388}
9389
9390/// SuggestParentheses - Emit a note with a fixit hint that wraps
9391/// ParenRange in parentheses.
9392static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9393 const PartialDiagnostic &Note,
9394 SourceRange ParenRange) {
9395 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9396 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9397 EndLoc.isValid()) {
9398 Self.Diag(Loc, Note)
9399 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9400 << FixItHint::CreateInsertion(EndLoc, ")");
9401 } else {
9402 // We can't display the parentheses, so just show the bare note.
9403 Self.Diag(Loc, Note) << ParenRange;
9404 }
9405}
9406
9407static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9408 return BinaryOperator::isAdditiveOp(Opc) ||
9409 BinaryOperator::isMultiplicativeOp(Opc) ||
9410 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9411 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9412 // not any of the logical operators. Bitwise-xor is commonly used as a
9413 // logical-xor because there is no logical-xor operator. The logical
9414 // operators, including uses of xor, have a high false positive rate for
9415 // precedence warnings.
9416}
9417
9418/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9419/// expression, either using a built-in or overloaded operator,
9420/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9421/// expression.
9422static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
9423 Expr **RHSExprs) {
9424 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9425 E = E->IgnoreImpCasts();
9426 E = E->IgnoreConversionOperatorSingleStep();
9427 E = E->IgnoreImpCasts();
9428 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9429 E = MTE->getSubExpr();
9430 E = E->IgnoreImpCasts();
9431 }
9432
9433 // Built-in binary operator.
9434 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
9435 if (IsArithmeticOp(OP->getOpcode())) {
9436 *Opcode = OP->getOpcode();
9437 *RHSExprs = OP->getRHS();
9438 return true;
9439 }
9440 }
9441
9442 // Overloaded operator.
9443 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9444 if (Call->getNumArgs() != 2)
9445 return false;
9446
9447 // Make sure this is really a binary operator that is safe to pass into
9448 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9449 OverloadedOperatorKind OO = Call->getOperator();
9450 if (OO < OO_Plus || OO > OO_Arrow ||
9451 OO == OO_PlusPlus || OO == OO_MinusMinus)
9452 return false;
9453
9454 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9455 if (IsArithmeticOp(OpKind)) {
9456 *Opcode = OpKind;
9457 *RHSExprs = Call->getArg(1);
9458 return true;
9459 }
9460 }
9461
9462 return false;
9463}
9464
9465/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9466/// or is a logical expression such as (x==y) which has int type, but is
9467/// commonly interpreted as boolean.
9468static bool ExprLooksBoolean(Expr *E) {
9469 E = E->IgnoreParenImpCasts();
9470
9471 if (E->getType()->isBooleanType())
9472 return true;
9473 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9474 return OP->isComparisonOp() || OP->isLogicalOp();
9475 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9476 return OP->getOpcode() == UO_LNot;
9477 if (E->getType()->isPointerType())
9478 return true;
9479 // FIXME: What about overloaded operator calls returning "unspecified boolean
9480 // type"s (commonly pointer-to-members)?
9481
9482 return false;
9483}
9484
9485/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9486/// and binary operator are mixed in a way that suggests the programmer assumed
9487/// the conditional operator has higher precedence, for example:
9488/// "int x = a + someBinaryCondition ? 1 : 2".
9489static void DiagnoseConditionalPrecedence(Sema &Self,
9490 SourceLocation OpLoc,
9491 Expr *Condition,
9492 Expr *LHSExpr,
9493 Expr *RHSExpr) {
9494 BinaryOperatorKind CondOpcode;
9495 Expr *CondRHS;
9496
9497 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9498 return;
9499 if (!ExprLooksBoolean(CondRHS))
9500 return;
9501
9502 // The condition is an arithmetic binary expression, with a right-
9503 // hand side that looks boolean, so warn.
9504
9505 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9506 ? diag::warn_precedence_bitwise_conditional
9507 : diag::warn_precedence_conditional;
9508
9509 Self.Diag(OpLoc, DiagID)
9510 << Condition->getSourceRange()
9511 << BinaryOperator::getOpcodeStr(CondOpcode);
9512
9513 SuggestParentheses(
9514 Self, OpLoc,
9515 Self.PDiag(diag::note_precedence_silence)
9516 << BinaryOperator::getOpcodeStr(CondOpcode),
9517 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9518
9519 SuggestParentheses(Self, OpLoc,
9520 Self.PDiag(diag::note_precedence_conditional_first),
9521 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9522}
9523
9524/// Compute the nullability of a conditional expression.
9525static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9526 QualType LHSTy, QualType RHSTy,
9527 ASTContext &Ctx) {
9528 if (!ResTy->isAnyPointerType())
9529 return ResTy;
9530
9531 auto GetNullability = [](QualType Ty) {
9532 std::optional<NullabilityKind> Kind = Ty->getNullability();
9533 if (Kind) {
9534 // For our purposes, treat _Nullable_result as _Nullable.
9535 if (*Kind == NullabilityKind::NullableResult)
9536 return NullabilityKind::Nullable;
9537 return *Kind;
9538 }
9539 return NullabilityKind::Unspecified;
9540 };
9541
9542 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9543 NullabilityKind MergedKind;
9544
9545 // Compute nullability of a binary conditional expression.
9546 if (IsBin) {
9547 if (LHSKind == NullabilityKind::NonNull)
9548 MergedKind = NullabilityKind::NonNull;
9549 else
9550 MergedKind = RHSKind;
9551 // Compute nullability of a normal conditional expression.
9552 } else {
9553 if (LHSKind == NullabilityKind::Nullable ||
9554 RHSKind == NullabilityKind::Nullable)
9555 MergedKind = NullabilityKind::Nullable;
9556 else if (LHSKind == NullabilityKind::NonNull)
9557 MergedKind = RHSKind;
9558 else if (RHSKind == NullabilityKind::NonNull)
9559 MergedKind = LHSKind;
9560 else
9561 MergedKind = NullabilityKind::Unspecified;
9562 }
9563
9564 // Return if ResTy already has the correct nullability.
9565 if (GetNullability(ResTy) == MergedKind)
9566 return ResTy;
9567
9568 // Strip all nullability from ResTy.
9569 while (ResTy->getNullability())
9570 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9571
9572 // Create a new AttributedType with the new nullability kind.
9573 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9574 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9575}
9576
9577/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9578/// in the case of a the GNU conditional expr extension.
9579ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9580 SourceLocation ColonLoc,
9581 Expr *CondExpr, Expr *LHSExpr,
9582 Expr *RHSExpr) {
9583 if (!Context.isDependenceAllowed()) {
9584 // C cannot handle TypoExpr nodes in the condition because it
9585 // doesn't handle dependent types properly, so make sure any TypoExprs have
9586 // been dealt with before checking the operands.
9587 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9588 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9589 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9590
9591 if (!CondResult.isUsable())
9592 return ExprError();
9593
9594 if (LHSExpr) {
9595 if (!LHSResult.isUsable())
9596 return ExprError();
9597 }
9598
9599 if (!RHSResult.isUsable())
9600 return ExprError();
9601
9602 CondExpr = CondResult.get();
9603 LHSExpr = LHSResult.get();
9604 RHSExpr = RHSResult.get();
9605 }
9606
9607 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9608 // was the condition.
9609 OpaqueValueExpr *opaqueValue = nullptr;
9610 Expr *commonExpr = nullptr;
9611 if (!LHSExpr) {
9612 commonExpr = CondExpr;
9613 // Lower out placeholder types first. This is important so that we don't
9614 // try to capture a placeholder. This happens in few cases in C++; such
9615 // as Objective-C++'s dictionary subscripting syntax.
9616 if (commonExpr->hasPlaceholderType()) {
9617 ExprResult result = CheckPlaceholderExpr(commonExpr);
9618 if (!result.isUsable()) return ExprError();
9619 commonExpr = result.get();
9620 }
9621 // We usually want to apply unary conversions *before* saving, except
9622 // in the special case of a C++ l-value conditional.
9623 if (!(getLangOpts().CPlusPlus
9624 && !commonExpr->isTypeDependent()
9625 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9626 && commonExpr->isGLValue()
9627 && commonExpr->isOrdinaryOrBitFieldObject()
9628 && RHSExpr->isOrdinaryOrBitFieldObject()
9629 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9630 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9631 if (commonRes.isInvalid())
9632 return ExprError();
9633 commonExpr = commonRes.get();
9634 }
9635
9636 // If the common expression is a class or array prvalue, materialize it
9637 // so that we can safely refer to it multiple times.
9638 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9639 commonExpr->getType()->isArrayType())) {
9640 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9641 if (MatExpr.isInvalid())
9642 return ExprError();
9643 commonExpr = MatExpr.get();
9644 }
9645
9646 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9647 commonExpr->getType(),
9648 commonExpr->getValueKind(),
9649 commonExpr->getObjectKind(),
9650 commonExpr);
9651 LHSExpr = CondExpr = opaqueValue;
9652 }
9653
9654 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9655 ExprValueKind VK = VK_PRValue;
9656 ExprObjectKind OK = OK_Ordinary;
9657 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9658 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9659 VK, OK, QuestionLoc);
9660 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9661 RHS.isInvalid())
9662 return ExprError();
9663
9664 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9665 RHS.get());
9666
9667 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9668
9669 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9670 Context);
9671
9672 if (!commonExpr)
9673 return new (Context)
9674 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9675 RHS.get(), result, VK, OK);
9676
9677 return new (Context) BinaryConditionalOperator(
9678 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9679 ColonLoc, result, VK, OK);
9680}
9681
9682// Check if we have a conversion between incompatible cmse function pointer
9683// types, that is, a conversion between a function pointer with the
9684// cmse_nonsecure_call attribute and one without.
9685static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9686 QualType ToType) {
9687 if (const auto *ToFn =
9688 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9689 if (const auto *FromFn =
9690 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9691 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9692 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9693
9694 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9695 }
9696 }
9697 return false;
9698}
9699
9700// checkPointerTypesForAssignment - This is a very tricky routine (despite
9701// being closely modeled after the C99 spec:-). The odd characteristic of this
9702// routine is it effectively iqnores the qualifiers on the top level pointee.
9703// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9704// FIXME: add a couple examples in this comment.
9705static Sema::AssignConvertType
9706checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9707 SourceLocation Loc) {
9708 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9709 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9710
9711 // get the "pointed to" type (ignoring qualifiers at the top level)
9712 const Type *lhptee, *rhptee;
9713 Qualifiers lhq, rhq;
9714 std::tie(lhptee, lhq) =
9715 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9716 std::tie(rhptee, rhq) =
9717 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9718
9719 Sema::AssignConvertType ConvTy = Sema::Compatible;
9720
9721 // C99 6.5.16.1p1: This following citation is common to constraints
9722 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9723 // qualifiers of the type *pointed to* by the right;
9724
9725 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9726 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9727 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9728 // Ignore lifetime for further calculation.
9729 lhq.removeObjCLifetime();
9730 rhq.removeObjCLifetime();
9731 }
9732
9733 if (!lhq.compatiblyIncludes(rhq)) {
9734 // Treat address-space mismatches as fatal.
9735 if (!lhq.isAddressSpaceSupersetOf(rhq))
9736 return Sema::IncompatiblePointerDiscardsQualifiers;
9737
9738 // It's okay to add or remove GC or lifetime qualifiers when converting to
9739 // and from void*.
9740 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9741 .compatiblyIncludes(
9742 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9743 && (lhptee->isVoidType() || rhptee->isVoidType()))
9744 ; // keep old
9745
9746 // Treat lifetime mismatches as fatal.
9747 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9748 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9749
9750 // For GCC/MS compatibility, other qualifier mismatches are treated
9751 // as still compatible in C.
9752 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9753 }
9754
9755 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9756 // incomplete type and the other is a pointer to a qualified or unqualified
9757 // version of void...
9758 if (lhptee->isVoidType()) {
9759 if (rhptee->isIncompleteOrObjectType())
9760 return ConvTy;
9761
9762 // As an extension, we allow cast to/from void* to function pointer.
9763 assert(rhptee->isFunctionType());
9764 return Sema::FunctionVoidPointer;
9765 }
9766
9767 if (rhptee->isVoidType()) {
9768 if (lhptee->isIncompleteOrObjectType())
9769 return ConvTy;
9770
9771 // As an extension, we allow cast to/from void* to function pointer.
9772 assert(lhptee->isFunctionType());
9773 return Sema::FunctionVoidPointer;
9774 }
9775
9776 if (!S.Diags.isIgnored(
9777 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9778 Loc) &&
9779 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9780 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9781 return Sema::IncompatibleFunctionPointerStrict;
9782
9783 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9784 // unqualified versions of compatible types, ...
9785 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9786 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9787 // Check if the pointee types are compatible ignoring the sign.
9788 // We explicitly check for char so that we catch "char" vs
9789 // "unsigned char" on systems where "char" is unsigned.
9790 if (lhptee->isCharType())
9791 ltrans = S.Context.UnsignedCharTy;
9792 else if (lhptee->hasSignedIntegerRepresentation())
9793 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9794
9795 if (rhptee->isCharType())
9796 rtrans = S.Context.UnsignedCharTy;
9797 else if (rhptee->hasSignedIntegerRepresentation())
9798 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9799
9800 if (ltrans == rtrans) {
9801 // Types are compatible ignoring the sign. Qualifier incompatibility
9802 // takes priority over sign incompatibility because the sign
9803 // warning can be disabled.
9804 if (ConvTy != Sema::Compatible)
9805 return ConvTy;
9806
9807 return Sema::IncompatiblePointerSign;
9808 }
9809
9810 // If we are a multi-level pointer, it's possible that our issue is simply
9811 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9812 // the eventual target type is the same and the pointers have the same
9813 // level of indirection, this must be the issue.
9814 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9815 do {
9816 std::tie(lhptee, lhq) =
9817 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9818 std::tie(rhptee, rhq) =
9819 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9820
9821 // Inconsistent address spaces at this point is invalid, even if the
9822 // address spaces would be compatible.
9823 // FIXME: This doesn't catch address space mismatches for pointers of
9824 // different nesting levels, like:
9825 // __local int *** a;
9826 // int ** b = a;
9827 // It's not clear how to actually determine when such pointers are
9828 // invalidly incompatible.
9829 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9830 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9831
9832 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9833
9834 if (lhptee == rhptee)
9835 return Sema::IncompatibleNestedPointerQualifiers;
9836 }
9837
9838 // General pointer incompatibility takes priority over qualifiers.
9839 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9840 return Sema::IncompatibleFunctionPointer;
9841 return Sema::IncompatiblePointer;
9842 }
9843 if (!S.getLangOpts().CPlusPlus &&
9844 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9845 return Sema::IncompatibleFunctionPointer;
9846 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9847 return Sema::IncompatibleFunctionPointer;
9848 return ConvTy;
9849}
9850
9851/// checkBlockPointerTypesForAssignment - This routine determines whether two
9852/// block pointer types are compatible or whether a block and normal pointer
9853/// are compatible. It is more restrict than comparing two function pointer
9854// types.
9855static Sema::AssignConvertType
9856checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9857 QualType RHSType) {
9858 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9859 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9860
9861 QualType lhptee, rhptee;
9862
9863 // get the "pointed to" type (ignoring qualifiers at the top level)
9864 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9865 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9866
9867 // In C++, the types have to match exactly.
9868 if (S.getLangOpts().CPlusPlus)
9869 return Sema::IncompatibleBlockPointer;
9870
9871 Sema::AssignConvertType ConvTy = Sema::Compatible;
9872
9873 // For blocks we enforce that qualifiers are identical.
9874 Qualifiers LQuals = lhptee.getLocalQualifiers();
9875 Qualifiers RQuals = rhptee.getLocalQualifiers();
9876 if (S.getLangOpts().OpenCL) {
9877 LQuals.removeAddressSpace();
9878 RQuals.removeAddressSpace();
9879 }
9880 if (LQuals != RQuals)
9881 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9882
9883 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9884 // assignment.
9885 // The current behavior is similar to C++ lambdas. A block might be
9886 // assigned to a variable iff its return type and parameters are compatible
9887 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9888 // an assignment. Presumably it should behave in way that a function pointer
9889 // assignment does in C, so for each parameter and return type:
9890 // * CVR and address space of LHS should be a superset of CVR and address
9891 // space of RHS.
9892 // * unqualified types should be compatible.
9893 if (S.getLangOpts().OpenCL) {
9894 if (!S.Context.typesAreBlockPointerCompatible(
9895 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9896 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9897 return Sema::IncompatibleBlockPointer;
9898 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9899 return Sema::IncompatibleBlockPointer;
9900
9901 return ConvTy;
9902}
9903
9904/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9905/// for assignment compatibility.
9906static Sema::AssignConvertType
9907checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9908 QualType RHSType) {
9909 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9910 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9911
9912 if (LHSType->isObjCBuiltinType()) {
9913 // Class is not compatible with ObjC object pointers.
9914 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9915 !RHSType->isObjCQualifiedClassType())
9916 return Sema::IncompatiblePointer;
9917 return Sema::Compatible;
9918 }
9919 if (RHSType->isObjCBuiltinType()) {
9920 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9921 !LHSType->isObjCQualifiedClassType())
9922 return Sema::IncompatiblePointer;
9923 return Sema::Compatible;
9924 }
9925 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9926 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9927
9928 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9929 // make an exception for id<P>
9930 !LHSType->isObjCQualifiedIdType())
9931 return Sema::CompatiblePointerDiscardsQualifiers;
9932
9933 if (S.Context.typesAreCompatible(LHSType, RHSType))
9934 return Sema::Compatible;
9935 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9936 return Sema::IncompatibleObjCQualifiedId;
9937 return Sema::IncompatiblePointer;
9938}
9939
9940Sema::AssignConvertType
9941Sema::CheckAssignmentConstraints(SourceLocation Loc,
9942 QualType LHSType, QualType RHSType) {
9943 // Fake up an opaque expression. We don't actually care about what
9944 // cast operations are required, so if CheckAssignmentConstraints
9945 // adds casts to this they'll be wasted, but fortunately that doesn't
9946 // usually happen on valid code.
9947 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9948 ExprResult RHSPtr = &RHSExpr;
9949 CastKind K;
9950
9951 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9952}
9953
9954/// This helper function returns true if QT is a vector type that has element
9955/// type ElementType.
9956static bool isVector(QualType QT, QualType ElementType) {
9957 if (const VectorType *VT = QT->getAs<VectorType>())
9958 return VT->getElementType().getCanonicalType() == ElementType;
9959 return false;
9960}
9961
9962/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9963/// has code to accommodate several GCC extensions when type checking
9964/// pointers. Here are some objectionable examples that GCC considers warnings:
9965///
9966/// int a, *pint;
9967/// short *pshort;
9968/// struct foo *pfoo;
9969///
9970/// pint = pshort; // warning: assignment from incompatible pointer type
9971/// a = pint; // warning: assignment makes integer from pointer without a cast
9972/// pint = a; // warning: assignment makes pointer from integer without a cast
9973/// pint = pfoo; // warning: assignment from incompatible pointer type
9974///
9975/// As a result, the code for dealing with pointers is more complex than the
9976/// C99 spec dictates.
9977///
9978/// Sets 'Kind' for any result kind except Incompatible.
9979Sema::AssignConvertType
9980Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9981 CastKind &Kind, bool ConvertRHS) {
9982 QualType RHSType = RHS.get()->getType();
9983 QualType OrigLHSType = LHSType;
9984
9985 // Get canonical types. We're not formatting these types, just comparing
9986 // them.
9987 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9988 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9989
9990 // Common case: no conversion required.
9991 if (LHSType == RHSType) {
9992 Kind = CK_NoOp;
9993 return Compatible;
9994 }
9995
9996 // If the LHS has an __auto_type, there are no additional type constraints
9997 // to be worried about.
9998 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9999 if (AT->isGNUAutoType()) {
10000 Kind = CK_NoOp;
10001 return Compatible;
10002 }
10003 }
10004
10005 // If we have an atomic type, try a non-atomic assignment, then just add an
10006 // atomic qualification step.
10007 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
10008 Sema::AssignConvertType result =
10009 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
10010 if (result != Compatible)
10011 return result;
10012 if (Kind != CK_NoOp && ConvertRHS)
10013 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
10014 Kind = CK_NonAtomicToAtomic;
10015 return Compatible;
10016 }
10017
10018 // If the left-hand side is a reference type, then we are in a
10019 // (rare!) case where we've allowed the use of references in C,
10020 // e.g., as a parameter type in a built-in function. In this case,
10021 // just make sure that the type referenced is compatible with the
10022 // right-hand side type. The caller is responsible for adjusting
10023 // LHSType so that the resulting expression does not have reference
10024 // type.
10025 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
10026 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
10027 Kind = CK_LValueBitCast;
10028 return Compatible;
10029 }
10030 return Incompatible;
10031 }
10032
10033 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
10034 // to the same ExtVector type.
10035 if (LHSType->isExtVectorType()) {
10036 if (RHSType->isExtVectorType())
10037 return Incompatible;
10038 if (RHSType->isArithmeticType()) {
10039 // CK_VectorSplat does T -> vector T, so first cast to the element type.
10040 if (ConvertRHS)
10041 RHS = prepareVectorSplat(LHSType, RHS.get());
10042 Kind = CK_VectorSplat;
10043 return Compatible;
10044 }
10045 }
10046
10047 // Conversions to or from vector type.
10048 if (LHSType->isVectorType() || RHSType->isVectorType()) {
10049 if (LHSType->isVectorType() && RHSType->isVectorType()) {
10050 // Allow assignments of an AltiVec vector type to an equivalent GCC
10051 // vector type and vice versa
10052 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10053 Kind = CK_BitCast;
10054 return Compatible;
10055 }
10056
10057 // If we are allowing lax vector conversions, and LHS and RHS are both
10058 // vectors, the total size only needs to be the same. This is a bitcast;
10059 // no bits are changed but the result type is different.
10060 if (isLaxVectorConversion(RHSType, LHSType)) {
10061 // The default for lax vector conversions with Altivec vectors will
10062 // change, so if we are converting between vector types where
10063 // at least one is an Altivec vector, emit a warning.
10064 if (Context.getTargetInfo().getTriple().isPPC() &&
10065 anyAltivecTypes(RHSType, LHSType) &&
10066 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10067 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10068 << RHSType << LHSType;
10069 Kind = CK_BitCast;
10070 return IncompatibleVectors;
10071 }
10072 }
10073
10074 // When the RHS comes from another lax conversion (e.g. binops between
10075 // scalars and vectors) the result is canonicalized as a vector. When the
10076 // LHS is also a vector, the lax is allowed by the condition above. Handle
10077 // the case where LHS is a scalar.
10078 if (LHSType->isScalarType()) {
10079 const VectorType *VecType = RHSType->getAs<VectorType>();
10080 if (VecType && VecType->getNumElements() == 1 &&
10081 isLaxVectorConversion(RHSType, LHSType)) {
10082 if (Context.getTargetInfo().getTriple().isPPC() &&
10083 (VecType->getVectorKind() == VectorType::AltiVecVector ||
10084 VecType->getVectorKind() == VectorType::AltiVecBool ||
10085 VecType->getVectorKind() == VectorType::AltiVecPixel))
10086 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10087 << RHSType << LHSType;
10088 ExprResult *VecExpr = &RHS;
10089 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
10090 Kind = CK_BitCast;
10091 return Compatible;
10092 }
10093 }
10094
10095 // Allow assignments between fixed-length and sizeless SVE vectors.
10096 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10097 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10098 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
10099 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
10100 Kind = CK_BitCast;
10101 return Compatible;
10102 }
10103
10104 // Allow assignments between fixed-length and sizeless RVV vectors.
10105 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10106 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10107 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
10108 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
10109 Kind = CK_BitCast;
10110 return Compatible;
10111 }
10112 }
10113
10114 return Incompatible;
10115 }
10116
10117 // Diagnose attempts to convert between __ibm128, __float128 and long double
10118 // where such conversions currently can't be handled.
10119 if (unsupportedTypeConversion(*this, LHSType, RHSType))
10120 return Incompatible;
10121
10122 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10123 // discards the imaginary part.
10124 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10125 !LHSType->getAs<ComplexType>())
10126 return Incompatible;
10127
10128 // Arithmetic conversions.
10129 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10130 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10131 if (ConvertRHS)
10132 Kind = PrepareScalarCast(RHS, LHSType);
10133 return Compatible;
10134 }
10135
10136 // Conversions to normal pointers.
10137 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
10138 // U* -> T*
10139 if (isa<PointerType>(RHSType)) {
10140 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10141 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10142 if (AddrSpaceL != AddrSpaceR)
10143 Kind = CK_AddressSpaceConversion;
10144 else if (Context.hasCvrSimilarType(RHSType, LHSType))
10145 Kind = CK_NoOp;
10146 else
10147 Kind = CK_BitCast;
10148 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10149 RHS.get()->getBeginLoc());
10150 }
10151
10152 // int -> T*
10153 if (RHSType->isIntegerType()) {
10154 Kind = CK_IntegralToPointer; // FIXME: null?
10155 return IntToPointer;
10156 }
10157
10158 // C pointers are not compatible with ObjC object pointers,
10159 // with two exceptions:
10160 if (isa<ObjCObjectPointerType>(RHSType)) {
10161 // - conversions to void*
10162 if (LHSPointer->getPointeeType()->isVoidType()) {
10163 Kind = CK_BitCast;
10164 return Compatible;
10165 }
10166
10167 // - conversions from 'Class' to the redefinition type
10168 if (RHSType->isObjCClassType() &&
10169 Context.hasSameType(LHSType,
10170 Context.getObjCClassRedefinitionType())) {
10171 Kind = CK_BitCast;
10172 return Compatible;
10173 }
10174
10175 Kind = CK_BitCast;
10176 return IncompatiblePointer;
10177 }
10178
10179 // U^ -> void*
10180 if (RHSType->getAs<BlockPointerType>()) {
10181 if (LHSPointer->getPointeeType()->isVoidType()) {
10182 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10183 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10184 ->getPointeeType()
10185 .getAddressSpace();
10186 Kind =
10187 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10188 return Compatible;
10189 }
10190 }
10191
10192 return Incompatible;
10193 }
10194
10195 // Conversions to block pointers.
10196 if (isa<BlockPointerType>(LHSType)) {
10197 // U^ -> T^
10198 if (RHSType->isBlockPointerType()) {
10199 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10200 ->getPointeeType()
10201 .getAddressSpace();
10202 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10203 ->getPointeeType()
10204 .getAddressSpace();
10205 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10206 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10207 }
10208
10209 // int or null -> T^
10210 if (RHSType->isIntegerType()) {
10211 Kind = CK_IntegralToPointer; // FIXME: null
10212 return IntToBlockPointer;
10213 }
10214
10215 // id -> T^
10216 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10217 Kind = CK_AnyPointerToBlockPointerCast;
10218 return Compatible;
10219 }
10220
10221 // void* -> T^
10222 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10223 if (RHSPT->getPointeeType()->isVoidType()) {
10224 Kind = CK_AnyPointerToBlockPointerCast;
10225 return Compatible;
10226 }
10227
10228 return Incompatible;
10229 }
10230
10231 // Conversions to Objective-C pointers.
10232 if (isa<ObjCObjectPointerType>(LHSType)) {
10233 // A* -> B*
10234 if (RHSType->isObjCObjectPointerType()) {
10235 Kind = CK_BitCast;
10236 Sema::AssignConvertType result =
10237 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10238 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10239 result == Compatible &&
10240 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10241 result = IncompatibleObjCWeakRef;
10242 return result;
10243 }
10244
10245 // int or null -> A*
10246 if (RHSType->isIntegerType()) {
10247 Kind = CK_IntegralToPointer; // FIXME: null
10248 return IntToPointer;
10249 }
10250
10251 // In general, C pointers are not compatible with ObjC object pointers,
10252 // with two exceptions:
10253 if (isa<PointerType>(RHSType)) {
10254 Kind = CK_CPointerToObjCPointerCast;
10255
10256 // - conversions from 'void*'
10257 if (RHSType->isVoidPointerType()) {
10258 return Compatible;
10259 }
10260
10261 // - conversions to 'Class' from its redefinition type
10262 if (LHSType->isObjCClassType() &&
10263 Context.hasSameType(RHSType,
10264 Context.getObjCClassRedefinitionType())) {
10265 return Compatible;
10266 }
10267
10268 return IncompatiblePointer;
10269 }
10270
10271 // Only under strict condition T^ is compatible with an Objective-C pointer.
10272 if (RHSType->isBlockPointerType() &&
10273 LHSType->isBlockCompatibleObjCPointerType(Context)) {
10274 if (ConvertRHS)
10275 maybeExtendBlockObject(RHS);
10276 Kind = CK_BlockPointerToObjCPointerCast;
10277 return Compatible;
10278 }
10279
10280 return Incompatible;
10281 }
10282
10283 // Conversion to nullptr_t (C2x only)
10284 if (getLangOpts().C2x && LHSType->isNullPtrType() &&
10285 RHS.get()->isNullPointerConstant(Context,
10286 Expr::NPC_ValueDependentIsNull)) {
10287 // null -> nullptr_t
10288 Kind = CK_NullToPointer;
10289 return Compatible;
10290 }
10291
10292 // Conversions from pointers that are not covered by the above.
10293 if (isa<PointerType>(RHSType)) {
10294 // T* -> _Bool
10295 if (LHSType == Context.BoolTy) {
10296 Kind = CK_PointerToBoolean;
10297 return Compatible;
10298 }
10299
10300 // T* -> int
10301 if (LHSType->isIntegerType()) {
10302 Kind = CK_PointerToIntegral;
10303 return PointerToInt;
10304 }
10305
10306 return Incompatible;
10307 }
10308
10309 // Conversions from Objective-C pointers that are not covered by the above.
10310 if (isa<ObjCObjectPointerType>(RHSType)) {
10311 // T* -> _Bool
10312 if (LHSType == Context.BoolTy) {
10313 Kind = CK_PointerToBoolean;
10314 return Compatible;
10315 }
10316
10317 // T* -> int
10318 if (LHSType->isIntegerType()) {
10319 Kind = CK_PointerToIntegral;
10320 return PointerToInt;
10321 }
10322
10323 return Incompatible;
10324 }
10325
10326 // struct A -> struct B
10327 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10328 if (Context.typesAreCompatible(LHSType, RHSType)) {
10329 Kind = CK_NoOp;
10330 return Compatible;
10331 }
10332 }
10333
10334 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10335 Kind = CK_IntToOCLSampler;
10336 return Compatible;
10337 }
10338
10339 return Incompatible;
10340}
10341
10342/// Constructs a transparent union from an expression that is
10343/// used to initialize the transparent union.
10344static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10345 ExprResult &EResult, QualType UnionType,
10346 FieldDecl *Field) {
10347 // Build an initializer list that designates the appropriate member
10348 // of the transparent union.
10349 Expr *E = EResult.get();
10350 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10351 E, SourceLocation());
10352 Initializer->setType(UnionType);
10353 Initializer->setInitializedFieldInUnion(Field);
10354
10355 // Build a compound literal constructing a value of the transparent
10356 // union type from this initializer list.
10357 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10358 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10359 VK_PRValue, Initializer, false);
10360}
10361
10362Sema::AssignConvertType
10363Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10364 ExprResult &RHS) {
10365 QualType RHSType = RHS.get()->getType();
10366
10367 // If the ArgType is a Union type, we want to handle a potential
10368 // transparent_union GCC extension.
10369 const RecordType *UT = ArgType->getAsUnionType();
10370 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10371 return Incompatible;
10372
10373 // The field to initialize within the transparent union.
10374 RecordDecl *UD = UT->getDecl();
10375 FieldDecl *InitField = nullptr;
10376 // It's compatible if the expression matches any of the fields.
10377 for (auto *it : UD->fields()) {
10378 if (it->getType()->isPointerType()) {
10379 // If the transparent union contains a pointer type, we allow:
10380 // 1) void pointer
10381 // 2) null pointer constant
10382 if (RHSType->isPointerType())
10383 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10384 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10385 InitField = it;
10386 break;
10387 }
10388
10389 if (RHS.get()->isNullPointerConstant(Context,
10390 Expr::NPC_ValueDependentIsNull)) {
10391 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10392 CK_NullToPointer);
10393 InitField = it;
10394 break;
10395 }
10396 }
10397
10398 CastKind Kind;
10399 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10400 == Compatible) {
10401 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10402 InitField = it;
10403 break;
10404 }
10405 }
10406
10407 if (!InitField)
10408 return Incompatible;
10409
10410 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10411 return Compatible;
10412}
10413
10414Sema::AssignConvertType
10415Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10416 bool Diagnose,
10417 bool DiagnoseCFAudited,
10418 bool ConvertRHS) {
10419 // We need to be able to tell the caller whether we diagnosed a problem, if
10420 // they ask us to issue diagnostics.
10421 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10422
10423 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10424 // we can't avoid *all* modifications at the moment, so we need some somewhere
10425 // to put the updated value.
10426 ExprResult LocalRHS = CallerRHS;
10427 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10428
10429 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10430 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10431 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10432 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10433 Diag(RHS.get()->getExprLoc(),
10434 diag::warn_noderef_to_dereferenceable_pointer)
10435 << RHS.get()->getSourceRange();
10436 }
10437 }
10438 }
10439
10440 if (getLangOpts().CPlusPlus) {
10441 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10442 // C++ 5.17p3: If the left operand is not of class type, the
10443 // expression is implicitly converted (C++ 4) to the
10444 // cv-unqualified type of the left operand.
10445 QualType RHSType = RHS.get()->getType();
10446 if (Diagnose) {
10447 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10448 AA_Assigning);
10449 } else {
10450 ImplicitConversionSequence ICS =
10451 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10452 /*SuppressUserConversions=*/false,
10453 AllowedExplicit::None,
10454 /*InOverloadResolution=*/false,
10455 /*CStyle=*/false,
10456 /*AllowObjCWritebackConversion=*/false);
10457 if (ICS.isFailure())
10458 return Incompatible;
10459 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10460 ICS, AA_Assigning);
10461 }
10462 if (RHS.isInvalid())
10463 return Incompatible;
10464 Sema::AssignConvertType result = Compatible;
10465 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10466 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10467 result = IncompatibleObjCWeakRef;
10468 return result;
10469 }
10470
10471 // FIXME: Currently, we fall through and treat C++ classes like C
10472 // structures.
10473 // FIXME: We also fall through for atomics; not sure what should
10474 // happen there, though.
10475 } else if (RHS.get()->getType() == Context.OverloadTy) {
10476 // As a set of extensions to C, we support overloading on functions. These
10477 // functions need to be resolved here.
10478 DeclAccessPair DAP;
10479 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10480 RHS.get(), LHSType, /*Complain=*/false, DAP))
10481 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10482 else
10483 return Incompatible;
10484 }
10485
10486 // This check seems unnatural, however it is necessary to ensure the proper
10487 // conversion of functions/arrays. If the conversion were done for all
10488 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10489 // expressions that suppress this implicit conversion (&, sizeof). This needs
10490 // to happen before we check for null pointer conversions because C does not
10491 // undergo the same implicit conversions as C++ does above (by the calls to
10492 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10493 // lvalue to rvalue cast before checking for null pointer constraints. This
10494 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10495 //
10496 // Suppress this for references: C++ 8.5.3p5.
10497 if (!LHSType->isReferenceType()) {
10498 // FIXME: We potentially allocate here even if ConvertRHS is false.
10499 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10500 if (RHS.isInvalid())
10501 return Incompatible;
10502 }
10503
10504 // The constraints are expressed in terms of the atomic, qualified, or
10505 // unqualified type of the LHS.
10506 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10507
10508 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10509 // a null pointer constant <C2x>or its type is nullptr_t;</C2x>.
10510 if ((LHSTypeAfterConversion->isPointerType() ||
10511 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10512 LHSTypeAfterConversion->isBlockPointerType()) &&
10513 ((getLangOpts().C2x && RHS.get()->getType()->isNullPtrType()) ||
10514 RHS.get()->isNullPointerConstant(Context,
10515 Expr::NPC_ValueDependentIsNull))) {
10516 if (Diagnose || ConvertRHS) {
10517 CastKind Kind;
10518 CXXCastPath Path;
10519 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10520 /*IgnoreBaseAccess=*/false, Diagnose);
10521 if (ConvertRHS)
10522 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10523 }
10524 return Compatible;
10525 }
10526 // C2x 6.5.16.1p1: the left operand has type atomic, qualified, or
10527 // unqualified bool, and the right operand is a pointer or its type is
10528 // nullptr_t.
10529 if (getLangOpts().C2x && LHSType->isBooleanType() &&
10530 RHS.get()->getType()->isNullPtrType()) {
10531 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10532 // only handles nullptr -> _Bool due to needing an extra conversion
10533 // step.
10534 // We model this by converting from nullptr -> void * and then let the
10535 // conversion from void * -> _Bool happen naturally.
10536 if (Diagnose || ConvertRHS) {
10537 CastKind Kind;
10538 CXXCastPath Path;
10539 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10540 /*IgnoreBaseAccess=*/false, Diagnose);
10541 if (ConvertRHS)
10542 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10543 &Path);
10544 }
10545 }
10546
10547 // OpenCL queue_t type assignment.
10548 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10549 Context, Expr::NPC_ValueDependentIsNull)) {
10550 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10551 return Compatible;
10552 }
10553
10554 CastKind Kind;
10555 Sema::AssignConvertType result =
10556 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10557
10558 // C99 6.5.16.1p2: The value of the right operand is converted to the
10559 // type of the assignment expression.
10560 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10561 // so that we can use references in built-in functions even in C.
10562 // The getNonReferenceType() call makes sure that the resulting expression
10563 // does not have reference type.
10564 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10565 QualType Ty = LHSType.getNonLValueExprType(Context);
10566 Expr *E = RHS.get();
10567
10568 // Check for various Objective-C errors. If we are not reporting
10569 // diagnostics and just checking for errors, e.g., during overload
10570 // resolution, return Incompatible to indicate the failure.
10571 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10572 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10573 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10574 if (!Diagnose)
10575 return Incompatible;
10576 }
10577 if (getLangOpts().ObjC &&
10578 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10579 E->getType(), E, Diagnose) ||
10580 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10581 if (!Diagnose)
10582 return Incompatible;
10583 // Replace the expression with a corrected version and continue so we
10584 // can find further errors.
10585 RHS = E;
10586 return Compatible;
10587 }
10588
10589 if (ConvertRHS)
10590 RHS = ImpCastExprToType(E, Ty, Kind);
10591 }
10592
10593 return result;
10594}
10595
10596namespace {
10597/// The original operand to an operator, prior to the application of the usual
10598/// arithmetic conversions and converting the arguments of a builtin operator
10599/// candidate.
10600struct OriginalOperand {
10601 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10602 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10603 Op = MTE->getSubExpr();
10604 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10605 Op = BTE->getSubExpr();
10606 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10607 Orig = ICE->getSubExprAsWritten();
10608 Conversion = ICE->getConversionFunction();
10609 }
10610 }
10611
10612 QualType getType() const { return Orig->getType(); }
10613
10614 Expr *Orig;
10615 NamedDecl *Conversion;
10616};
10617}
10618
10619QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10620 ExprResult &RHS) {
10621 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10622
10623 Diag(Loc, diag::err_typecheck_invalid_operands)
10624 << OrigLHS.getType() << OrigRHS.getType()
10625 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10626
10627 // If a user-defined conversion was applied to either of the operands prior
10628 // to applying the built-in operator rules, tell the user about it.
10629 if (OrigLHS.Conversion) {
10630 Diag(OrigLHS.Conversion->getLocation(),
10631 diag::note_typecheck_invalid_operands_converted)
10632 << 0 << LHS.get()->getType();
10633 }
10634 if (OrigRHS.Conversion) {
10635 Diag(OrigRHS.Conversion->getLocation(),
10636 diag::note_typecheck_invalid_operands_converted)
10637 << 1 << RHS.get()->getType();
10638 }
10639
10640 return QualType();
10641}
10642
10643// Diagnose cases where a scalar was implicitly converted to a vector and
10644// diagnose the underlying types. Otherwise, diagnose the error
10645// as invalid vector logical operands for non-C++ cases.
10646QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10647 ExprResult &RHS) {
10648 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10649 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10650
10651 bool LHSNatVec = LHSType->isVectorType();
10652 bool RHSNatVec = RHSType->isVectorType();
10653
10654 if (!(LHSNatVec && RHSNatVec)) {
10655 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10656 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10657 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10658 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10659 << Vector->getSourceRange();
10660 return QualType();
10661 }
10662
10663 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10664 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10665 << RHS.get()->getSourceRange();
10666
10667 return QualType();
10668}
10669
10670/// Try to convert a value of non-vector type to a vector type by converting
10671/// the type to the element type of the vector and then performing a splat.
10672/// If the language is OpenCL, we only use conversions that promote scalar
10673/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10674/// for float->int.
10675///
10676/// OpenCL V2.0 6.2.6.p2:
10677/// An error shall occur if any scalar operand type has greater rank
10678/// than the type of the vector element.
10679///
10680/// \param scalar - if non-null, actually perform the conversions
10681/// \return true if the operation fails (but without diagnosing the failure)
10682static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10683 QualType scalarTy,
10684 QualType vectorEltTy,
10685 QualType vectorTy,
10686 unsigned &DiagID) {
10687 // The conversion to apply to the scalar before splatting it,
10688 // if necessary.
10689 CastKind scalarCast = CK_NoOp;
10690
10691 if (vectorEltTy->isIntegralType(S.Context)) {
10692 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10693 (scalarTy->isIntegerType() &&
10694 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10695 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10696 return true;
10697 }
10698 if (!scalarTy->isIntegralType(S.Context))
10699 return true;
10700 scalarCast = CK_IntegralCast;
10701 } else if (vectorEltTy->isRealFloatingType()) {
10702 if (scalarTy->isRealFloatingType()) {
10703 if (S.getLangOpts().OpenCL &&
10704 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10705 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10706 return true;
10707 }
10708 scalarCast = CK_FloatingCast;
10709 }
10710 else if (scalarTy->isIntegralType(S.Context))
10711 scalarCast = CK_IntegralToFloating;
10712 else
10713 return true;
10714 } else {
10715 return true;
10716 }
10717
10718 // Adjust scalar if desired.
10719 if (scalar) {
10720 if (scalarCast != CK_NoOp)
10721 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10722 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10723 }
10724 return false;
10725}
10726
10727/// Convert vector E to a vector with the same number of elements but different
10728/// element type.
10729static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10730 const auto *VecTy = E->getType()->getAs<VectorType>();
10731 assert(VecTy && "Expression E must be a vector");
10732 QualType NewVecTy =
10733 VecTy->isExtVectorType()
10734 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10735 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10736 VecTy->getVectorKind());
10737
10738 // Look through the implicit cast. Return the subexpression if its type is
10739 // NewVecTy.
10740 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10741 if (ICE->getSubExpr()->getType() == NewVecTy)
10742 return ICE->getSubExpr();
10743
10744 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10745 return S.ImpCastExprToType(E, NewVecTy, Cast);
10746}
10747
10748/// Test if a (constant) integer Int can be casted to another integer type
10749/// IntTy without losing precision.
10750static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10751 QualType OtherIntTy) {
10752 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10753
10754 // Reject cases where the value of the Int is unknown as that would
10755 // possibly cause truncation, but accept cases where the scalar can be
10756 // demoted without loss of precision.
10757 Expr::EvalResult EVResult;
10758 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10759 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10760 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10761 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10762
10763 if (CstInt) {
10764 // If the scalar is constant and is of a higher order and has more active
10765 // bits that the vector element type, reject it.
10766 llvm::APSInt Result = EVResult.Val.getInt();
10767 unsigned NumBits = IntSigned
10768 ? (Result.isNegative() ? Result.getSignificantBits()
10769 : Result.getActiveBits())
10770 : Result.getActiveBits();
10771 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10772 return true;
10773
10774 // If the signedness of the scalar type and the vector element type
10775 // differs and the number of bits is greater than that of the vector
10776 // element reject it.
10777 return (IntSigned != OtherIntSigned &&
10778 NumBits > S.Context.getIntWidth(OtherIntTy));
10779 }
10780
10781 // Reject cases where the value of the scalar is not constant and it's
10782 // order is greater than that of the vector element type.
10783 return (Order < 0);
10784}
10785
10786/// Test if a (constant) integer Int can be casted to floating point type
10787/// FloatTy without losing precision.
10788static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10789 QualType FloatTy) {
10790 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10791
10792 // Determine if the integer constant can be expressed as a floating point
10793 // number of the appropriate type.
10794 Expr::EvalResult EVResult;
10795 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10796
10797 uint64_t Bits = 0;
10798 if (CstInt) {
10799 // Reject constants that would be truncated if they were converted to
10800 // the floating point type. Test by simple to/from conversion.
10801 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10802 // could be avoided if there was a convertFromAPInt method
10803 // which could signal back if implicit truncation occurred.
10804 llvm::APSInt Result = EVResult.Val.getInt();
10805 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10806 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10807 llvm::APFloat::rmTowardZero);
10808 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10809 !IntTy->hasSignedIntegerRepresentation());
10810 bool Ignored = false;
10811 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10812 &Ignored);
10813 if (Result != ConvertBack)
10814 return true;
10815 } else {
10816 // Reject types that cannot be fully encoded into the mantissa of
10817 // the float.
10818 Bits = S.Context.getTypeSize(IntTy);
10819 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10820 S.Context.getFloatTypeSemantics(FloatTy));
10821 if (Bits > FloatPrec)
10822 return true;
10823 }
10824
10825 return false;
10826}
10827
10828/// Attempt to convert and splat Scalar into a vector whose types matches
10829/// Vector following GCC conversion rules. The rule is that implicit
10830/// conversion can occur when Scalar can be casted to match Vector's element
10831/// type without causing truncation of Scalar.
10832static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10833 ExprResult *Vector) {
10834 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10835 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10836 QualType VectorEltTy;
10837
10838 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10839 assert(!isa<ExtVectorType>(VT) &&
10840 "ExtVectorTypes should not be handled here!");
10841 VectorEltTy = VT->getElementType();
10842 } else if (VectorTy->isVLSTBuiltinType()) {
10843 VectorEltTy =
10844 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10845 } else {
10846 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10847 }
10848
10849 // Reject cases where the vector element type or the scalar element type are
10850 // not integral or floating point types.
10851 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10852 return true;
10853
10854 // The conversion to apply to the scalar before splatting it,
10855 // if necessary.
10856 CastKind ScalarCast = CK_NoOp;
10857
10858 // Accept cases where the vector elements are integers and the scalar is
10859 // an integer.
10860 // FIXME: Notionally if the scalar was a floating point value with a precise
10861 // integral representation, we could cast it to an appropriate integer
10862 // type and then perform the rest of the checks here. GCC will perform
10863 // this conversion in some cases as determined by the input language.
10864 // We should accept it on a language independent basis.
10865 if (VectorEltTy->isIntegralType(S.Context) &&
10866 ScalarTy->isIntegralType(S.Context) &&
10867 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10868
10869 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10870 return true;
10871
10872 ScalarCast = CK_IntegralCast;
10873 } else if (VectorEltTy->isIntegralType(S.Context) &&
10874 ScalarTy->isRealFloatingType()) {
10875 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10876 ScalarCast = CK_FloatingToIntegral;
10877 else
10878 return true;
10879 } else if (VectorEltTy->isRealFloatingType()) {
10880 if (ScalarTy->isRealFloatingType()) {
10881
10882 // Reject cases where the scalar type is not a constant and has a higher
10883 // Order than the vector element type.
10884 llvm::APFloat Result(0.0);
10885
10886 // Determine whether this is a constant scalar. In the event that the
10887 // value is dependent (and thus cannot be evaluated by the constant
10888 // evaluator), skip the evaluation. This will then diagnose once the
10889 // expression is instantiated.
10890 bool CstScalar = Scalar->get()->isValueDependent() ||
10891 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10892 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10893 if (!CstScalar && Order < 0)
10894 return true;
10895
10896 // If the scalar cannot be safely casted to the vector element type,
10897 // reject it.
10898 if (CstScalar) {
10899 bool Truncated = false;
10900 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10901 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10902 if (Truncated)
10903 return true;
10904 }
10905
10906 ScalarCast = CK_FloatingCast;
10907 } else if (ScalarTy->isIntegralType(S.Context)) {
10908 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10909 return true;
10910
10911 ScalarCast = CK_IntegralToFloating;
10912 } else
10913 return true;
10914 } else if (ScalarTy->isEnumeralType())
10915 return true;
10916
10917 // Adjust scalar if desired.
10918 if (ScalarCast != CK_NoOp)
10919 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10920 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10921 return false;
10922}
10923
10924QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10925 SourceLocation Loc, bool IsCompAssign,
10926 bool AllowBothBool,
10927 bool AllowBoolConversions,
10928 bool AllowBoolOperation,
10929 bool ReportInvalid) {
10930 if (!IsCompAssign) {
10931 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10932 if (LHS.isInvalid())
10933 return QualType();
10934 }
10935 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10936 if (RHS.isInvalid())
10937 return QualType();
10938
10939 // For conversion purposes, we ignore any qualifiers.
10940 // For example, "const float" and "float" are equivalent.
10941 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10942 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10943
10944 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10945 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10946 assert(LHSVecType || RHSVecType);
10947
10948 // AltiVec-style "vector bool op vector bool" combinations are allowed
10949 // for some operators but not others.
10950 if (!AllowBothBool &&
10951 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10952 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10953 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10954
10955 // This operation may not be performed on boolean vectors.
10956 if (!AllowBoolOperation &&
10957 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10958 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10959
10960 // If the vector types are identical, return.
10961 if (Context.hasSameType(LHSType, RHSType))
10962 return Context.getCommonSugaredType(LHSType, RHSType);
10963
10964 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10965 if (LHSVecType && RHSVecType &&
10966 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10967 if (isa<ExtVectorType>(LHSVecType)) {
10968 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10969 return LHSType;
10970 }
10971
10972 if (!IsCompAssign)
10973 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10974 return RHSType;
10975 }
10976
10977 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10978 // can be mixed, with the result being the non-bool type. The non-bool
10979 // operand must have integer element type.
10980 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10981 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10982 (Context.getTypeSize(LHSVecType->getElementType()) ==
10983 Context.getTypeSize(RHSVecType->getElementType()))) {
10984 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10985 LHSVecType->getElementType()->isIntegerType() &&
10986 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10987 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10988 return LHSType;
10989 }
10990 if (!IsCompAssign &&
10991 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10992 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10993 RHSVecType->getElementType()->isIntegerType()) {
10994 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10995 return RHSType;
10996 }
10997 }
10998
10999 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11000 // invalid since the ambiguity can affect the ABI.
11001 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
11002 unsigned &SVEorRVV) {
11003 const VectorType *VecType = SecondType->getAs<VectorType>();
11004 SVEorRVV = 0;
11005 if (FirstType->isSizelessBuiltinType() && VecType) {
11006 if (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
11007 VecType->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
11008 return true;
11009 if (VecType->getVectorKind() == VectorType::RVVFixedLengthDataVector) {
11010 SVEorRVV = 1;
11011 return true;
11012 }
11013 }
11014
11015 return false;
11016 };
11017
11018 unsigned SVEorRVV;
11019 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11020 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11021 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
11022 << SVEorRVV << LHSType << RHSType;
11023 return QualType();
11024 }
11025
11026 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11027 // invalid since the ambiguity can affect the ABI.
11028 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11029 unsigned &SVEorRVV) {
11030 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11031 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11032
11033 SVEorRVV = 0;
11034 if (FirstVecType && SecondVecType) {
11035 if (FirstVecType->getVectorKind() == VectorType::GenericVector) {
11036 if (SecondVecType->getVectorKind() ==
11037 VectorType::SveFixedLengthDataVector ||
11038 SecondVecType->getVectorKind() ==
11039 VectorType::SveFixedLengthPredicateVector)
11040 return true;
11041 if (SecondVecType->getVectorKind() ==
11042 VectorType::RVVFixedLengthDataVector) {
11043 SVEorRVV = 1;
11044 return true;
11045 }
11046 }
11047 return false;
11048 }
11049
11050 if (SecondVecType &&
11051 SecondVecType->getVectorKind() == VectorType::GenericVector) {
11052 if (FirstType->isSVESizelessBuiltinType())
11053 return true;
11054 if (FirstType->isRVVSizelessBuiltinType()) {
11055 SVEorRVV = 1;
11056 return true;
11057 }
11058 }
11059
11060 return false;
11061 };
11062
11063 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11064 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11065 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11066 << SVEorRVV << LHSType << RHSType;
11067 return QualType();
11068 }
11069
11070 // If there's a vector type and a scalar, try to convert the scalar to
11071 // the vector element type and splat.
11072 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11073 if (!RHSVecType) {
11074 if (isa<ExtVectorType>(LHSVecType)) {
11075 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
11076 LHSVecType->getElementType(), LHSType,
11077 DiagID))
11078 return LHSType;
11079 } else {
11080 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11081 return LHSType;
11082 }
11083 }
11084 if (!LHSVecType) {
11085 if (isa<ExtVectorType>(RHSVecType)) {
11086 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
11087 LHSType, RHSVecType->getElementType(),
11088 RHSType, DiagID))
11089 return RHSType;
11090 } else {
11091 if (LHS.get()->isLValue() ||
11092 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11093 return RHSType;
11094 }
11095 }
11096
11097 // FIXME: The code below also handles conversion between vectors and
11098 // non-scalars, we should break this down into fine grained specific checks
11099 // and emit proper diagnostics.
11100 QualType VecType = LHSVecType ? LHSType : RHSType;
11101 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11102 QualType OtherType = LHSVecType ? RHSType : LHSType;
11103 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11104 if (isLaxVectorConversion(OtherType, VecType)) {
11105 if (Context.getTargetInfo().getTriple().isPPC() &&
11106 anyAltivecTypes(RHSType, LHSType) &&
11107 !Context.areCompatibleVectorTypes(RHSType, LHSType))
11108 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11109 // If we're allowing lax vector conversions, only the total (data) size
11110 // needs to be the same. For non compound assignment, if one of the types is
11111 // scalar, the result is always the vector type.
11112 if (!IsCompAssign) {
11113 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
11114 return VecType;
11115 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11116 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11117 // type. Note that this is already done by non-compound assignments in
11118 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11119 // <1 x T> -> T. The result is also a vector type.
11120 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11121 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11122 ExprResult *RHSExpr = &RHS;
11123 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
11124 return VecType;
11125 }
11126 }
11127
11128 // Okay, the expression is invalid.
11129
11130 // If there's a non-vector, non-real operand, diagnose that.
11131 if ((!RHSVecType && !RHSType->isRealType()) ||
11132 (!LHSVecType && !LHSType->isRealType())) {
11133 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11134 << LHSType << RHSType
11135 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11136 return QualType();
11137 }
11138
11139 // OpenCL V1.1 6.2.6.p1:
11140 // If the operands are of more than one vector type, then an error shall
11141 // occur. Implicit conversions between vector types are not permitted, per
11142 // section 6.2.1.
11143 if (getLangOpts().OpenCL &&
11144 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11145 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11146 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11147 << RHSType;
11148 return QualType();
11149 }
11150
11151
11152 // If there is a vector type that is not a ExtVector and a scalar, we reach
11153 // this point if scalar could not be converted to the vector's element type
11154 // without truncation.
11155 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11156 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11157 QualType Scalar = LHSVecType ? RHSType : LHSType;
11158 QualType Vector = LHSVecType ? LHSType : RHSType;
11159 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11160 Diag(Loc,
11161 diag::err_typecheck_vector_not_convertable_implict_truncation)
11162 << ScalarOrVector << Scalar << Vector;
11163
11164 return QualType();
11165 }
11166
11167 // Otherwise, use the generic diagnostic.
11168 Diag(Loc, DiagID)
11169 << LHSType << RHSType
11170 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11171 return QualType();
11172}
11173
11174QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11175 SourceLocation Loc,
11176 bool IsCompAssign,
11177 ArithConvKind OperationKind) {
11178 if (!IsCompAssign) {
11179 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11180 if (LHS.isInvalid())
11181 return QualType();
11182 }
11183 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11184 if (RHS.isInvalid())
11185 return QualType();
11186
11187 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11188 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11189
11190 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11191 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11192
11193 unsigned DiagID = diag::err_typecheck_invalid_operands;
11194 if ((OperationKind == ACK_Arithmetic) &&
11195 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11196 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11197 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11198 << RHS.get()->getSourceRange();
11199 return QualType();
11200 }
11201
11202 if (Context.hasSameType(LHSType, RHSType))
11203 return LHSType;
11204
11205 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
11206 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11207 return LHSType;
11208 }
11209 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
11210 if (LHS.get()->isLValue() ||
11211 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11212 return RHSType;
11213 }
11214
11215 if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
11216 (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
11217 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11218 << LHSType << RHSType << LHS.get()->getSourceRange()
11219 << RHS.get()->getSourceRange();
11220 return QualType();
11221 }
11222
11223 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11224 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11225 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11226 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11227 << LHSType << RHSType << LHS.get()->getSourceRange()
11228 << RHS.get()->getSourceRange();
11229 return QualType();
11230 }
11231
11232 if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
11233 QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
11234 QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
11235 bool ScalarOrVector =
11236 LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
11237
11238 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11239 << ScalarOrVector << Scalar << Vector;
11240
11241 return QualType();
11242 }
11243
11244 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11245 << RHS.get()->getSourceRange();
11246 return QualType();
11247}
11248
11249// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11250// expression. These are mainly cases where the null pointer is used as an
11251// integer instead of a pointer.
11252static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11253 SourceLocation Loc, bool IsCompare) {
11254 // The canonical way to check for a GNU null is with isNullPointerConstant,
11255 // but we use a bit of a hack here for speed; this is a relatively
11256 // hot path, and isNullPointerConstant is slow.
11257 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11258 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11259
11260 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11261
11262 // Avoid analyzing cases where the result will either be invalid (and
11263 // diagnosed as such) or entirely valid and not something to warn about.
11264 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11265 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11266 return;
11267
11268 // Comparison operations would not make sense with a null pointer no matter
11269 // what the other expression is.
11270 if (!IsCompare) {
11271 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11272 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11273 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11274 return;
11275 }
11276
11277 // The rest of the operations only make sense with a null pointer
11278 // if the other expression is a pointer.
11279 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11280 NonNullType->canDecayToPointerType())
11281 return;
11282
11283 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11284 << LHSNull /* LHS is NULL */ << NonNullType
11285 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11286}
11287
11288static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11289 SourceLocation Loc) {
11290 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11291 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11292 if (!LUE || !RUE)
11293 return;
11294 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11295 RUE->getKind() != UETT_SizeOf)
11296 return;
11297
11298 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11299 QualType LHSTy = LHSArg->getType();
11300 QualType RHSTy;
11301
11302 if (RUE->isArgumentType())
11303 RHSTy = RUE->getArgumentType().getNonReferenceType();
11304 else
11305 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11306
11307 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11308 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11309 return;
11310
11311 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11312 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11313 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11314 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11315 << LHSArgDecl;
11316 }
11317 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11318 QualType ArrayElemTy = ArrayTy->getElementType();
11319 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11320 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11321 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11322 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11323 return;
11324 S.Diag(Loc, diag::warn_division_sizeof_array)
11325 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11326 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11327 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11328 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11329 << LHSArgDecl;
11330 }
11331
11332 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11333 }
11334}
11335
11336static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11337 ExprResult &RHS,
11338 SourceLocation Loc, bool IsDiv) {
11339 // Check for division/remainder by zero.
11340 Expr::EvalResult RHSValue;
11341 if (!RHS.get()->isValueDependent() &&
11342 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11343 RHSValue.Val.getInt() == 0)
11344 S.DiagRuntimeBehavior(Loc, RHS.get(),
11345 S.PDiag(diag::warn_remainder_division_by_zero)
11346 << IsDiv << RHS.get()->getSourceRange());
11347}
11348
11349QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11350 SourceLocation Loc,
11351 bool IsCompAssign, bool IsDiv) {
11352 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11353
11354 QualType LHSTy = LHS.get()->getType();
11355 QualType RHSTy = RHS.get()->getType();
11356 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11357 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11358 /*AllowBothBool*/ getLangOpts().AltiVec,
11359 /*AllowBoolConversions*/ false,
11360 /*AllowBooleanOperation*/ false,
11361 /*ReportInvalid*/ true);
11362 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
11363 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11364 ACK_Arithmetic);
11365 if (!IsDiv &&
11366 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11367 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11368 // For division, only matrix-by-scalar is supported. Other combinations with
11369 // matrix types are invalid.
11370 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11371 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11372
11373 QualType compType = UsualArithmeticConversions(
11374 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11375 if (LHS.isInvalid() || RHS.isInvalid())
11376 return QualType();
11377
11378
11379 if (compType.isNull() || !compType->isArithmeticType())
11380 return InvalidOperands(Loc, LHS, RHS);
11381 if (IsDiv) {
11382 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11383 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11384 }
11385 return compType;
11386}
11387
11388QualType Sema::CheckRemainderOperands(
11389 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11390 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11391
11392 if (LHS.get()->getType()->isVectorType() ||
11393 RHS.get()->getType()->isVectorType()) {
11394 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11395 RHS.get()->getType()->hasIntegerRepresentation())
11396 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11397 /*AllowBothBool*/ getLangOpts().AltiVec,
11398 /*AllowBoolConversions*/ false,
11399 /*AllowBooleanOperation*/ false,
11400 /*ReportInvalid*/ true);
11401 return InvalidOperands(Loc, LHS, RHS);
11402 }
11403
11404 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11405 RHS.get()->getType()->isVLSTBuiltinType()) {
11406 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11407 RHS.get()->getType()->hasIntegerRepresentation())
11408 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11409 ACK_Arithmetic);
11410
11411 return InvalidOperands(Loc, LHS, RHS);
11412 }
11413
11414 QualType compType = UsualArithmeticConversions(
11415 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11416 if (LHS.isInvalid() || RHS.isInvalid())
11417 return QualType();
11418
11419 if (compType.isNull() || !compType->isIntegerType())
11420 return InvalidOperands(Loc, LHS, RHS);
11421 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11422 return compType;
11423}
11424
11425/// Diagnose invalid arithmetic on two void pointers.
11426static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11427 Expr *LHSExpr, Expr *RHSExpr) {
11428 S.Diag(Loc, S.getLangOpts().CPlusPlus
11429 ? diag::err_typecheck_pointer_arith_void_type
11430 : diag::ext_gnu_void_ptr)
11431 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11432 << RHSExpr->getSourceRange();
11433}
11434
11435/// Diagnose invalid arithmetic on a void pointer.
11436static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11437 Expr *Pointer) {
11438 S.Diag(Loc, S.getLangOpts().CPlusPlus
11439 ? diag::err_typecheck_pointer_arith_void_type
11440 : diag::ext_gnu_void_ptr)
11441 << 0 /* one pointer */ << Pointer->getSourceRange();
11442}
11443
11444/// Diagnose invalid arithmetic on a null pointer.
11445///
11446/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11447/// idiom, which we recognize as a GNU extension.
11448///
11449static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11450 Expr *Pointer, bool IsGNUIdiom) {
11451 if (IsGNUIdiom)
11452 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11453 << Pointer->getSourceRange();
11454 else
11455 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11456 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11457}
11458
11459/// Diagnose invalid subraction on a null pointer.
11460///
11461static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11462 Expr *Pointer, bool BothNull) {
11463 // Null - null is valid in C++ [expr.add]p7
11464 if (BothNull && S.getLangOpts().CPlusPlus)
11465 return;
11466
11467 // Is this s a macro from a system header?
11468 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11469 return;
11470
11471 S.DiagRuntimeBehavior(Loc, Pointer,
11472 S.PDiag(diag::warn_pointer_sub_null_ptr)
11473 << S.getLangOpts().CPlusPlus
11474 << Pointer->getSourceRange());
11475}
11476
11477/// Diagnose invalid arithmetic on two function pointers.
11478static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11479 Expr *LHS, Expr *RHS) {
11480 assert(LHS->getType()->isAnyPointerType());
11481 assert(RHS->getType()->isAnyPointerType());
11482 S.Diag(Loc, S.getLangOpts().CPlusPlus
11483 ? diag::err_typecheck_pointer_arith_function_type
11484 : diag::ext_gnu_ptr_func_arith)
11485 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11486 // We only show the second type if it differs from the first.
11487 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11488 RHS->getType())
11489 << RHS->getType()->getPointeeType()
11490 << LHS->getSourceRange() << RHS->getSourceRange();
11491}
11492
11493/// Diagnose invalid arithmetic on a function pointer.
11494static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11495 Expr *Pointer) {
11496 assert(Pointer->getType()->isAnyPointerType());
11497 S.Diag(Loc, S.getLangOpts().CPlusPlus
11498 ? diag::err_typecheck_pointer_arith_function_type
11499 : diag::ext_gnu_ptr_func_arith)
11500 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11501 << 0 /* one pointer, so only one type */
11502 << Pointer->getSourceRange();
11503}
11504
11505/// Emit error if Operand is incomplete pointer type
11506///
11507/// \returns True if pointer has incomplete type
11508static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11509 Expr *Operand) {
11510 QualType ResType = Operand->getType();
11511 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11512 ResType = ResAtomicType->getValueType();
11513
11514 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11515 QualType PointeeTy = ResType->getPointeeType();
11516 return S.RequireCompleteSizedType(
11517 Loc, PointeeTy,
11518 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11519 Operand->getSourceRange());
11520}
11521
11522/// Check the validity of an arithmetic pointer operand.
11523///
11524/// If the operand has pointer type, this code will check for pointer types
11525/// which are invalid in arithmetic operations. These will be diagnosed
11526/// appropriately, including whether or not the use is supported as an
11527/// extension.
11528///
11529/// \returns True when the operand is valid to use (even if as an extension).
11530static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11531 Expr *Operand) {
11532 QualType ResType = Operand->getType();
11533 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11534 ResType = ResAtomicType->getValueType();
11535
11536 if (!ResType->isAnyPointerType()) return true;
11537
11538 QualType PointeeTy = ResType->getPointeeType();
11539 if (PointeeTy->isVoidType()) {
11540 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11541 return !S.getLangOpts().CPlusPlus;
11542 }
11543 if (PointeeTy->isFunctionType()) {
11544 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11545 return !S.getLangOpts().CPlusPlus;
11546 }
11547
11548 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11549
11550 return true;
11551}
11552
11553/// Check the validity of a binary arithmetic operation w.r.t. pointer
11554/// operands.
11555///
11556/// This routine will diagnose any invalid arithmetic on pointer operands much
11557/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11558/// for emitting a single diagnostic even for operations where both LHS and RHS
11559/// are (potentially problematic) pointers.
11560///
11561/// \returns True when the operand is valid to use (even if as an extension).
11562static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11563 Expr *LHSExpr, Expr *RHSExpr) {
11564 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11565 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11566 if (!isLHSPointer && !isRHSPointer) return true;
11567
11568 QualType LHSPointeeTy, RHSPointeeTy;
11569 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11570 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11571
11572 // if both are pointers check if operation is valid wrt address spaces
11573 if (isLHSPointer && isRHSPointer) {
11574 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11575 S.Diag(Loc,
11576 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11577 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11578 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11579 return false;
11580 }
11581 }
11582
11583 // Check for arithmetic on pointers to incomplete types.
11584 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11585 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11586 if (isLHSVoidPtr || isRHSVoidPtr) {
11587 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11588 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11589 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11590
11591 return !S.getLangOpts().CPlusPlus;
11592 }
11593
11594 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11595 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11596 if (isLHSFuncPtr || isRHSFuncPtr) {
11597 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11598 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11599 RHSExpr);
11600 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11601
11602 return !S.getLangOpts().CPlusPlus;
11603 }
11604
11605 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11606 return false;
11607 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11608 return false;
11609
11610 return true;
11611}
11612
11613/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11614/// literal.
11615static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11616 Expr *LHSExpr, Expr *RHSExpr) {
11617 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11618 Expr* IndexExpr = RHSExpr;
11619 if (!StrExpr) {
11620 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11621 IndexExpr = LHSExpr;
11622 }
11623
11624 bool IsStringPlusInt = StrExpr &&
11625 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11626 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11627 return;
11628
11629 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11630 Self.Diag(OpLoc, diag::warn_string_plus_int)
11631 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11632
11633 // Only print a fixit for "str" + int, not for int + "str".
11634 if (IndexExpr == RHSExpr) {
11635 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11636 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11637 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11638 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11639 << FixItHint::CreateInsertion(EndLoc, "]");
11640 } else
11641 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11642}
11643
11644/// Emit a warning when adding a char literal to a string.
11645static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11646 Expr *LHSExpr, Expr *RHSExpr) {
11647 const Expr *StringRefExpr = LHSExpr;
11648 const CharacterLiteral *CharExpr =
11649 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11650
11651 if (!CharExpr) {
11652 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11653 StringRefExpr = RHSExpr;
11654 }
11655
11656 if (!CharExpr || !StringRefExpr)
11657 return;
11658
11659 const QualType StringType = StringRefExpr->getType();
11660
11661 // Return if not a PointerType.
11662 if (!StringType->isAnyPointerType())
11663 return;
11664
11665 // Return if not a CharacterType.
11666 if (!StringType->getPointeeType()->isAnyCharacterType())
11667 return;
11668
11669 ASTContext &Ctx = Self.getASTContext();
11670 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11671
11672 const QualType CharType = CharExpr->getType();
11673 if (!CharType->isAnyCharacterType() &&
11674 CharType->isIntegerType() &&
11675 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11676 Self.Diag(OpLoc, diag::warn_string_plus_char)
11677 << DiagRange << Ctx.CharTy;
11678 } else {
11679 Self.Diag(OpLoc, diag::warn_string_plus_char)
11680 << DiagRange << CharExpr->getType();
11681 }
11682
11683 // Only print a fixit for str + char, not for char + str.
11684 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11685 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11686 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11687 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11688 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11689 << FixItHint::CreateInsertion(EndLoc, "]");
11690 } else {
11691 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11692 }
11693}
11694
11695/// Emit error when two pointers are incompatible.
11696static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11697 Expr *LHSExpr, Expr *RHSExpr) {
11698 assert(LHSExpr->getType()->isAnyPointerType());
11699 assert(RHSExpr->getType()->isAnyPointerType());
11700 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11701 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11702 << RHSExpr->getSourceRange();
11703}
11704
11705// C99 6.5.6
11706QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11707 SourceLocation Loc, BinaryOperatorKind Opc,
11708 QualType* CompLHSTy) {
11709 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11710
11711 if (LHS.get()->getType()->isVectorType() ||
11712 RHS.get()->getType()->isVectorType()) {
11713 QualType compType =
11714 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11715 /*AllowBothBool*/ getLangOpts().AltiVec,
11716 /*AllowBoolConversions*/ getLangOpts().ZVector,
11717 /*AllowBooleanOperation*/ false,
11718 /*ReportInvalid*/ true);
11719 if (CompLHSTy) *CompLHSTy = compType;
11720 return compType;
11721 }
11722
11723 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11724 RHS.get()->getType()->isVLSTBuiltinType()) {
11725 QualType compType =
11726 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11727 if (CompLHSTy)
11728 *CompLHSTy = compType;
11729 return compType;
11730 }
11731
11732 if (LHS.get()->getType()->isConstantMatrixType() ||
11733 RHS.get()->getType()->isConstantMatrixType()) {
11734 QualType compType =
11735 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11736 if (CompLHSTy)
11737 *CompLHSTy = compType;
11738 return compType;
11739 }
11740
11741 QualType compType = UsualArithmeticConversions(
11742 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11743 if (LHS.isInvalid() || RHS.isInvalid())
11744 return QualType();
11745
11746 // Diagnose "string literal" '+' int and string '+' "char literal".
11747 if (Opc == BO_Add) {
11748 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11749 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11750 }
11751
11752 // handle the common case first (both operands are arithmetic).
11753 if (!compType.isNull() && compType->isArithmeticType()) {
11754 if (CompLHSTy) *CompLHSTy = compType;
11755 return compType;
11756 }
11757
11758 // Type-checking. Ultimately the pointer's going to be in PExp;
11759 // note that we bias towards the LHS being the pointer.
11760 Expr *PExp = LHS.get(), *IExp = RHS.get();
11761
11762 bool isObjCPointer;
11763 if (PExp->getType()->isPointerType()) {
11764 isObjCPointer = false;
11765 } else if (PExp->getType()->isObjCObjectPointerType()) {
11766 isObjCPointer = true;
11767 } else {
11768 std::swap(PExp, IExp);
11769 if (PExp->getType()->isPointerType()) {
11770 isObjCPointer = false;
11771 } else if (PExp->getType()->isObjCObjectPointerType()) {
11772 isObjCPointer = true;
11773 } else {
11774 return InvalidOperands(Loc, LHS, RHS);
11775 }
11776 }
11777 assert(PExp->getType()->isAnyPointerType());
11778
11779 if (!IExp->getType()->isIntegerType())
11780 return InvalidOperands(Loc, LHS, RHS);
11781
11782 // Adding to a null pointer results in undefined behavior.
11783 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11784 Context, Expr::NPC_ValueDependentIsNotNull)) {
11785 // In C++ adding zero to a null pointer is defined.
11786 Expr::EvalResult KnownVal;
11787 if (!getLangOpts().CPlusPlus ||
11788 (!IExp->isValueDependent() &&
11789 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11790 KnownVal.Val.getInt() != 0))) {
11791 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11792 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11793 Context, BO_Add, PExp, IExp);
11794 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11795 }
11796 }
11797
11798 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11799 return QualType();
11800
11801 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11802 return QualType();
11803
11804 // Check array bounds for pointer arithemtic
11805 CheckArrayAccess(PExp, IExp);
11806
11807 if (CompLHSTy) {
11808 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11809 if (LHSTy.isNull()) {
11810 LHSTy = LHS.get()->getType();
11811 if (Context.isPromotableIntegerType(LHSTy))
11812 LHSTy = Context.getPromotedIntegerType(LHSTy);
11813 }
11814 *CompLHSTy = LHSTy;
11815 }
11816
11817 return PExp->getType();
11818}
11819
11820// C99 6.5.6
11821QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11822 SourceLocation Loc,
11823 QualType* CompLHSTy) {
11824 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11825
11826 if (LHS.get()->getType()->isVectorType() ||
11827 RHS.get()->getType()->isVectorType()) {
11828 QualType compType =
11829 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11830 /*AllowBothBool*/ getLangOpts().AltiVec,
11831 /*AllowBoolConversions*/ getLangOpts().ZVector,
11832 /*AllowBooleanOperation*/ false,
11833 /*ReportInvalid*/ true);
11834 if (CompLHSTy) *CompLHSTy = compType;
11835 return compType;
11836 }
11837
11838 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11839 RHS.get()->getType()->isVLSTBuiltinType()) {
11840 QualType compType =
11841 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11842 if (CompLHSTy)
11843 *CompLHSTy = compType;
11844 return compType;
11845 }
11846
11847 if (LHS.get()->getType()->isConstantMatrixType() ||
11848 RHS.get()->getType()->isConstantMatrixType()) {
11849 QualType compType =
11850 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11851 if (CompLHSTy)
11852 *CompLHSTy = compType;
11853 return compType;
11854 }
11855
11856 QualType compType = UsualArithmeticConversions(
11857 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11858 if (LHS.isInvalid() || RHS.isInvalid())
11859 return QualType();
11860
11861 // Enforce type constraints: C99 6.5.6p3.
11862
11863 // Handle the common case first (both operands are arithmetic).
11864 if (!compType.isNull() && compType->isArithmeticType()) {
11865 if (CompLHSTy) *CompLHSTy = compType;
11866 return compType;
11867 }
11868
11869 // Either ptr - int or ptr - ptr.
11870 if (LHS.get()->getType()->isAnyPointerType()) {
11871 QualType lpointee = LHS.get()->getType()->getPointeeType();
11872
11873 // Diagnose bad cases where we step over interface counts.
11874 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11875 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11876 return QualType();
11877
11878 // The result type of a pointer-int computation is the pointer type.
11879 if (RHS.get()->getType()->isIntegerType()) {
11880 // Subtracting from a null pointer should produce a warning.
11881 // The last argument to the diagnose call says this doesn't match the
11882 // GNU int-to-pointer idiom.
11883 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11884 Expr::NPC_ValueDependentIsNotNull)) {
11885 // In C++ adding zero to a null pointer is defined.
11886 Expr::EvalResult KnownVal;
11887 if (!getLangOpts().CPlusPlus ||
11888 (!RHS.get()->isValueDependent() &&
11889 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11890 KnownVal.Val.getInt() != 0))) {
11891 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11892 }
11893 }
11894
11895 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11896 return QualType();
11897
11898 // Check array bounds for pointer arithemtic
11899 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11900 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11901
11902 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11903 return LHS.get()->getType();
11904 }
11905
11906 // Handle pointer-pointer subtractions.
11907 if (const PointerType *RHSPTy
11908 = RHS.get()->getType()->getAs<PointerType>()) {
11909 QualType rpointee = RHSPTy->getPointeeType();
11910
11911 if (getLangOpts().CPlusPlus) {
11912 // Pointee types must be the same: C++ [expr.add]
11913 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11914 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11915 }
11916 } else {
11917 // Pointee types must be compatible C99 6.5.6p3
11918 if (!Context.typesAreCompatible(
11919 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11920 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11921 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11922 return QualType();
11923 }
11924 }
11925
11926 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11927 LHS.get(), RHS.get()))
11928 return QualType();
11929
11930 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11931 Context, Expr::NPC_ValueDependentIsNotNull);
11932 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11933 Context, Expr::NPC_ValueDependentIsNotNull);
11934
11935 // Subtracting nullptr or from nullptr is suspect
11936 if (LHSIsNullPtr)
11937 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11938 if (RHSIsNullPtr)
11939 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11940
11941 // The pointee type may have zero size. As an extension, a structure or
11942 // union may have zero size or an array may have zero length. In this
11943 // case subtraction does not make sense.
11944 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11945 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11946 if (ElementSize.isZero()) {
11947 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11948 << rpointee.getUnqualifiedType()
11949 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11950 }
11951 }
11952
11953 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11954 return Context.getPointerDiffType();
11955 }
11956 }
11957
11958 return InvalidOperands(Loc, LHS, RHS);
11959}
11960
11961static bool isScopedEnumerationType(QualType T) {
11962 if (const EnumType *ET = T->getAs<EnumType>())
11963 return ET->getDecl()->isScoped();
11964 return false;
11965}
11966
11967static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11968 SourceLocation Loc, BinaryOperatorKind Opc,
11969 QualType LHSType) {
11970 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11971 // so skip remaining warnings as we don't want to modify values within Sema.
11972 if (S.getLangOpts().OpenCL)
11973 return;
11974
11975 // Check right/shifter operand
11976 Expr::EvalResult RHSResult;
11977 if (RHS.get()->isValueDependent() ||
11978 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11979 return;
11980 llvm::APSInt Right = RHSResult.Val.getInt();
11981
11982 if (Right.isNegative()) {
11983 S.DiagRuntimeBehavior(Loc, RHS.get(),
11984 S.PDiag(diag::warn_shift_negative)
11985 << RHS.get()->getSourceRange());
11986 return;
11987 }
11988
11989 QualType LHSExprType = LHS.get()->getType();
11990 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11991 if (LHSExprType->isBitIntType())
11992 LeftSize = S.Context.getIntWidth(LHSExprType);
11993 else if (LHSExprType->isFixedPointType()) {
11994 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11995 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11996 }
11997 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11998 if (Right.uge(LeftBits)) {
11999 S.DiagRuntimeBehavior(Loc, RHS.get(),
12000 S.PDiag(diag::warn_shift_gt_typewidth)
12001 << RHS.get()->getSourceRange());
12002 return;
12003 }
12004
12005 // FIXME: We probably need to handle fixed point types specially here.
12006 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12007 return;
12008
12009 // When left shifting an ICE which is signed, we can check for overflow which
12010 // according to C++ standards prior to C++2a has undefined behavior
12011 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12012 // more than the maximum value representable in the result type, so never
12013 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12014 // expression is still probably a bug.)
12015 Expr::EvalResult LHSResult;
12016 if (LHS.get()->isValueDependent() ||
12017 LHSType->hasUnsignedIntegerRepresentation() ||
12018 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12019 return;
12020 llvm::APSInt Left = LHSResult.Val.getInt();
12021
12022 // Don't warn if signed overflow is defined, then all the rest of the
12023 // diagnostics will not be triggered because the behavior is defined.
12024 // Also don't warn in C++20 mode (and newer), as signed left shifts
12025 // always wrap and never overflow.
12026 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12027 return;
12028
12029 // If LHS does not have a non-negative value then, the
12030 // behavior is undefined before C++2a. Warn about it.
12031 if (Left.isNegative()) {
12032 S.DiagRuntimeBehavior(Loc, LHS.get(),
12033 S.PDiag(diag::warn_shift_lhs_negative)
12034 << LHS.get()->getSourceRange());
12035 return;
12036 }
12037
12038 llvm::APInt ResultBits =
12039 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12040 if (LeftBits.uge(ResultBits))
12041 return;
12042 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12043 Result = Result.shl(Right);
12044
12045 // Print the bit representation of the signed integer as an unsigned
12046 // hexadecimal number.
12047 SmallString<40> HexResult;
12048 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12049
12050 // If we are only missing a sign bit, this is less likely to result in actual
12051 // bugs -- if the result is cast back to an unsigned type, it will have the
12052 // expected value. Thus we place this behind a different warning that can be
12053 // turned off separately if needed.
12054 if (LeftBits == ResultBits - 1) {
12055 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12056 << HexResult << LHSType
12057 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12058 return;
12059 }
12060
12061 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12062 << HexResult.str() << Result.getSignificantBits() << LHSType
12063 << Left.getBitWidth() << LHS.get()->getSourceRange()
12064 << RHS.get()->getSourceRange();
12065}
12066
12067/// Return the resulting type when a vector is shifted
12068/// by a scalar or vector shift amount.
12069static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12070 SourceLocation Loc, bool IsCompAssign) {
12071 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12072 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12073 !LHS.get()->getType()->isVectorType()) {
12074 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12075 << RHS.get()->getType() << LHS.get()->getType()
12076 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12077 return QualType();
12078 }
12079
12080 if (!IsCompAssign) {
12081 LHS = S.UsualUnaryConversions(LHS.get());
12082 if (LHS.isInvalid()) return QualType();
12083 }
12084
12085 RHS = S.UsualUnaryConversions(RHS.get());
12086 if (RHS.isInvalid()) return QualType();
12087
12088 QualType LHSType = LHS.get()->getType();
12089 // Note that LHS might be a scalar because the routine calls not only in
12090 // OpenCL case.
12091 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12092 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12093
12094 // Note that RHS might not be a vector.
12095 QualType RHSType = RHS.get()->getType();
12096 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12097 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12098
12099 // Do not allow shifts for boolean vectors.
12100 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12101 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12102 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12103 << LHS.get()->getType() << RHS.get()->getType()
12104 << LHS.get()->getSourceRange();
12105 return QualType();
12106 }
12107
12108 // The operands need to be integers.
12109 if (!LHSEleType->isIntegerType()) {
12110 S.Diag(Loc, diag::err_typecheck_expect_int)
12111 << LHS.get()->getType() << LHS.get()->getSourceRange();
12112 return QualType();
12113 }
12114
12115 if (!RHSEleType->isIntegerType()) {
12116 S.Diag(Loc, diag::err_typecheck_expect_int)
12117 << RHS.get()->getType() << RHS.get()->getSourceRange();
12118 return QualType();
12119 }
12120
12121 if (!LHSVecTy) {
12122 assert(RHSVecTy);
12123 if (IsCompAssign)
12124 return RHSType;
12125 if (LHSEleType != RHSEleType) {
12126 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12127 LHSEleType = RHSEleType;
12128 }
12129 QualType VecTy =
12130 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12131 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12132 LHSType = VecTy;
12133 } else if (RHSVecTy) {
12134 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12135 // are applied component-wise. So if RHS is a vector, then ensure
12136 // that the number of elements is the same as LHS...
12137 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12138 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12139 << LHS.get()->getType() << RHS.get()->getType()
12140 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12141 return QualType();
12142 }
12143 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12144 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12145 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12146 if (LHSBT != RHSBT &&
12147 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12148 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12149 << LHS.get()->getType() << RHS.get()->getType()
12150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12151 }
12152 }
12153 } else {
12154 // ...else expand RHS to match the number of elements in LHS.
12155 QualType VecTy =
12156 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12157 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12158 }
12159
12160 return LHSType;
12161}
12162
12163static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12164 ExprResult &RHS, SourceLocation Loc,
12165 bool IsCompAssign) {
12166 if (!IsCompAssign) {
12167 LHS = S.UsualUnaryConversions(LHS.get());
12168 if (LHS.isInvalid())
12169 return QualType();
12170 }
12171
12172 RHS = S.UsualUnaryConversions(RHS.get());
12173 if (RHS.isInvalid())
12174 return QualType();
12175
12176 QualType LHSType = LHS.get()->getType();
12177 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12178 QualType LHSEleType = LHSType->isVLSTBuiltinType()
12179 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12180 : LHSType;
12181
12182 // Note that RHS might not be a vector
12183 QualType RHSType = RHS.get()->getType();
12184 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12185 QualType RHSEleType = RHSType->isVLSTBuiltinType()
12186 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12187 : RHSType;
12188
12189 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12190 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12191 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12192 << LHSType << RHSType << LHS.get()->getSourceRange();
12193 return QualType();
12194 }
12195
12196 if (!LHSEleType->isIntegerType()) {
12197 S.Diag(Loc, diag::err_typecheck_expect_int)
12198 << LHS.get()->getType() << LHS.get()->getSourceRange();
12199 return QualType();
12200 }
12201
12202 if (!RHSEleType->isIntegerType()) {
12203 S.Diag(Loc, diag::err_typecheck_expect_int)
12204 << RHS.get()->getType() << RHS.get()->getSourceRange();
12205 return QualType();
12206 }
12207
12208 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
12209 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12210 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12211 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12212 << LHSType << RHSType << LHS.get()->getSourceRange()
12213 << RHS.get()->getSourceRange();
12214 return QualType();
12215 }
12216
12217 if (!LHSType->isVLSTBuiltinType()) {
12218 assert(RHSType->isVLSTBuiltinType());
12219 if (IsCompAssign)
12220 return RHSType;
12221 if (LHSEleType != RHSEleType) {
12222 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12223 LHSEleType = RHSEleType;
12224 }
12225 const llvm::ElementCount VecSize =
12226 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12227 QualType VecTy =
12228 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12229 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12230 LHSType = VecTy;
12231 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
12232 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12233 S.Context.getTypeSize(LHSBuiltinTy)) {
12234 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12235 << LHSType << RHSType << LHS.get()->getSourceRange()
12236 << RHS.get()->getSourceRange();
12237 return QualType();
12238 }
12239 } else {
12240 const llvm::ElementCount VecSize =
12241 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12242 if (LHSEleType != RHSEleType) {
12243 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12244 RHSEleType = LHSEleType;
12245 }
12246 QualType VecTy =
12247 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12248 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12249 }
12250
12251 return LHSType;
12252}
12253
12254// C99 6.5.7
12255QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12256 SourceLocation Loc, BinaryOperatorKind Opc,
12257 bool IsCompAssign) {
12258 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12259
12260 // Vector shifts promote their scalar inputs to vector type.
12261 if (LHS.get()->getType()->isVectorType() ||
12262 RHS.get()->getType()->isVectorType()) {
12263 if (LangOpts.ZVector) {
12264 // The shift operators for the z vector extensions work basically
12265 // like general shifts, except that neither the LHS nor the RHS is
12266 // allowed to be a "vector bool".
12267 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12268 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
12269 return InvalidOperands(Loc, LHS, RHS);
12270 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12271 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
12272 return InvalidOperands(Loc, LHS, RHS);
12273 }
12274 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12275 }
12276
12277 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12278 RHS.get()->getType()->isVLSTBuiltinType())
12279 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12280
12281 // Shifts don't perform usual arithmetic conversions, they just do integer
12282 // promotions on each operand. C99 6.5.7p3
12283
12284 // For the LHS, do usual unary conversions, but then reset them away
12285 // if this is a compound assignment.
12286 ExprResult OldLHS = LHS;
12287 LHS = UsualUnaryConversions(LHS.get());
12288 if (LHS.isInvalid())
12289 return QualType();
12290 QualType LHSType = LHS.get()->getType();
12291 if (IsCompAssign) LHS = OldLHS;
12292
12293 // The RHS is simpler.
12294 RHS = UsualUnaryConversions(RHS.get());
12295 if (RHS.isInvalid())
12296 return QualType();
12297 QualType RHSType = RHS.get()->getType();
12298
12299 // C99 6.5.7p2: Each of the operands shall have integer type.
12300 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12301 if ((!LHSType->isFixedPointOrIntegerType() &&
12302 !LHSType->hasIntegerRepresentation()) ||
12303 !RHSType->hasIntegerRepresentation())
12304 return InvalidOperands(Loc, LHS, RHS);
12305
12306 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12307 // hasIntegerRepresentation() above instead of this.
12308 if (isScopedEnumerationType(LHSType) ||
12309 isScopedEnumerationType(RHSType)) {
12310 return InvalidOperands(Loc, LHS, RHS);
12311 }
12312 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12313
12314 // "The type of the result is that of the promoted left operand."
12315 return LHSType;
12316}
12317
12318/// Diagnose bad pointer comparisons.
12319static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12320 ExprResult &LHS, ExprResult &RHS,
12321 bool IsError) {
12322 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12323 : diag::ext_typecheck_comparison_of_distinct_pointers)
12324 << LHS.get()->getType() << RHS.get()->getType()
12325 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12326}
12327
12328/// Returns false if the pointers are converted to a composite type,
12329/// true otherwise.
12330static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12331 ExprResult &LHS, ExprResult &RHS) {
12332 // C++ [expr.rel]p2:
12333 // [...] Pointer conversions (4.10) and qualification
12334 // conversions (4.4) are performed on pointer operands (or on
12335 // a pointer operand and a null pointer constant) to bring
12336 // them to their composite pointer type. [...]
12337 //
12338 // C++ [expr.eq]p1 uses the same notion for (in)equality
12339 // comparisons of pointers.
12340
12341 QualType LHSType = LHS.get()->getType();
12342 QualType RHSType = RHS.get()->getType();
12343 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12344 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12345
12346 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12347 if (T.isNull()) {
12348 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12349 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12350 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12351 else
12352 S.InvalidOperands(Loc, LHS, RHS);
12353 return true;
12354 }
12355
12356 return false;
12357}
12358
12359static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12360 ExprResult &LHS,
12361 ExprResult &RHS,
12362 bool IsError) {
12363 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12364 : diag::ext_typecheck_comparison_of_fptr_to_void)
12365 << LHS.get()->getType() << RHS.get()->getType()
12366 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12367}
12368
12369static bool isObjCObjectLiteral(ExprResult &E) {
12370 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12371 case Stmt::ObjCArrayLiteralClass:
12372 case Stmt::ObjCDictionaryLiteralClass:
12373 case Stmt::ObjCStringLiteralClass:
12374 case Stmt::ObjCBoxedExprClass:
12375 return true;
12376 default:
12377 // Note that ObjCBoolLiteral is NOT an object literal!
12378 return false;
12379 }
12380}
12381
12382static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12383 const ObjCObjectPointerType *Type =
12384 LHS->getType()->getAs<ObjCObjectPointerType>();
12385
12386 // If this is not actually an Objective-C object, bail out.
12387 if (!Type)
12388 return false;
12389
12390 // Get the LHS object's interface type.
12391 QualType InterfaceType = Type->getPointeeType();
12392
12393 // If the RHS isn't an Objective-C object, bail out.
12394 if (!RHS->getType()->isObjCObjectPointerType())
12395 return false;
12396
12397 // Try to find the -isEqual: method.
12398 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12399 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12400 InterfaceType,
12401 /*IsInstance=*/true);
12402 if (!Method) {
12403 if (Type->isObjCIdType()) {
12404 // For 'id', just check the global pool.
12405 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12406 /*receiverId=*/true);
12407 } else {
12408 // Check protocols.
12409 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12410 /*IsInstance=*/true);
12411 }
12412 }
12413
12414 if (!Method)
12415 return false;
12416
12417 QualType T = Method->parameters()[0]->getType();
12418 if (!T->isObjCObjectPointerType())
12419 return false;
12420
12421 QualType R = Method->getReturnType();
12422 if (!R->isScalarType())
12423 return false;
12424
12425 return true;
12426}
12427
12428Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12429 FromE = FromE->IgnoreParenImpCasts();
12430 switch (FromE->getStmtClass()) {
12431 default:
12432 break;
12433 case Stmt::ObjCStringLiteralClass:
12434 // "string literal"
12435 return LK_String;
12436 case Stmt::ObjCArrayLiteralClass:
12437 // "array literal"
12438 return LK_Array;
12439 case Stmt::ObjCDictionaryLiteralClass:
12440 // "dictionary literal"
12441 return LK_Dictionary;
12442 case Stmt::BlockExprClass:
12443 return LK_Block;
12444 case Stmt::ObjCBoxedExprClass: {
12445 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12446 switch (Inner->getStmtClass()) {
12447 case Stmt::IntegerLiteralClass:
12448 case Stmt::FloatingLiteralClass:
12449 case Stmt::CharacterLiteralClass:
12450 case Stmt::ObjCBoolLiteralExprClass:
12451 case Stmt::CXXBoolLiteralExprClass:
12452 // "numeric literal"
12453 return LK_Numeric;
12454 case Stmt::ImplicitCastExprClass: {
12455 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12456 // Boolean literals can be represented by implicit casts.
12457 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12458 return LK_Numeric;
12459 break;
12460 }
12461 default:
12462 break;
12463 }
12464 return LK_Boxed;
12465 }
12466 }
12467 return LK_None;
12468}
12469
12470static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12471 ExprResult &LHS, ExprResult &RHS,
12472 BinaryOperator::Opcode Opc){
12473 Expr *Literal;
12474 Expr *Other;
12475 if (isObjCObjectLiteral(LHS)) {
12476 Literal = LHS.get();
12477 Other = RHS.get();
12478 } else {
12479 Literal = RHS.get();
12480 Other = LHS.get();
12481 }
12482
12483 // Don't warn on comparisons against nil.
12484 Other = Other->IgnoreParenCasts();
12485 if (Other->isNullPointerConstant(S.getASTContext(),
12486 Expr::NPC_ValueDependentIsNotNull))
12487 return;
12488
12489 // This should be kept in sync with warn_objc_literal_comparison.
12490 // LK_String should always be after the other literals, since it has its own
12491 // warning flag.
12492 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12493 assert(LiteralKind != Sema::LK_Block);
12494 if (LiteralKind == Sema::LK_None) {
12495 llvm_unreachable("Unknown Objective-C object literal kind");
12496 }
12497
12498 if (LiteralKind == Sema::LK_String)
12499 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12500 << Literal->getSourceRange();
12501 else
12502 S.Diag(Loc, diag::warn_objc_literal_comparison)
12503 << LiteralKind << Literal->getSourceRange();
12504
12505 if (BinaryOperator::isEqualityOp(Opc) &&
12506 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12507 SourceLocation Start = LHS.get()->getBeginLoc();
12508 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12509 CharSourceRange OpRange =
12510 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12511
12512 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12513 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12514 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12515 << FixItHint::CreateInsertion(End, "]");
12516 }
12517}
12518
12519/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12520static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12521 ExprResult &RHS, SourceLocation Loc,
12522 BinaryOperatorKind Opc) {
12523 // Check that left hand side is !something.
12524 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12525 if (!UO || UO->getOpcode() != UO_LNot) return;
12526
12527 // Only check if the right hand side is non-bool arithmetic type.
12528 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12529
12530 // Make sure that the something in !something is not bool.
12531 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12532 if (SubExpr->isKnownToHaveBooleanValue()) return;
12533
12534 // Emit warning.
12535 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12536 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12537 << Loc << IsBitwiseOp;
12538
12539 // First note suggest !(x < y)
12540 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12541 SourceLocation FirstClose = RHS.get()->getEndLoc();
12542 FirstClose = S.getLocForEndOfToken(FirstClose);
12543 if (FirstClose.isInvalid())
12544 FirstOpen = SourceLocation();
12545 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12546 << IsBitwiseOp
12547 << FixItHint::CreateInsertion(FirstOpen, "(")
12548 << FixItHint::CreateInsertion(FirstClose, ")");
12549
12550 // Second note suggests (!x) < y
12551 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12552 SourceLocation SecondClose = LHS.get()->getEndLoc();
12553 SecondClose = S.getLocForEndOfToken(SecondClose);
12554 if (SecondClose.isInvalid())
12555 SecondOpen = SourceLocation();
12556 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12557 << FixItHint::CreateInsertion(SecondOpen, "(")
12558 << FixItHint::CreateInsertion(SecondClose, ")");
12559}
12560
12561// Returns true if E refers to a non-weak array.
12562static bool checkForArray(const Expr *E) {
12563 const ValueDecl *D = nullptr;
12564 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12565 D = DR->getDecl();
12566 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12567 if (Mem->isImplicitAccess())
12568 D = Mem->getMemberDecl();
12569 }
12570 if (!D)
12571 return false;
12572 return D->getType()->isArrayType() && !D->isWeak();
12573}
12574
12575/// Diagnose some forms of syntactically-obvious tautological comparison.
12576static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12577 Expr *LHS, Expr *RHS,
12578 BinaryOperatorKind Opc) {
12579 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12580 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12581
12582 QualType LHSType = LHS->getType();
12583 QualType RHSType = RHS->getType();
12584 if (LHSType->hasFloatingRepresentation() ||
12585 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12586 S.inTemplateInstantiation())
12587 return;
12588
12589 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12590 // Tautological diagnostics.
12591 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12592 return;
12593
12594 // Comparisons between two array types are ill-formed for operator<=>, so
12595 // we shouldn't emit any additional warnings about it.
12596 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12597 return;
12598
12599 // For non-floating point types, check for self-comparisons of the form
12600 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12601 // often indicate logic errors in the program.
12602 //
12603 // NOTE: Don't warn about comparison expressions resulting from macro
12604 // expansion. Also don't warn about comparisons which are only self
12605 // comparisons within a template instantiation. The warnings should catch
12606 // obvious cases in the definition of the template anyways. The idea is to
12607 // warn when the typed comparison operator will always evaluate to the same
12608 // result.
12609
12610 // Used for indexing into %select in warn_comparison_always
12611 enum {
12612 AlwaysConstant,
12613 AlwaysTrue,
12614 AlwaysFalse,
12615 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12616 };
12617
12618 // C++2a [depr.array.comp]:
12619 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12620 // operands of array type are deprecated.
12621 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12622 RHSStripped->getType()->isArrayType()) {
12623 S.Diag(Loc, diag::warn_depr_array_comparison)
12624 << LHS->getSourceRange() << RHS->getSourceRange()
12625 << LHSStripped->getType() << RHSStripped->getType();
12626 // Carry on to produce the tautological comparison warning, if this
12627 // expression is potentially-evaluated, we can resolve the array to a
12628 // non-weak declaration, and so on.
12629 }
12630
12631 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12632 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12633 unsigned Result;
12634 switch (Opc) {
12635 case BO_EQ:
12636 case BO_LE:
12637 case BO_GE:
12638 Result = AlwaysTrue;
12639 break;
12640 case BO_NE:
12641 case BO_LT:
12642 case BO_GT:
12643 Result = AlwaysFalse;
12644 break;
12645 case BO_Cmp:
12646 Result = AlwaysEqual;
12647 break;
12648 default:
12649 Result = AlwaysConstant;
12650 break;
12651 }
12652 S.DiagRuntimeBehavior(Loc, nullptr,
12653 S.PDiag(diag::warn_comparison_always)
12654 << 0 /*self-comparison*/
12655 << Result);
12656 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12657 // What is it always going to evaluate to?
12658 unsigned Result;
12659 switch (Opc) {
12660 case BO_EQ: // e.g. array1 == array2
12661 Result = AlwaysFalse;
12662 break;
12663 case BO_NE: // e.g. array1 != array2
12664 Result = AlwaysTrue;
12665 break;
12666 default: // e.g. array1 <= array2
12667 // The best we can say is 'a constant'
12668 Result = AlwaysConstant;
12669 break;
12670 }
12671 S.DiagRuntimeBehavior(Loc, nullptr,
12672 S.PDiag(diag::warn_comparison_always)
12673 << 1 /*array comparison*/
12674 << Result);
12675 }
12676 }
12677
12678 if (isa<CastExpr>(LHSStripped))
12679 LHSStripped = LHSStripped->IgnoreParenCasts();
12680 if (isa<CastExpr>(RHSStripped))
12681 RHSStripped = RHSStripped->IgnoreParenCasts();
12682
12683 // Warn about comparisons against a string constant (unless the other
12684 // operand is null); the user probably wants string comparison function.
12685 Expr *LiteralString = nullptr;
12686 Expr *LiteralStringStripped = nullptr;
12687 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12688 !RHSStripped->isNullPointerConstant(S.Context,
12689 Expr::NPC_ValueDependentIsNull)) {
12690 LiteralString = LHS;
12691 LiteralStringStripped = LHSStripped;
12692 } else if ((isa<StringLiteral>(RHSStripped) ||
12693 isa<ObjCEncodeExpr>(RHSStripped)) &&
12694 !LHSStripped->isNullPointerConstant(S.Context,
12695 Expr::NPC_ValueDependentIsNull)) {
12696 LiteralString = RHS;
12697 LiteralStringStripped = RHSStripped;
12698 }
12699
12700 if (LiteralString) {
12701 S.DiagRuntimeBehavior(Loc, nullptr,
12702 S.PDiag(diag::warn_stringcompare)
12703 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12704 << LiteralString->getSourceRange());
12705 }
12706}
12707
12708static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12709 switch (CK) {
12710 default: {
12711#ifndef NDEBUG
12712 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12713 << "\n";
12714#endif
12715 llvm_unreachable("unhandled cast kind");
12716 }
12717 case CK_UserDefinedConversion:
12718 return ICK_Identity;
12719 case CK_LValueToRValue:
12720 return ICK_Lvalue_To_Rvalue;
12721 case CK_ArrayToPointerDecay:
12722 return ICK_Array_To_Pointer;
12723 case CK_FunctionToPointerDecay:
12724 return ICK_Function_To_Pointer;
12725 case CK_IntegralCast:
12726 return ICK_Integral_Conversion;
12727 case CK_FloatingCast:
12728 return ICK_Floating_Conversion;
12729 case CK_IntegralToFloating:
12730 case CK_FloatingToIntegral:
12731 return ICK_Floating_Integral;
12732 case CK_IntegralComplexCast:
12733 case CK_FloatingComplexCast:
12734 case CK_FloatingComplexToIntegralComplex:
12735 case CK_IntegralComplexToFloatingComplex:
12736 return ICK_Complex_Conversion;
12737 case CK_FloatingComplexToReal:
12738 case CK_FloatingRealToComplex:
12739 case CK_IntegralComplexToReal:
12740 case CK_IntegralRealToComplex:
12741 return ICK_Complex_Real;
12742 }
12743}
12744
12745static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12746 QualType FromType,
12747 SourceLocation Loc) {
12748 // Check for a narrowing implicit conversion.
12749 StandardConversionSequence SCS;
12750 SCS.setAsIdentityConversion();
12751 SCS.setToType(0, FromType);
12752 SCS.setToType(1, ToType);
12753 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12754 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12755
12756 APValue PreNarrowingValue;
12757 QualType PreNarrowingType;
12758 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12759 PreNarrowingType,
12760 /*IgnoreFloatToIntegralConversion*/ true)) {
12761 case NK_Dependent_Narrowing:
12762 // Implicit conversion to a narrower type, but the expression is
12763 // value-dependent so we can't tell whether it's actually narrowing.
12764 case NK_Not_Narrowing:
12765 return false;
12766
12767 case NK_Constant_Narrowing:
12768 // Implicit conversion to a narrower type, and the value is not a constant
12769 // expression.
12770 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12771 << /*Constant*/ 1
12772 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12773 return true;
12774
12775 case NK_Variable_Narrowing:
12776 // Implicit conversion to a narrower type, and the value is not a constant
12777 // expression.
12778 case NK_Type_Narrowing:
12779 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12780 << /*Constant*/ 0 << FromType << ToType;
12781 // TODO: It's not a constant expression, but what if the user intended it
12782 // to be? Can we produce notes to help them figure out why it isn't?
12783 return true;
12784 }
12785 llvm_unreachable("unhandled case in switch");
12786}
12787
12788static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12789 ExprResult &LHS,
12790 ExprResult &RHS,
12791 SourceLocation Loc) {
12792 QualType LHSType = LHS.get()->getType();
12793 QualType RHSType = RHS.get()->getType();
12794 // Dig out the original argument type and expression before implicit casts
12795 // were applied. These are the types/expressions we need to check the
12796 // [expr.spaceship] requirements against.
12797 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12798 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12799 QualType LHSStrippedType = LHSStripped.get()->getType();
12800 QualType RHSStrippedType = RHSStripped.get()->getType();
12801
12802 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12803 // other is not, the program is ill-formed.
12804 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12805 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12806 return QualType();
12807 }
12808
12809 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12810 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12811 RHSStrippedType->isEnumeralType();
12812 if (NumEnumArgs == 1) {
12813 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12814 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12815 if (OtherTy->hasFloatingRepresentation()) {
12816 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12817 return QualType();
12818 }
12819 }
12820 if (NumEnumArgs == 2) {
12821 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12822 // type E, the operator yields the result of converting the operands
12823 // to the underlying type of E and applying <=> to the converted operands.
12824 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12825 S.InvalidOperands(Loc, LHS, RHS);
12826 return QualType();
12827 }
12828 QualType IntType =
12829 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12830 assert(IntType->isArithmeticType());
12831
12832 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12833 // promote the boolean type, and all other promotable integer types, to
12834 // avoid this.
12835 if (S.Context.isPromotableIntegerType(IntType))
12836 IntType = S.Context.getPromotedIntegerType(IntType);
12837
12838 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12839 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12840 LHSType = RHSType = IntType;
12841 }
12842
12843 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12844 // usual arithmetic conversions are applied to the operands.
12845 QualType Type =
12846 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12847 if (LHS.isInvalid() || RHS.isInvalid())
12848 return QualType();
12849 if (Type.isNull())
12850 return S.InvalidOperands(Loc, LHS, RHS);
12851
12852 std::optional<ComparisonCategoryType> CCT =
12853 getComparisonCategoryForBuiltinCmp(Type);
12854 if (!CCT)
12855 return S.InvalidOperands(Loc, LHS, RHS);
12856
12857 bool HasNarrowing = checkThreeWayNarrowingConversion(
12858 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12859 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12860 RHS.get()->getBeginLoc());
12861 if (HasNarrowing)
12862 return QualType();
12863
12864 assert(!Type.isNull() && "composite type for <=> has not been set");
12865
12866 return S.CheckComparisonCategoryType(
12867 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12868}
12869
12870static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12871 ExprResult &RHS,
12872 SourceLocation Loc,
12873 BinaryOperatorKind Opc) {
12874 if (Opc == BO_Cmp)
12875 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12876
12877 // C99 6.5.8p3 / C99 6.5.9p4
12878 QualType Type =
12879 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12880 if (LHS.isInvalid() || RHS.isInvalid())
12881 return QualType();
12882 if (Type.isNull())
12883 return S.InvalidOperands(Loc, LHS, RHS);
12884 assert(Type->isArithmeticType() || Type->isEnumeralType());
12885
12886 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12887 return S.InvalidOperands(Loc, LHS, RHS);
12888
12889 // Check for comparisons of floating point operands using != and ==.
12890 if (Type->hasFloatingRepresentation())
12891 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12892
12893 // The result of comparisons is 'bool' in C++, 'int' in C.
12894 return S.Context.getLogicalOperationType();
12895}
12896
12897void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12898 if (!NullE.get()->getType()->isAnyPointerType())
12899 return;
12900 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12901 if (!E.get()->getType()->isAnyPointerType() &&
12902 E.get()->isNullPointerConstant(Context,
12903 Expr::NPC_ValueDependentIsNotNull) ==
12904 Expr::NPCK_ZeroExpression) {
12905 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12906 if (CL->getValue() == 0)
12907 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12908 << NullValue
12909 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12910 NullValue ? "NULL" : "(void *)0");
12911 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12912 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12913 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12914 if (T == Context.CharTy)
12915 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12916 << NullValue
12917 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12918 NullValue ? "NULL" : "(void *)0");
12919 }
12920 }
12921}
12922
12923// C99 6.5.8, C++ [expr.rel]
12924QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12925 SourceLocation Loc,
12926 BinaryOperatorKind Opc) {
12927 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12928 bool IsThreeWay = Opc == BO_Cmp;
12929 bool IsOrdered = IsRelational || IsThreeWay;
12930 auto IsAnyPointerType = [](ExprResult E) {
12931 QualType Ty = E.get()->getType();
12932 return Ty->isPointerType() || Ty->isMemberPointerType();
12933 };
12934
12935 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12936 // type, array-to-pointer, ..., conversions are performed on both operands to
12937 // bring them to their composite type.
12938 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12939 // any type-related checks.
12940 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12941 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12942 if (LHS.isInvalid())
12943 return QualType();
12944 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12945 if (RHS.isInvalid())
12946 return QualType();
12947 } else {
12948 LHS = DefaultLvalueConversion(LHS.get());
12949 if (LHS.isInvalid())
12950 return QualType();
12951 RHS = DefaultLvalueConversion(RHS.get());
12952 if (RHS.isInvalid())
12953 return QualType();
12954 }
12955
12956 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12957 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12958 CheckPtrComparisonWithNullChar(LHS, RHS);
12959 CheckPtrComparisonWithNullChar(RHS, LHS);
12960 }
12961
12962 // Handle vector comparisons separately.
12963 if (LHS.get()->getType()->isVectorType() ||
12964 RHS.get()->getType()->isVectorType())
12965 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12966
12967 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12968 RHS.get()->getType()->isVLSTBuiltinType())
12969 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12970
12971 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12972 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12973
12974 QualType LHSType = LHS.get()->getType();
12975 QualType RHSType = RHS.get()->getType();
12976 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12977 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12978 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12979
12980 if ((LHSType->isPointerType() &&
12981 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12982 (RHSType->isPointerType() &&
12983 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12984 return InvalidOperands(Loc, LHS, RHS);
12985
12986 const Expr::NullPointerConstantKind LHSNullKind =
12987 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12988 const Expr::NullPointerConstantKind RHSNullKind =
12989 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12990 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12991 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12992
12993 auto computeResultTy = [&]() {
12994 if (Opc != BO_Cmp)
12995 return Context.getLogicalOperationType();
12996 assert(getLangOpts().CPlusPlus);
12997 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12998
12999 QualType CompositeTy = LHS.get()->getType();
13000 assert(!CompositeTy->isReferenceType());
13001
13002 std::optional<ComparisonCategoryType> CCT =
13003 getComparisonCategoryForBuiltinCmp(CompositeTy);
13004 if (!CCT)
13005 return InvalidOperands(Loc, LHS, RHS);
13006
13007 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13008 // P0946R0: Comparisons between a null pointer constant and an object
13009 // pointer result in std::strong_equality, which is ill-formed under
13010 // P1959R0.
13011 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13012 << (LHSIsNull ? LHS.get()->getSourceRange()
13013 : RHS.get()->getSourceRange());
13014 return QualType();
13015 }
13016
13017 return CheckComparisonCategoryType(
13018 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
13019 };
13020
13021 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13022 bool IsEquality = Opc == BO_EQ;
13023 if (RHSIsNull)
13024 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13025 RHS.get()->getSourceRange());
13026 else
13027 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13028 LHS.get()->getSourceRange());
13029 }
13030
13031 if (IsOrdered && LHSType->isFunctionPointerType() &&
13032 RHSType->isFunctionPointerType()) {
13033 // Valid unless a relational comparison of function pointers
13034 bool IsError = Opc == BO_Cmp;
13035 auto DiagID =
13036 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13037 : getLangOpts().CPlusPlus
13038 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13039 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13040 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13041 << RHS.get()->getSourceRange();
13042 if (IsError)
13043 return QualType();
13044 }
13045
13046 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13047 (RHSType->isIntegerType() && !RHSIsNull)) {
13048 // Skip normal pointer conversion checks in this case; we have better
13049 // diagnostics for this below.
13050 } else if (getLangOpts().CPlusPlus) {
13051 // Equality comparison of a function pointer to a void pointer is invalid,
13052 // but we allow it as an extension.
13053 // FIXME: If we really want to allow this, should it be part of composite
13054 // pointer type computation so it works in conditionals too?
13055 if (!IsOrdered &&
13056 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13057 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13058 // This is a gcc extension compatibility comparison.
13059 // In a SFINAE context, we treat this as a hard error to maintain
13060 // conformance with the C++ standard.
13061 diagnoseFunctionPointerToVoidComparison(
13062 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
13063
13064 if (isSFINAEContext())
13065 return QualType();
13066
13067 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13068 return computeResultTy();
13069 }
13070
13071 // C++ [expr.eq]p2:
13072 // If at least one operand is a pointer [...] bring them to their
13073 // composite pointer type.
13074 // C++ [expr.spaceship]p6
13075 // If at least one of the operands is of pointer type, [...] bring them
13076 // to their composite pointer type.
13077 // C++ [expr.rel]p2:
13078 // If both operands are pointers, [...] bring them to their composite
13079 // pointer type.
13080 // For <=>, the only valid non-pointer types are arrays and functions, and
13081 // we already decayed those, so this is really the same as the relational
13082 // comparison rule.
13083 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13084 (IsOrdered ? 2 : 1) &&
13085 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13086 RHSType->isObjCObjectPointerType()))) {
13087 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13088 return QualType();
13089 return computeResultTy();
13090 }
13091 } else if (LHSType->isPointerType() &&
13092 RHSType->isPointerType()) { // C99 6.5.8p2
13093 // All of the following pointer-related warnings are GCC extensions, except
13094 // when handling null pointer constants.
13095 QualType LCanPointeeTy =
13096 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13097 QualType RCanPointeeTy =
13098 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13099
13100 // C99 6.5.9p2 and C99 6.5.8p2
13101 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13102 RCanPointeeTy.getUnqualifiedType())) {
13103 if (IsRelational) {
13104 // Pointers both need to point to complete or incomplete types
13105 if ((LCanPointeeTy->isIncompleteType() !=
13106 RCanPointeeTy->isIncompleteType()) &&
13107 !getLangOpts().C11) {
13108 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13109 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13110 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13111 << RCanPointeeTy->isIncompleteType();
13112 }
13113 }
13114 } else if (!IsRelational &&
13115 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13116 // Valid unless comparison between non-null pointer and function pointer
13117 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13118 && !LHSIsNull && !RHSIsNull)
13119 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13120 /*isError*/false);
13121 } else {
13122 // Invalid
13123 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13124 }
13125 if (LCanPointeeTy != RCanPointeeTy) {
13126 // Treat NULL constant as a special case in OpenCL.
13127 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13128 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
13129 Diag(Loc,
13130 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13131 << LHSType << RHSType << 0 /* comparison */
13132 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13133 }
13134 }
13135 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13136 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13137 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13138 : CK_BitCast;
13139 if (LHSIsNull && !RHSIsNull)
13140 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13141 else
13142 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13143 }
13144 return computeResultTy();
13145 }
13146
13147
13148 // C++ [expr.eq]p4:
13149 // Two operands of type std::nullptr_t or one operand of type
13150 // std::nullptr_t and the other a null pointer constant compare
13151 // equal.
13152 // C2x 6.5.9p5:
13153 // If both operands have type nullptr_t or one operand has type nullptr_t
13154 // and the other is a null pointer constant, they compare equal.
13155 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13156 if (LHSType->isNullPtrType()) {
13157 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13158 return computeResultTy();
13159 }
13160 if (RHSType->isNullPtrType()) {
13161 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13162 return computeResultTy();
13163 }
13164 }
13165
13166 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13167 // C2x 6.5.9p6:
13168 // Otherwise, at least one operand is a pointer. If one is a pointer and
13169 // the other is a null pointer constant, the null pointer constant is
13170 // converted to the type of the pointer.
13171 if (LHSIsNull && RHSType->isPointerType()) {
13172 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13173 return computeResultTy();
13174 }
13175 if (RHSIsNull && LHSType->isPointerType()) {
13176 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13177 return computeResultTy();
13178 }
13179 }
13180
13181 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13182 // These aren't covered by the composite pointer type rules.
13183 if (!IsOrdered && RHSType->isNullPtrType() &&
13184 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13185 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13186 return computeResultTy();
13187 }
13188 if (!IsOrdered && LHSType->isNullPtrType() &&
13189 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13190 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13191 return computeResultTy();
13192 }
13193
13194 if (getLangOpts().CPlusPlus) {
13195 if (IsRelational &&
13196 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13197 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13198 // HACK: Relational comparison of nullptr_t against a pointer type is
13199 // invalid per DR583, but we allow it within std::less<> and friends,
13200 // since otherwise common uses of it break.
13201 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13202 // friends to have std::nullptr_t overload candidates.
13203 DeclContext *DC = CurContext;
13204 if (isa<FunctionDecl>(DC))
13205 DC = DC->getParent();
13206 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13207 if (CTSD->isInStdNamespace() &&
13208 llvm::StringSwitch<bool>(CTSD->getName())
13209 .Cases("less", "less_equal", "greater", "greater_equal", true)
13210 .Default(false)) {
13211 if (RHSType->isNullPtrType())
13212 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13213 else
13214 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13215 return computeResultTy();
13216 }
13217 }
13218 }
13219
13220 // C++ [expr.eq]p2:
13221 // If at least one operand is a pointer to member, [...] bring them to
13222 // their composite pointer type.
13223 if (!IsOrdered &&
13224 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13225 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13226 return QualType();
13227 else
13228 return computeResultTy();
13229 }
13230 }
13231
13232 // Handle block pointer types.
13233 if (!IsOrdered && LHSType->isBlockPointerType() &&
13234 RHSType->isBlockPointerType()) {
13235 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13236 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13237
13238 if (!LHSIsNull && !RHSIsNull &&
13239 !Context.typesAreCompatible(lpointee, rpointee)) {
13240 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13241 << LHSType << RHSType << LHS.get()->getSourceRange()
13242 << RHS.get()->getSourceRange();
13243 }
13244 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13245 return computeResultTy();
13246 }
13247
13248 // Allow block pointers to be compared with null pointer constants.
13249 if (!IsOrdered
13250 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13251 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13252 if (!LHSIsNull && !RHSIsNull) {
13253 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13254 ->getPointeeType()->isVoidType())
13255 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13256 ->getPointeeType()->isVoidType())))
13257 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13258 << LHSType << RHSType << LHS.get()->getSourceRange()
13259 << RHS.get()->getSourceRange();
13260 }
13261 if (LHSIsNull && !RHSIsNull)
13262 LHS = ImpCastExprToType(LHS.get(), RHSType,
13263 RHSType->isPointerType() ? CK_BitCast
13264 : CK_AnyPointerToBlockPointerCast);
13265 else
13266 RHS = ImpCastExprToType(RHS.get(), LHSType,
13267 LHSType->isPointerType() ? CK_BitCast
13268 : CK_AnyPointerToBlockPointerCast);
13269 return computeResultTy();
13270 }
13271
13272 if (LHSType->isObjCObjectPointerType() ||
13273 RHSType->isObjCObjectPointerType()) {
13274 const PointerType *LPT = LHSType->getAs<PointerType>();
13275 const PointerType *RPT = RHSType->getAs<PointerType>();
13276 if (LPT || RPT) {
13277 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13278 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13279
13280 if (!LPtrToVoid && !RPtrToVoid &&
13281 !Context.typesAreCompatible(LHSType, RHSType)) {
13282 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13283 /*isError*/false);
13284 }
13285 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13286 // the RHS, but we have test coverage for this behavior.
13287 // FIXME: Consider using convertPointersToCompositeType in C++.
13288 if (LHSIsNull && !RHSIsNull) {
13289 Expr *E = LHS.get();
13290 if (getLangOpts().ObjCAutoRefCount)
13291 CheckObjCConversion(SourceRange(), RHSType, E,
13292 CCK_ImplicitConversion);
13293 LHS = ImpCastExprToType(E, RHSType,
13294 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13295 }
13296 else {
13297 Expr *E = RHS.get();
13298 if (getLangOpts().ObjCAutoRefCount)
13299 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
13300 /*Diagnose=*/true,
13301 /*DiagnoseCFAudited=*/false, Opc);
13302 RHS = ImpCastExprToType(E, LHSType,
13303 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13304 }
13305 return computeResultTy();
13306 }
13307 if (LHSType->isObjCObjectPointerType() &&
13308 RHSType->isObjCObjectPointerType()) {
13309 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13310 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13311 /*isError*/false);
13312 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13313 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13314
13315 if (LHSIsNull && !RHSIsNull)
13316 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13317 else
13318 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13319 return computeResultTy();
13320 }
13321
13322 if (!IsOrdered && LHSType->isBlockPointerType() &&
13323 RHSType->isBlockCompatibleObjCPointerType(Context)) {
13324 LHS = ImpCastExprToType(LHS.get(), RHSType,
13325 CK_BlockPointerToObjCPointerCast);
13326 return computeResultTy();
13327 } else if (!IsOrdered &&
13328 LHSType->isBlockCompatibleObjCPointerType(Context) &&
13329 RHSType->isBlockPointerType()) {
13330 RHS = ImpCastExprToType(RHS.get(), LHSType,
13331 CK_BlockPointerToObjCPointerCast);
13332 return computeResultTy();
13333 }
13334 }
13335 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13336 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13337 unsigned DiagID = 0;
13338 bool isError = false;
13339 if (LangOpts.DebuggerSupport) {
13340 // Under a debugger, allow the comparison of pointers to integers,
13341 // since users tend to want to compare addresses.
13342 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13343 (RHSIsNull && RHSType->isIntegerType())) {
13344 if (IsOrdered) {
13345 isError = getLangOpts().CPlusPlus;
13346 DiagID =
13347 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13348 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13349 }
13350 } else if (getLangOpts().CPlusPlus) {
13351 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13352 isError = true;
13353 } else if (IsOrdered)
13354 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13355 else
13356 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13357
13358 if (DiagID) {
13359 Diag(Loc, DiagID)
13360 << LHSType << RHSType << LHS.get()->getSourceRange()
13361 << RHS.get()->getSourceRange();
13362 if (isError)
13363 return QualType();
13364 }
13365
13366 if (LHSType->isIntegerType())
13367 LHS = ImpCastExprToType(LHS.get(), RHSType,
13368 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13369 else
13370 RHS = ImpCastExprToType(RHS.get(), LHSType,
13371 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13372 return computeResultTy();
13373 }
13374
13375 // Handle block pointers.
13376 if (!IsOrdered && RHSIsNull
13377 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13378 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13379 return computeResultTy();
13380 }
13381 if (!IsOrdered && LHSIsNull
13382 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13383 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13384 return computeResultTy();
13385 }
13386
13387 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13388 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13389 return computeResultTy();
13390 }
13391
13392 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13393 return computeResultTy();
13394 }
13395
13396 if (LHSIsNull && RHSType->isQueueT()) {
13397 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13398 return computeResultTy();
13399 }
13400
13401 if (LHSType->isQueueT() && RHSIsNull) {
13402 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13403 return computeResultTy();
13404 }
13405 }
13406
13407 return InvalidOperands(Loc, LHS, RHS);
13408}
13409
13410// Return a signed ext_vector_type that is of identical size and number of
13411// elements. For floating point vectors, return an integer type of identical
13412// size and number of elements. In the non ext_vector_type case, search from
13413// the largest type to the smallest type to avoid cases where long long == long,
13414// where long gets picked over long long.
13415QualType Sema::GetSignedVectorType(QualType V) {
13416 const VectorType *VTy = V->castAs<VectorType>();
13417 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13418
13419 if (isa<ExtVectorType>(VTy)) {
13420 if (VTy->isExtVectorBoolType())
13421 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13422 if (TypeSize == Context.getTypeSize(Context.CharTy))
13423 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13424 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13425 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13426 if (TypeSize == Context.getTypeSize(Context.IntTy))
13427 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13428 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13429 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13430 if (TypeSize == Context.getTypeSize(Context.LongTy))
13431 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13432 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13433 "Unhandled vector element size in vector compare");
13434 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13435 }
13436
13437 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13438 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13439 VectorType::GenericVector);
13440 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13441 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13442 VectorType::GenericVector);
13443 if (TypeSize == Context.getTypeSize(Context.LongTy))
13444 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13445 VectorType::GenericVector);
13446 if (TypeSize == Context.getTypeSize(Context.IntTy))
13447 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13448 VectorType::GenericVector);
13449 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13450 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13451 VectorType::GenericVector);
13452 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13453 "Unhandled vector element size in vector compare");
13454 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13455 VectorType::GenericVector);
13456}
13457
13458QualType Sema::GetSignedSizelessVectorType(QualType V) {
13459 const BuiltinType *VTy = V->castAs<BuiltinType>();
13460 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13461
13462 const QualType ETy = V->getSveEltType(Context);
13463 const auto TypeSize = Context.getTypeSize(ETy);
13464
13465 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13466 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13467 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13468}
13469
13470/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13471/// operates on extended vector types. Instead of producing an IntTy result,
13472/// like a scalar comparison, a vector comparison produces a vector of integer
13473/// types.
13474QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13475 SourceLocation Loc,
13476 BinaryOperatorKind Opc) {
13477 if (Opc == BO_Cmp) {
13478 Diag(Loc, diag::err_three_way_vector_comparison);
13479 return QualType();
13480 }
13481
13482 // Check to make sure we're operating on vectors of the same type and width,
13483 // Allowing one side to be a scalar of element type.
13484 QualType vType =
13485 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13486 /*AllowBothBool*/ true,
13487 /*AllowBoolConversions*/ getLangOpts().ZVector,
13488 /*AllowBooleanOperation*/ true,
13489 /*ReportInvalid*/ true);
13490 if (vType.isNull())
13491 return vType;
13492
13493 QualType LHSType = LHS.get()->getType();
13494
13495 // Determine the return type of a vector compare. By default clang will return
13496 // a scalar for all vector compares except vector bool and vector pixel.
13497 // With the gcc compiler we will always return a vector type and with the xl
13498 // compiler we will always return a scalar type. This switch allows choosing
13499 // which behavior is prefered.
13500 if (getLangOpts().AltiVec) {
13501 switch (getLangOpts().getAltivecSrcCompat()) {
13502 case LangOptions::AltivecSrcCompatKind::Mixed:
13503 // If AltiVec, the comparison results in a numeric type, i.e.
13504 // bool for C++, int for C
13505 if (vType->castAs<VectorType>()->getVectorKind() ==
13506 VectorType::AltiVecVector)
13507 return Context.getLogicalOperationType();
13508 else
13509 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13510 break;
13511 case LangOptions::AltivecSrcCompatKind::GCC:
13512 // For GCC we always return the vector type.
13513 break;
13514 case LangOptions::AltivecSrcCompatKind::XL:
13515 return Context.getLogicalOperationType();
13516 break;
13517 }
13518 }
13519
13520 // For non-floating point types, check for self-comparisons of the form
13521 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13522 // often indicate logic errors in the program.
13523 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13524
13525 // Check for comparisons of floating point operands using != and ==.
13526 if (LHSType->hasFloatingRepresentation()) {
13527 assert(RHS.get()->getType()->hasFloatingRepresentation());
13528 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13529 }
13530
13531 // Return a signed type for the vector.
13532 return GetSignedVectorType(vType);
13533}
13534
13535QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13536 ExprResult &RHS,
13537 SourceLocation Loc,
13538 BinaryOperatorKind Opc) {
13539 if (Opc == BO_Cmp) {
13540 Diag(Loc, diag::err_three_way_vector_comparison);
13541 return QualType();
13542 }
13543
13544 // Check to make sure we're operating on vectors of the same type and width,
13545 // Allowing one side to be a scalar of element type.
13546 QualType vType = CheckSizelessVectorOperands(
13547 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13548
13549 if (vType.isNull())
13550 return vType;
13551
13552 QualType LHSType = LHS.get()->getType();
13553
13554 // For non-floating point types, check for self-comparisons of the form
13555 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13556 // often indicate logic errors in the program.
13557 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13558
13559 // Check for comparisons of floating point operands using != and ==.
13560 if (LHSType->hasFloatingRepresentation()) {
13561 assert(RHS.get()->getType()->hasFloatingRepresentation());
13562 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13563 }
13564
13565 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13566 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13567
13568 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13569 RHSBuiltinTy->isSVEBool())
13570 return LHSType;
13571
13572 // Return a signed type for the vector.
13573 return GetSignedSizelessVectorType(vType);
13574}
13575
13576static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13577 const ExprResult &XorRHS,
13578 const SourceLocation Loc) {
13579 // Do not diagnose macros.
13580 if (Loc.isMacroID())
13581 return;
13582
13583 // Do not diagnose if both LHS and RHS are macros.
13584 if (XorLHS.get()->getExprLoc().isMacroID() &&
13585 XorRHS.get()->getExprLoc().isMacroID())
13586 return;
13587
13588 bool Negative = false;
13589 bool ExplicitPlus = false;
13590 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13591 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13592
13593 if (!LHSInt)
13594 return;
13595 if (!RHSInt) {
13596 // Check negative literals.
13597 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13598 UnaryOperatorKind Opc = UO->getOpcode();
13599 if (Opc != UO_Minus && Opc != UO_Plus)
13600 return;
13601 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13602 if (!RHSInt)
13603 return;
13604 Negative = (Opc == UO_Minus);
13605 ExplicitPlus = !Negative;
13606 } else {
13607 return;
13608 }
13609 }
13610
13611 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13612 llvm::APInt RightSideValue = RHSInt->getValue();
13613 if (LeftSideValue != 2 && LeftSideValue != 10)
13614 return;
13615
13616 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13617 return;
13618
13619 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13620 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13621 llvm::StringRef ExprStr =
13622 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13623
13624 CharSourceRange XorRange =
13625 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13626 llvm::StringRef XorStr =
13627 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13628 // Do not diagnose if xor keyword/macro is used.
13629 if (XorStr == "xor")
13630 return;
13631
13632 std::string LHSStr = std::string(Lexer::getSourceText(
13633 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13634 S.getSourceManager(), S.getLangOpts()));
13635 std::string RHSStr = std::string(Lexer::getSourceText(
13636 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13637 S.getSourceManager(), S.getLangOpts()));
13638
13639 if (Negative) {
13640 RightSideValue = -RightSideValue;
13641 RHSStr = "-" + RHSStr;
13642 } else if (ExplicitPlus) {
13643 RHSStr = "+" + RHSStr;
13644 }
13645
13646 StringRef LHSStrRef = LHSStr;
13647 StringRef RHSStrRef = RHSStr;
13648 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13649 // literals.
13650 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13651 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13652 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13653 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13654 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13655 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13656 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13657 return;
13658
13659 bool SuggestXor =
13660 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13661 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13662 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13663 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13664 std::string SuggestedExpr = "1 << " + RHSStr;
13665 bool Overflow = false;
13666 llvm::APInt One = (LeftSideValue - 1);
13667 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13668 if (Overflow) {
13669 if (RightSideIntValue < 64)
13670 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13671 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13672 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13673 else if (RightSideIntValue == 64)
13674 S.Diag(Loc, diag::warn_xor_used_as_pow)
13675 << ExprStr << toString(XorValue, 10, true);
13676 else
13677 return;
13678 } else {
13679 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13680 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13681 << toString(PowValue, 10, true)
13682 << FixItHint::CreateReplacement(
13683 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13684 }
13685
13686 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13687 << ("0x2 ^ " + RHSStr) << SuggestXor;
13688 } else if (LeftSideValue == 10) {
13689 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13690 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13691 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13692 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13693 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13694 << ("0xA ^ " + RHSStr) << SuggestXor;
13695 }
13696}
13697
13698QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13699 SourceLocation Loc) {
13700 // Ensure that either both operands are of the same vector type, or
13701 // one operand is of a vector type and the other is of its element type.
13702 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13703 /*AllowBothBool*/ true,
13704 /*AllowBoolConversions*/ false,
13705 /*AllowBooleanOperation*/ false,
13706 /*ReportInvalid*/ false);
13707 if (vType.isNull())
13708 return InvalidOperands(Loc, LHS, RHS);
13709 if (getLangOpts().OpenCL &&
13710 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13711 vType->hasFloatingRepresentation())
13712 return InvalidOperands(Loc, LHS, RHS);
13713 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13714 // usage of the logical operators && and || with vectors in C. This
13715 // check could be notionally dropped.
13716 if (!getLangOpts().CPlusPlus &&
13717 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13718 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13719
13720 return GetSignedVectorType(LHS.get()->getType());
13721}
13722
13723QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13724 SourceLocation Loc,
13725 bool IsCompAssign) {
13726 if (!IsCompAssign) {
13727 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13728 if (LHS.isInvalid())
13729 return QualType();
13730 }
13731 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13732 if (RHS.isInvalid())
13733 return QualType();
13734
13735 // For conversion purposes, we ignore any qualifiers.
13736 // For example, "const float" and "float" are equivalent.
13737 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13738 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13739
13740 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13741 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13742 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13743
13744 if (Context.hasSameType(LHSType, RHSType))
13745 return Context.getCommonSugaredType(LHSType, RHSType);
13746
13747 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13748 // case we have to return InvalidOperands.
13749 ExprResult OriginalLHS = LHS;
13750 ExprResult OriginalRHS = RHS;
13751 if (LHSMatType && !RHSMatType) {
13752 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13753 if (!RHS.isInvalid())
13754 return LHSType;
13755
13756 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13757 }
13758
13759 if (!LHSMatType && RHSMatType) {
13760 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13761 if (!LHS.isInvalid())
13762 return RHSType;
13763 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13764 }
13765
13766 return InvalidOperands(Loc, LHS, RHS);
13767}
13768
13769QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13770 SourceLocation Loc,
13771 bool IsCompAssign) {
13772 if (!IsCompAssign) {
13773 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13774 if (LHS.isInvalid())
13775 return QualType();
13776 }
13777 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13778 if (RHS.isInvalid())
13779 return QualType();
13780
13781 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13782 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13783 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13784
13785 if (LHSMatType && RHSMatType) {
13786 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13787 return InvalidOperands(Loc, LHS, RHS);
13788
13789 if (Context.hasSameType(LHSMatType, RHSMatType))
13790 return Context.getCommonSugaredType(
13791 LHS.get()->getType().getUnqualifiedType(),
13792 RHS.get()->getType().getUnqualifiedType());
13793
13794 QualType LHSELTy = LHSMatType->getElementType(),
13795 RHSELTy = RHSMatType->getElementType();
13796 if (!Context.hasSameType(LHSELTy, RHSELTy))
13797 return InvalidOperands(Loc, LHS, RHS);
13798
13799 return Context.getConstantMatrixType(
13800 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13801 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13802 }
13803 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13804}
13805
13806static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13807 switch (Opc) {
13808 default:
13809 return false;
13810 case BO_And:
13811 case BO_AndAssign:
13812 case BO_Or:
13813 case BO_OrAssign:
13814 case BO_Xor:
13815 case BO_XorAssign:
13816 return true;
13817 }
13818}
13819
13820inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13821 SourceLocation Loc,
13822 BinaryOperatorKind Opc) {
13823 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13824
13825 bool IsCompAssign =
13826 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13827
13828 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13829
13830 if (LHS.get()->getType()->isVectorType() ||
13831 RHS.get()->getType()->isVectorType()) {
13832 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13833 RHS.get()->getType()->hasIntegerRepresentation())
13834 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13835 /*AllowBothBool*/ true,
13836 /*AllowBoolConversions*/ getLangOpts().ZVector,
13837 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13838 /*ReportInvalid*/ true);
13839 return InvalidOperands(Loc, LHS, RHS);
13840 }
13841
13842 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13843 RHS.get()->getType()->isVLSTBuiltinType()) {
13844 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13845 RHS.get()->getType()->hasIntegerRepresentation())
13846 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13847 ACK_BitwiseOp);
13848 return InvalidOperands(Loc, LHS, RHS);
13849 }
13850
13851 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13852 RHS.get()->getType()->isVLSTBuiltinType()) {
13853 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13854 RHS.get()->getType()->hasIntegerRepresentation())
13855 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13856 ACK_BitwiseOp);
13857 return InvalidOperands(Loc, LHS, RHS);
13858 }
13859
13860 if (Opc == BO_And)
13861 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13862
13863 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13864 RHS.get()->getType()->hasFloatingRepresentation())
13865 return InvalidOperands(Loc, LHS, RHS);
13866
13867 ExprResult LHSResult = LHS, RHSResult = RHS;
13868 QualType compType = UsualArithmeticConversions(
13869 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13870 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13871 return QualType();
13872 LHS = LHSResult.get();
13873 RHS = RHSResult.get();
13874
13875 if (Opc == BO_Xor)
13876 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13877
13878 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13879 return compType;
13880 return InvalidOperands(Loc, LHS, RHS);
13881}
13882
13883// C99 6.5.[13,14]
13884inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13885 SourceLocation Loc,
13886 BinaryOperatorKind Opc) {
13887 // Check vector operands differently.
13888 if (LHS.get()->getType()->isVectorType() ||
13889 RHS.get()->getType()->isVectorType())
13890 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13891
13892 bool EnumConstantInBoolContext = false;
13893 for (const ExprResult &HS : {LHS, RHS}) {
13894 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13895 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13896 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13897 EnumConstantInBoolContext = true;
13898 }
13899 }
13900
13901 if (EnumConstantInBoolContext)
13902 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13903
13904 // WebAssembly tables can't be used with logical operators.
13905 QualType LHSTy = LHS.get()->getType();
13906 QualType RHSTy = RHS.get()->getType();
13907 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13908 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13909 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13910 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13911 return InvalidOperands(Loc, LHS, RHS);
13912 }
13913
13914 // Diagnose cases where the user write a logical and/or but probably meant a
13915 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13916 // is a constant.
13917 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13918 !LHS.get()->getType()->isBooleanType() &&
13919 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13920 // Don't warn in macros or template instantiations.
13921 !Loc.isMacroID() && !inTemplateInstantiation()) {
13922 // If the RHS can be constant folded, and if it constant folds to something
13923 // that isn't 0 or 1 (which indicate a potential logical operation that
13924 // happened to fold to true/false) then warn.
13925 // Parens on the RHS are ignored.
13926 Expr::EvalResult EVResult;
13927 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13928 llvm::APSInt Result = EVResult.Val.getInt();
13929 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13930 !RHS.get()->getExprLoc().isMacroID()) ||
13931 (Result != 0 && Result != 1)) {
13932 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13933 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13934 // Suggest replacing the logical operator with the bitwise version
13935 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13936 << (Opc == BO_LAnd ? "&" : "|")
13937 << FixItHint::CreateReplacement(
13938 SourceRange(Loc, getLocForEndOfToken(Loc)),
13939 Opc == BO_LAnd ? "&" : "|");
13940 if (Opc == BO_LAnd)
13941 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13942 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13943 << FixItHint::CreateRemoval(
13944 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13945 RHS.get()->getEndLoc()));
13946 }
13947 }
13948 }
13949
13950 if (!Context.getLangOpts().CPlusPlus) {
13951 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13952 // not operate on the built-in scalar and vector float types.
13953 if (Context.getLangOpts().OpenCL &&
13954 Context.getLangOpts().OpenCLVersion < 120) {
13955 if (LHS.get()->getType()->isFloatingType() ||
13956 RHS.get()->getType()->isFloatingType())
13957 return InvalidOperands(Loc, LHS, RHS);
13958 }
13959
13960 LHS = UsualUnaryConversions(LHS.get());
13961 if (LHS.isInvalid())
13962 return QualType();
13963
13964 RHS = UsualUnaryConversions(RHS.get());
13965 if (RHS.isInvalid())
13966 return QualType();
13967
13968 if (!LHS.get()->getType()->isScalarType() ||
13969 !RHS.get()->getType()->isScalarType())
13970 return InvalidOperands(Loc, LHS, RHS);
13971
13972 return Context.IntTy;
13973 }
13974
13975 // The following is safe because we only use this method for
13976 // non-overloadable operands.
13977
13978 // C++ [expr.log.and]p1
13979 // C++ [expr.log.or]p1
13980 // The operands are both contextually converted to type bool.
13981 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13982 if (LHSRes.isInvalid())
13983 return InvalidOperands(Loc, LHS, RHS);
13984 LHS = LHSRes;
13985
13986 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13987 if (RHSRes.isInvalid())
13988 return InvalidOperands(Loc, LHS, RHS);
13989 RHS = RHSRes;
13990
13991 // C++ [expr.log.and]p2
13992 // C++ [expr.log.or]p2
13993 // The result is a bool.
13994 return Context.BoolTy;
13995}
13996
13997static bool IsReadonlyMessage(Expr *E, Sema &S) {
13998 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13999 if (!ME) return false;
14000 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14001 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14002 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14003 if (!Base) return false;
14004 return Base->getMethodDecl() != nullptr;
14005}
14006
14007/// Is the given expression (which must be 'const') a reference to a
14008/// variable which was originally non-const, but which has become
14009/// 'const' due to being captured within a block?
14010enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14011static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14012 assert(E->isLValue() && E->getType().isConstQualified());
14013 E = E->IgnoreParens();
14014
14015 // Must be a reference to a declaration from an enclosing scope.
14016 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14017 if (!DRE) return NCCK_None;
14018 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14019
14020 // The declaration must be a variable which is not declared 'const'.
14021 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
14022 if (!var) return NCCK_None;
14023 if (var->getType().isConstQualified()) return NCCK_None;
14024 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
14025
14026 // Decide whether the first capture was for a block or a lambda.
14027 DeclContext *DC = S.CurContext, *Prev = nullptr;
14028 // Decide whether the first capture was for a block or a lambda.
14029 while (DC) {
14030 // For init-capture, it is possible that the variable belongs to the
14031 // template pattern of the current context.
14032 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14033 if (var->isInitCapture() &&
14034 FD->getTemplateInstantiationPattern() == var->getDeclContext())
14035 break;
14036 if (DC == var->getDeclContext())
14037 break;
14038 Prev = DC;
14039 DC = DC->getParent();
14040 }
14041 // Unless we have an init-capture, we've gone one step too far.
14042 if (!var->isInitCapture())
14043 DC = Prev;
14044 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14045}
14046
14047static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14048 Ty = Ty.getNonReferenceType();
14049 if (IsDereference && Ty->isPointerType())
14050 Ty = Ty->getPointeeType();
14051 return !Ty.isConstQualified();
14052}
14053
14054// Update err_typecheck_assign_const and note_typecheck_assign_const
14055// when this enum is changed.
14056enum {
14057 ConstFunction,
14058 ConstVariable,
14059 ConstMember,
14060 ConstMethod,
14061 NestedConstMember,
14062 ConstUnknown, // Keep as last element
14063};
14064
14065/// Emit the "read-only variable not assignable" error and print notes to give
14066/// more information about why the variable is not assignable, such as pointing
14067/// to the declaration of a const variable, showing that a method is const, or
14068/// that the function is returning a const reference.
14069static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14070 SourceLocation Loc) {
14071 SourceRange ExprRange = E->getSourceRange();
14072
14073 // Only emit one error on the first const found. All other consts will emit
14074 // a note to the error.
14075 bool DiagnosticEmitted = false;
14076
14077 // Track if the current expression is the result of a dereference, and if the
14078 // next checked expression is the result of a dereference.
14079 bool IsDereference = false;
14080 bool NextIsDereference = false;
14081
14082 // Loop to process MemberExpr chains.
14083 while (true) {
14084 IsDereference = NextIsDereference;
14085
14086 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14087 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14088 NextIsDereference = ME->isArrow();
14089 const ValueDecl *VD = ME->getMemberDecl();
14090 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14091 // Mutable fields can be modified even if the class is const.
14092 if (Field->isMutable()) {
14093 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14094 break;
14095 }
14096
14097 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14098 if (!DiagnosticEmitted) {
14099 S.Diag(Loc, diag::err_typecheck_assign_const)
14100 << ExprRange << ConstMember << false /*static*/ << Field
14101 << Field->getType();
14102 DiagnosticEmitted = true;
14103 }
14104 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14105 << ConstMember << false /*static*/ << Field << Field->getType()
14106 << Field->getSourceRange();
14107 }
14108 E = ME->getBase();
14109 continue;
14110 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14111 if (VDecl->getType().isConstQualified()) {
14112 if (!DiagnosticEmitted) {
14113 S.Diag(Loc, diag::err_typecheck_assign_const)
14114 << ExprRange << ConstMember << true /*static*/ << VDecl
14115 << VDecl->getType();
14116 DiagnosticEmitted = true;
14117 }
14118 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14119 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14120 << VDecl->getSourceRange();
14121 }
14122 // Static fields do not inherit constness from parents.
14123 break;
14124 }
14125 break; // End MemberExpr
14126 } else if (const ArraySubscriptExpr *ASE =
14127 dyn_cast<ArraySubscriptExpr>(E)) {
14128 E = ASE->getBase()->IgnoreParenImpCasts();
14129 continue;
14130 } else if (const ExtVectorElementExpr *EVE =
14131 dyn_cast<ExtVectorElementExpr>(E)) {
14132 E = EVE->getBase()->IgnoreParenImpCasts();
14133 continue;
14134 }
14135 break;
14136 }
14137
14138 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14139 // Function calls
14140 const FunctionDecl *FD = CE->getDirectCallee();
14141 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14142 if (!DiagnosticEmitted) {
14143 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14144 << ConstFunction << FD;
14145 DiagnosticEmitted = true;
14146 }
14147 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
14148 diag::note_typecheck_assign_const)
14149 << ConstFunction << FD << FD->getReturnType()
14150 << FD->getReturnTypeSourceRange();
14151 }
14152 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14153 // Point to variable declaration.
14154 if (const ValueDecl *VD = DRE->getDecl()) {
14155 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14156 if (!DiagnosticEmitted) {
14157 S.Diag(Loc, diag::err_typecheck_assign_const)
14158 << ExprRange << ConstVariable << VD << VD->getType();
14159 DiagnosticEmitted = true;
14160 }
14161 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14162 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14163 }
14164 }
14165 } else if (isa<CXXThisExpr>(E)) {
14166 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14167 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14168 if (MD->isConst()) {
14169 if (!DiagnosticEmitted) {
14170 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14171 << ConstMethod << MD;
14172 DiagnosticEmitted = true;
14173 }
14174 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
14175 << ConstMethod << MD << MD->getSourceRange();
14176 }
14177 }
14178 }
14179 }
14180
14181 if (DiagnosticEmitted)
14182 return;
14183
14184 // Can't determine a more specific message, so display the generic error.
14185 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14186}
14187
14188enum OriginalExprKind {
14189 OEK_Variable,
14190 OEK_Member,
14191 OEK_LValue
14192};
14193
14194static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14195 const RecordType *Ty,
14196 SourceLocation Loc, SourceRange Range,
14197 OriginalExprKind OEK,
14198 bool &DiagnosticEmitted) {
14199 std::vector<const RecordType *> RecordTypeList;
14200 RecordTypeList.push_back(Ty);
14201 unsigned NextToCheckIndex = 0;
14202 // We walk the record hierarchy breadth-first to ensure that we print
14203 // diagnostics in field nesting order.
14204 while (RecordTypeList.size() > NextToCheckIndex) {
14205 bool IsNested = NextToCheckIndex > 0;
14206 for (const FieldDecl *Field :
14207 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
14208 // First, check every field for constness.
14209 QualType FieldTy = Field->getType();
14210 if (FieldTy.isConstQualified()) {
14211 if (!DiagnosticEmitted) {
14212 S.Diag(Loc, diag::err_typecheck_assign_const)
14213 << Range << NestedConstMember << OEK << VD
14214 << IsNested << Field;
14215 DiagnosticEmitted = true;
14216 }
14217 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14218 << NestedConstMember << IsNested << Field
14219 << FieldTy << Field->getSourceRange();
14220 }
14221
14222 // Then we append it to the list to check next in order.
14223 FieldTy = FieldTy.getCanonicalType();
14224 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
14225 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14226 RecordTypeList.push_back(FieldRecTy);
14227 }
14228 }
14229 ++NextToCheckIndex;
14230 }
14231}
14232
14233/// Emit an error for the case where a record we are trying to assign to has a
14234/// const-qualified field somewhere in its hierarchy.
14235static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14236 SourceLocation Loc) {
14237 QualType Ty = E->getType();
14238 assert(Ty->isRecordType() && "lvalue was not record?");
14239 SourceRange Range = E->getSourceRange();
14240 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
14241 bool DiagEmitted = false;
14242
14243 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14244 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14245 Range, OEK_Member, DiagEmitted);
14246 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14247 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14248 Range, OEK_Variable, DiagEmitted);
14249 else
14250 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14251 Range, OEK_LValue, DiagEmitted);
14252 if (!DiagEmitted)
14253 DiagnoseConstAssignment(S, E, Loc);
14254}
14255
14256/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14257/// emit an error and return true. If so, return false.
14258static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14259 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14260
14261 S.CheckShadowingDeclModification(E, Loc);
14262
14263 SourceLocation OrigLoc = Loc;
14264 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
14265 &Loc);
14266 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14267 IsLV = Expr::MLV_InvalidMessageExpression;
14268 if (IsLV == Expr::MLV_Valid)
14269 return false;
14270
14271 unsigned DiagID = 0;
14272 bool NeedType = false;
14273 switch (IsLV) { // C99 6.5.16p2
14274 case Expr::MLV_ConstQualified:
14275 // Use a specialized diagnostic when we're assigning to an object
14276 // from an enclosing function or block.
14277 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14278 if (NCCK == NCCK_Block)
14279 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14280 else
14281 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14282 break;
14283 }
14284
14285 // In ARC, use some specialized diagnostics for occasions where we
14286 // infer 'const'. These are always pseudo-strong variables.
14287 if (S.getLangOpts().ObjCAutoRefCount) {
14288 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14289 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14290 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14291
14292 // Use the normal diagnostic if it's pseudo-__strong but the
14293 // user actually wrote 'const'.
14294 if (var->isARCPseudoStrong() &&
14295 (!var->getTypeSourceInfo() ||
14296 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14297 // There are three pseudo-strong cases:
14298 // - self
14299 ObjCMethodDecl *method = S.getCurMethodDecl();
14300 if (method && var == method->getSelfDecl()) {
14301 DiagID = method->isClassMethod()
14302 ? diag::err_typecheck_arc_assign_self_class_method
14303 : diag::err_typecheck_arc_assign_self;
14304
14305 // - Objective-C externally_retained attribute.
14306 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14307 isa<ParmVarDecl>(var)) {
14308 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14309
14310 // - fast enumeration variables
14311 } else {
14312 DiagID = diag::err_typecheck_arr_assign_enumeration;
14313 }
14314
14315 SourceRange Assign;
14316 if (Loc != OrigLoc)
14317 Assign = SourceRange(OrigLoc, OrigLoc);
14318 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14319 // We need to preserve the AST regardless, so migration tool
14320 // can do its job.
14321 return false;
14322 }
14323 }
14324 }
14325
14326 // If none of the special cases above are triggered, then this is a
14327 // simple const assignment.
14328 if (DiagID == 0) {
14329 DiagnoseConstAssignment(S, E, Loc);
14330 return true;
14331 }
14332
14333 break;
14334 case Expr::MLV_ConstAddrSpace:
14335 DiagnoseConstAssignment(S, E, Loc);
14336 return true;
14337 case Expr::MLV_ConstQualifiedField:
14338 DiagnoseRecursiveConstFields(S, E, Loc);
14339 return true;
14340 case Expr::MLV_ArrayType:
14341 case Expr::MLV_ArrayTemporary:
14342 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14343 NeedType = true;
14344 break;
14345 case Expr::MLV_NotObjectType:
14346 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14347 NeedType = true;
14348 break;
14349 case Expr::MLV_LValueCast:
14350 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14351 break;
14352 case Expr::MLV_Valid:
14353 llvm_unreachable("did not take early return for MLV_Valid");
14354 case Expr::MLV_InvalidExpression:
14355 case Expr::MLV_MemberFunction:
14356 case Expr::MLV_ClassTemporary:
14357 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14358 break;
14359 case Expr::MLV_IncompleteType:
14360 case Expr::MLV_IncompleteVoidType:
14361 return S.RequireCompleteType(Loc, E->getType(),
14362 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14363 case Expr::MLV_DuplicateVectorComponents:
14364 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14365 break;
14366 case Expr::MLV_NoSetterProperty:
14367 llvm_unreachable("readonly properties should be processed differently");
14368 case Expr::MLV_InvalidMessageExpression:
14369 DiagID = diag::err_readonly_message_assignment;
14370 break;
14371 case Expr::MLV_SubObjCPropertySetting:
14372 DiagID = diag::err_no_subobject_property_setting;
14373 break;
14374 }
14375
14376 SourceRange Assign;
14377 if (Loc != OrigLoc)
14378 Assign = SourceRange(OrigLoc, OrigLoc);
14379 if (NeedType)
14380 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14381 else
14382 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14383 return true;
14384}
14385
14386static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14387 SourceLocation Loc,
14388 Sema &Sema) {
14389 if (Sema.inTemplateInstantiation())
14390 return;
14391 if (Sema.isUnevaluatedContext())
14392 return;
14393 if (Loc.isInvalid() || Loc.isMacroID())
14394 return;
14395 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14396 return;
14397
14398 // C / C++ fields
14399 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14400 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14401 if (ML && MR) {
14402 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14403 return;
14404 const ValueDecl *LHSDecl =
14405 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14406 const ValueDecl *RHSDecl =
14407 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14408 if (LHSDecl != RHSDecl)
14409 return;
14410 if (LHSDecl->getType().isVolatileQualified())
14411 return;
14412 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14413 if (RefTy->getPointeeType().isVolatileQualified())
14414 return;
14415
14416 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14417 }
14418
14419 // Objective-C instance variables
14420 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14421 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14422 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14423 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14424 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14425 if (RL && RR && RL->getDecl() == RR->getDecl())
14426 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14427 }
14428}
14429
14430// C99 6.5.16.1
14431QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14432 SourceLocation Loc,
14433 QualType CompoundType,
14434 BinaryOperatorKind Opc) {
14435 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14436
14437 // Verify that LHS is a modifiable lvalue, and emit error if not.
14438 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14439 return QualType();
14440
14441 QualType LHSType = LHSExpr->getType();
14442 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14443 CompoundType;
14444 // OpenCL v1.2 s6.1.1.1 p2:
14445 // The half data type can only be used to declare a pointer to a buffer that
14446 // contains half values
14447 if (getLangOpts().OpenCL &&
14448 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14449 LHSType->isHalfType()) {
14450 Diag(Loc, diag::err_opencl_half_load_store) << 1
14451 << LHSType.getUnqualifiedType();
14452 return QualType();
14453 }
14454
14455 // WebAssembly tables can't be used on RHS of an assignment expression.
14456 if (RHSType->isWebAssemblyTableType()) {
14457 Diag(Loc, diag::err_wasm_table_art) << 0;
14458 return QualType();
14459 }
14460
14461 AssignConvertType ConvTy;
14462 if (CompoundType.isNull()) {
14463 Expr *RHSCheck = RHS.get();
14464
14465 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14466
14467 QualType LHSTy(LHSType);
14468 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14469 if (RHS.isInvalid())
14470 return QualType();
14471 // Special case of NSObject attributes on c-style pointer types.
14472 if (ConvTy == IncompatiblePointer &&
14473 ((Context.isObjCNSObjectType(LHSType) &&
14474 RHSType->isObjCObjectPointerType()) ||
14475 (Context.isObjCNSObjectType(RHSType) &&
14476 LHSType->isObjCObjectPointerType())))
14477 ConvTy = Compatible;
14478
14479 if (ConvTy == Compatible &&
14480 LHSType->isObjCObjectType())
14481 Diag(Loc, diag::err_objc_object_assignment)
14482 << LHSType;
14483
14484 // If the RHS is a unary plus or minus, check to see if they = and + are
14485 // right next to each other. If so, the user may have typo'd "x =+ 4"
14486 // instead of "x += 4".
14487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14488 RHSCheck = ICE->getSubExpr();
14489 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14490 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14491 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14492 // Only if the two operators are exactly adjacent.
14493 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14494 // And there is a space or other character before the subexpr of the
14495 // unary +/-. We don't want to warn on "x=-1".
14496 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14497 UO->getSubExpr()->getBeginLoc().isFileID()) {
14498 Diag(Loc, diag::warn_not_compound_assign)
14499 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14500 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14501 }
14502 }
14503
14504 if (ConvTy == Compatible) {
14505 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14506 // Warn about retain cycles where a block captures the LHS, but
14507 // not if the LHS is a simple variable into which the block is
14508 // being stored...unless that variable can be captured by reference!
14509 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14510 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14511 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14512 checkRetainCycles(LHSExpr, RHS.get());
14513 }
14514
14515 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14516 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14517 // It is safe to assign a weak reference into a strong variable.
14518 // Although this code can still have problems:
14519 // id x = self.weakProp;
14520 // id y = self.weakProp;
14521 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14522 // paths through the function. This should be revisited if
14523 // -Wrepeated-use-of-weak is made flow-sensitive.
14524 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14525 // variable, which will be valid for the current autorelease scope.
14526 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14527 RHS.get()->getBeginLoc()))
14528 getCurFunction()->markSafeWeakUse(RHS.get());
14529
14530 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14531 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14532 }
14533 }
14534 } else {
14535 // Compound assignment "x += y"
14536 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14537 }
14538
14539 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14540 RHS.get(), AA_Assigning))
14541 return QualType();
14542
14543 CheckForNullPointerDereference(*this, LHSExpr);
14544
14545 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14546 if (CompoundType.isNull()) {
14547 // C++2a [expr.ass]p5:
14548 // A simple-assignment whose left operand is of a volatile-qualified
14549 // type is deprecated unless the assignment is either a discarded-value
14550 // expression or an unevaluated operand
14551 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14552 }
14553 }
14554
14555 // C11 6.5.16p3: The type of an assignment expression is the type of the
14556 // left operand would have after lvalue conversion.
14557 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14558 // qualified type, the value has the unqualified version of the type of the
14559 // lvalue; additionally, if the lvalue has atomic type, the value has the
14560 // non-atomic version of the type of the lvalue.
14561 // C++ 5.17p1: the type of the assignment expression is that of its left
14562 // operand.
14563 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14564}
14565
14566// Scenarios to ignore if expression E is:
14567// 1. an explicit cast expression into void
14568// 2. a function call expression that returns void
14569static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14570 E = E->IgnoreParens();
14571
14572 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14573 if (CE->getCastKind() == CK_ToVoid) {
14574 return true;
14575 }
14576
14577 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14578 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14579 CE->getSubExpr()->getType()->isDependentType()) {
14580 return true;
14581 }
14582 }
14583
14584 if (const auto *CE = dyn_cast<CallExpr>(E))
14585 return CE->getCallReturnType(Context)->isVoidType();
14586 return false;
14587}
14588
14589// Look for instances where it is likely the comma operator is confused with
14590// another operator. There is an explicit list of acceptable expressions for
14591// the left hand side of the comma operator, otherwise emit a warning.
14592void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14593 // No warnings in macros
14594 if (Loc.isMacroID())
14595 return;
14596
14597 // Don't warn in template instantiations.
14598 if (inTemplateInstantiation())
14599 return;
14600
14601 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14602 // instead, skip more than needed, then call back into here with the
14603 // CommaVisitor in SemaStmt.cpp.
14604 // The listed locations are the initialization and increment portions
14605 // of a for loop. The additional checks are on the condition of
14606 // if statements, do/while loops, and for loops.
14607 // Differences in scope flags for C89 mode requires the extra logic.
14608 const unsigned ForIncrementFlags =
14609 getLangOpts().C99 || getLangOpts().CPlusPlus
14610 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14611 : Scope::ContinueScope | Scope::BreakScope;
14612 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14613 const unsigned ScopeFlags = getCurScope()->getFlags();
14614 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14615 (ScopeFlags & ForInitFlags) == ForInitFlags)
14616 return;
14617
14618 // If there are multiple comma operators used together, get the RHS of the
14619 // of the comma operator as the LHS.
14620 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14621 if (BO->getOpcode() != BO_Comma)
14622 break;
14623 LHS = BO->getRHS();
14624 }
14625
14626 // Only allow some expressions on LHS to not warn.
14627 if (IgnoreCommaOperand(LHS, Context))
14628 return;
14629
14630 Diag(Loc, diag::warn_comma_operator);
14631 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14632 << LHS->getSourceRange()
14633 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14634 LangOpts.CPlusPlus ? "static_cast<void>("
14635 : "(void)(")
14636 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14637 ")");
14638}
14639
14640// C99 6.5.17
14641static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14642 SourceLocation Loc) {
14643 LHS = S.CheckPlaceholderExpr(LHS.get());
14644 RHS = S.CheckPlaceholderExpr(RHS.get());
14645 if (LHS.isInvalid() || RHS.isInvalid())
14646 return QualType();
14647
14648 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14649 // operands, but not unary promotions.
14650 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14651
14652 // So we treat the LHS as a ignored value, and in C++ we allow the
14653 // containing site to determine what should be done with the RHS.
14654 LHS = S.IgnoredValueConversions(LHS.get());
14655 if (LHS.isInvalid())
14656 return QualType();
14657
14658 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14659
14660 if (!S.getLangOpts().CPlusPlus) {
14661 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14662 if (RHS.isInvalid())
14663 return QualType();
14664 if (!RHS.get()->getType()->isVoidType())
14665 S.RequireCompleteType(Loc, RHS.get()->getType(),
14666 diag::err_incomplete_type);
14667 }
14668
14669 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14670 S.DiagnoseCommaOperator(LHS.get(), Loc);
14671
14672 return RHS.get()->getType();
14673}
14674
14675/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14676/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14677static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14678 ExprValueKind &VK,
14679 ExprObjectKind &OK,
14680 SourceLocation OpLoc,
14681 bool IsInc, bool IsPrefix) {
14682 if (Op->isTypeDependent())
14683 return S.Context.DependentTy;
14684
14685 QualType ResType = Op->getType();
14686 // Atomic types can be used for increment / decrement where the non-atomic
14687 // versions can, so ignore the _Atomic() specifier for the purpose of
14688 // checking.
14689 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14690 ResType = ResAtomicType->getValueType();
14691
14692 assert(!ResType.isNull() && "no type for increment/decrement expression");
14693
14694 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14695 // Decrement of bool is not allowed.
14696 if (!IsInc) {
14697 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14698 return QualType();
14699 }
14700 // Increment of bool sets it to true, but is deprecated.
14701 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14702 : diag::warn_increment_bool)
14703 << Op->getSourceRange();
14704 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14705 // Error on enum increments and decrements in C++ mode
14706 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14707 return QualType();
14708 } else if (ResType->isRealType()) {
14709 // OK!
14710 } else if (ResType->isPointerType()) {
14711 // C99 6.5.2.4p2, 6.5.6p2
14712 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14713 return QualType();
14714 } else if (ResType->isObjCObjectPointerType()) {
14715 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14716 // Otherwise, we just need a complete type.
14717 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14718 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14719 return QualType();
14720 } else if (ResType->isAnyComplexType()) {
14721 // C99 does not support ++/-- on complex types, we allow as an extension.
14722 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14723 << ResType << Op->getSourceRange();
14724 } else if (ResType->isPlaceholderType()) {
14725 ExprResult PR = S.CheckPlaceholderExpr(Op);
14726 if (PR.isInvalid()) return QualType();
14727 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14728 IsInc, IsPrefix);
14729 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14730 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14731 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14732 (ResType->castAs<VectorType>()->getVectorKind() !=
14733 VectorType::AltiVecBool)) {
14734 // The z vector extensions allow ++ and -- for non-bool vectors.
14735 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14736 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14737 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14738 } else {
14739 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14740 << ResType << int(IsInc) << Op->getSourceRange();
14741 return QualType();
14742 }
14743 // At this point, we know we have a real, complex or pointer type.
14744 // Now make sure the operand is a modifiable lvalue.
14745 if (CheckForModifiableLvalue(Op, OpLoc, S))
14746 return QualType();
14747 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14748 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14749 // An operand with volatile-qualified type is deprecated
14750 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14751 << IsInc << ResType;
14752 }
14753 // In C++, a prefix increment is the same type as the operand. Otherwise
14754 // (in C or with postfix), the increment is the unqualified type of the
14755 // operand.
14756 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14757 VK = VK_LValue;
14758 OK = Op->getObjectKind();
14759 return ResType;
14760 } else {
14761 VK = VK_PRValue;
14762 return ResType.getUnqualifiedType();
14763 }
14764}
14765
14766
14767/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14768/// This routine allows us to typecheck complex/recursive expressions
14769/// where the declaration is needed for type checking. We only need to
14770/// handle cases when the expression references a function designator
14771/// or is an lvalue. Here are some examples:
14772/// - &(x) => x
14773/// - &*****f => f for f a function designator.
14774/// - &s.xx => s
14775/// - &s.zz[1].yy -> s, if zz is an array
14776/// - *(x + 1) -> x, if x is an array
14777/// - &"123"[2] -> 0
14778/// - & __real__ x -> x
14779///
14780/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14781/// members.
14782static ValueDecl *getPrimaryDecl(Expr *E) {
14783 switch (E->getStmtClass()) {
14784 case Stmt::DeclRefExprClass:
14785 return cast<DeclRefExpr>(E)->getDecl();
14786 case Stmt::MemberExprClass:
14787 // If this is an arrow operator, the address is an offset from
14788 // the base's value, so the object the base refers to is
14789 // irrelevant.
14790 if (cast<MemberExpr>(E)->isArrow())
14791 return nullptr;
14792 // Otherwise, the expression refers to a part of the base
14793 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14794 case Stmt::ArraySubscriptExprClass: {
14795 // FIXME: This code shouldn't be necessary! We should catch the implicit
14796 // promotion of register arrays earlier.
14797 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14798 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14799 if (ICE->getSubExpr()->getType()->isArrayType())
14800 return getPrimaryDecl(ICE->getSubExpr());
14801 }
14802 return nullptr;
14803 }
14804 case Stmt::UnaryOperatorClass: {
14805 UnaryOperator *UO = cast<UnaryOperator>(E);
14806
14807 switch(UO->getOpcode()) {
14808 case UO_Real:
14809 case UO_Imag:
14810 case UO_Extension:
14811 return getPrimaryDecl(UO->getSubExpr());
14812 default:
14813 return nullptr;
14814 }
14815 }
14816 case Stmt::ParenExprClass:
14817 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14818 case Stmt::ImplicitCastExprClass:
14819 // If the result of an implicit cast is an l-value, we care about
14820 // the sub-expression; otherwise, the result here doesn't matter.
14821 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14822 case Stmt::CXXUuidofExprClass:
14823 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14824 default:
14825 return nullptr;
14826 }
14827}
14828
14829namespace {
14830enum {
14831 AO_Bit_Field = 0,
14832 AO_Vector_Element = 1,
14833 AO_Property_Expansion = 2,
14834 AO_Register_Variable = 3,
14835 AO_Matrix_Element = 4,
14836 AO_No_Error = 5
14837};
14838}
14839/// Diagnose invalid operand for address of operations.
14840///
14841/// \param Type The type of operand which cannot have its address taken.
14842static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14843 Expr *E, unsigned Type) {
14844 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14845}
14846
14847/// CheckAddressOfOperand - The operand of & must be either a function
14848/// designator or an lvalue designating an object. If it is an lvalue, the
14849/// object cannot be declared with storage class register or be a bit field.
14850/// Note: The usual conversions are *not* applied to the operand of the &
14851/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14852/// In C++, the operand might be an overloaded function name, in which case
14853/// we allow the '&' but retain the overloaded-function type.
14854QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14855 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14856 if (PTy->getKind() == BuiltinType::Overload) {
14857 Expr *E = OrigOp.get()->IgnoreParens();
14858 if (!isa<OverloadExpr>(E)) {
14859 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14860 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14861 << OrigOp.get()->getSourceRange();
14862 return QualType();
14863 }
14864
14865 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14866 if (isa<UnresolvedMemberExpr>(Ovl))
14867 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14868 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14869 << OrigOp.get()->getSourceRange();
14870 return QualType();
14871 }
14872
14873 return Context.OverloadTy;
14874 }
14875
14876 if (PTy->getKind() == BuiltinType::UnknownAny)
14877 return Context.UnknownAnyTy;
14878
14879 if (PTy->getKind() == BuiltinType::BoundMember) {
14880 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14881 << OrigOp.get()->getSourceRange();
14882 return QualType();
14883 }
14884
14885 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14886 if (OrigOp.isInvalid()) return QualType();
14887 }
14888
14889 if (OrigOp.get()->isTypeDependent())
14890 return Context.DependentTy;
14891
14892 assert(!OrigOp.get()->hasPlaceholderType());
14893
14894 // Make sure to ignore parentheses in subsequent checks
14895 Expr *op = OrigOp.get()->IgnoreParens();
14896
14897 // In OpenCL captures for blocks called as lambda functions
14898 // are located in the private address space. Blocks used in
14899 // enqueue_kernel can be located in a different address space
14900 // depending on a vendor implementation. Thus preventing
14901 // taking an address of the capture to avoid invalid AS casts.
14902 if (LangOpts.OpenCL) {
14903 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14904 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14905 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14906 return QualType();
14907 }
14908 }
14909
14910 if (getLangOpts().C99) {
14911 // Implement C99-only parts of addressof rules.
14912 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14913 if (uOp->getOpcode() == UO_Deref)
14914 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14915 // (assuming the deref expression is valid).
14916 return uOp->getSubExpr()->getType();
14917 }
14918 // Technically, there should be a check for array subscript
14919 // expressions here, but the result of one is always an lvalue anyway.
14920 }
14921 ValueDecl *dcl = getPrimaryDecl(op);
14922
14923 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14924 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14925 op->getBeginLoc()))
14926 return QualType();
14927
14928 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14929 unsigned AddressOfError = AO_No_Error;
14930
14931 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14932 bool sfinae = (bool)isSFINAEContext();
14933 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14934 : diag::ext_typecheck_addrof_temporary)
14935 << op->getType() << op->getSourceRange();
14936 if (sfinae)
14937 return QualType();
14938 // Materialize the temporary as an lvalue so that we can take its address.
14939 OrigOp = op =
14940 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14941 } else if (isa<ObjCSelectorExpr>(op)) {
14942 return Context.getPointerType(op->getType());
14943 } else if (lval == Expr::LV_MemberFunction) {
14944 // If it's an instance method, make a member pointer.
14945 // The expression must have exactly the form &A::foo.
14946
14947 // If the underlying expression isn't a decl ref, give up.
14948 if (!isa<DeclRefExpr>(op)) {
14949 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14950 << OrigOp.get()->getSourceRange();
14951 return QualType();
14952 }
14953 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14954 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14955
14956 // The id-expression was parenthesized.
14957 if (OrigOp.get() != DRE) {
14958 Diag(OpLoc, diag::err_parens_pointer_member_function)
14959 << OrigOp.get()->getSourceRange();
14960
14961 // The method was named without a qualifier.
14962 } else if (!DRE->getQualifier()) {
14963 if (MD->getParent()->getName().empty())
14964 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14965 << op->getSourceRange();
14966 else {
14967 SmallString<32> Str;
14968 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14969 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14970 << op->getSourceRange()
14971 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14972 }
14973 }
14974
14975 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14976 if (isa<CXXDestructorDecl>(MD))
14977 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14978
14979 QualType MPTy = Context.getMemberPointerType(
14980 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14981 // Under the MS ABI, lock down the inheritance model now.
14982 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14983 (void)isCompleteType(OpLoc, MPTy);
14984 return MPTy;
14985 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14986 // C99 6.5.3.2p1
14987 // The operand must be either an l-value or a function designator
14988 if (!op->getType()->isFunctionType()) {
14989 // Use a special diagnostic for loads from property references.
14990 if (isa<PseudoObjectExpr>(op)) {
14991 AddressOfError = AO_Property_Expansion;
14992 } else {
14993 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14994 << op->getType() << op->getSourceRange();
14995 return QualType();
14996 }
14997 }
14998 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14999 // The operand cannot be a bit-field
15000 AddressOfError = AO_Bit_Field;
15001 } else if (op->getObjectKind() == OK_VectorComponent) {
15002 // The operand cannot be an element of a vector
15003 AddressOfError = AO_Vector_Element;
15004 } else if (op->getObjectKind() == OK_MatrixComponent) {
15005 // The operand cannot be an element of a matrix.
15006 AddressOfError = AO_Matrix_Element;
15007 } else if (dcl) { // C99 6.5.3.2p1
15008 // We have an lvalue with a decl. Make sure the decl is not declared
15009 // with the register storage-class specifier.
15010 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15011 // in C++ it is not error to take address of a register
15012 // variable (c++03 7.1.1P3)
15013 if (vd->getStorageClass() == SC_Register &&
15014 !getLangOpts().CPlusPlus) {
15015 AddressOfError = AO_Register_Variable;
15016 }
15017 } else if (isa<MSPropertyDecl>(dcl)) {
15018 AddressOfError = AO_Property_Expansion;
15019 } else if (isa<FunctionTemplateDecl>(dcl)) {
15020 return Context.OverloadTy;
15021 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15022 // Okay: we can take the address of a field.
15023 // Could be a pointer to member, though, if there is an explicit
15024 // scope qualifier for the class.
15025 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
15026 DeclContext *Ctx = dcl->getDeclContext();
15027 if (Ctx && Ctx->isRecord()) {
15028 if (dcl->getType()->isReferenceType()) {
15029 Diag(OpLoc,
15030 diag::err_cannot_form_pointer_to_member_of_reference_type)
15031 << dcl->getDeclName() << dcl->getType();
15032 return QualType();
15033 }
15034
15035 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15036 Ctx = Ctx->getParent();
15037
15038 QualType MPTy = Context.getMemberPointerType(
15039 op->getType(),
15040 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
15041 // Under the MS ABI, lock down the inheritance model now.
15042 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15043 (void)isCompleteType(OpLoc, MPTy);
15044 return MPTy;
15045 }
15046 }
15047 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
15048 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
15049 llvm_unreachable("Unknown/unexpected decl type");
15050 }
15051
15052 if (AddressOfError != AO_No_Error) {
15053 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15054 return QualType();
15055 }
15056
15057 if (lval == Expr::LV_IncompleteVoidType) {
15058 // Taking the address of a void variable is technically illegal, but we
15059 // allow it in cases which are otherwise valid.
15060 // Example: "extern void x; void* y = &x;".
15061 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15062 }
15063
15064 // If the operand has type "type", the result has type "pointer to type".
15065 if (op->getType()->isObjCObjectType())
15066 return Context.getObjCObjectPointerType(op->getType());
15067
15068 // Cannot take the address of WebAssembly references or tables.
15069 if (Context.getTargetInfo().getTriple().isWasm()) {
15070 QualType OpTy = op->getType();
15071 if (OpTy.isWebAssemblyReferenceType()) {
15072 Diag(OpLoc, diag::err_wasm_ca_reference)
15073 << 1 << OrigOp.get()->getSourceRange();
15074 return QualType();
15075 }
15076 if (OpTy->isWebAssemblyTableType()) {
15077 Diag(OpLoc, diag::err_wasm_table_pr)
15078 << 1 << OrigOp.get()->getSourceRange();
15079 return QualType();
15080 }
15081 }
15082
15083 CheckAddressOfPackedMember(op);
15084
15085 return Context.getPointerType(op->getType());
15086}
15087
15088static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15089 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15090 if (!DRE)
15091 return;
15092 const Decl *D = DRE->getDecl();
15093 if (!D)
15094 return;
15095 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15096 if (!Param)
15097 return;
15098 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15099 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15100 return;
15101 if (FunctionScopeInfo *FD = S.getCurFunction())
15102 FD->ModifiedNonNullParams.insert(Param);
15103}
15104
15105/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15106static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15107 SourceLocation OpLoc,
15108 bool IsAfterAmp = false) {
15109 if (Op->isTypeDependent())
15110 return S.Context.DependentTy;
15111
15112 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15113 if (ConvResult.isInvalid())
15114 return QualType();
15115 Op = ConvResult.get();
15116 QualType OpTy = Op->getType();
15117 QualType Result;
15118
15119 if (isa<CXXReinterpretCastExpr>(Op)) {
15120 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15121 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15122 Op->getSourceRange());
15123 }
15124
15125 if (const PointerType *PT = OpTy->getAs<PointerType>())
15126 {
15127 Result = PT->getPointeeType();
15128 }
15129 else if (const ObjCObjectPointerType *OPT =
15130 OpTy->getAs<ObjCObjectPointerType>())
15131 Result = OPT->getPointeeType();
15132 else {
15133 ExprResult PR = S.CheckPlaceholderExpr(Op);
15134 if (PR.isInvalid()) return QualType();
15135 if (PR.get() != Op)
15136 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15137 }
15138
15139 if (Result.isNull()) {
15140 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15141 << OpTy << Op->getSourceRange();
15142 return QualType();
15143 }
15144
15145 if (Result->isVoidType()) {
15146 // C++ [expr.unary.op]p1:
15147 // [...] the expression to which [the unary * operator] is applied shall
15148 // be a pointer to an object type, or a pointer to a function type
15149 LangOptions LO = S.getLangOpts();
15150 if (LO.CPlusPlus)
15151 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15152 << OpTy << Op->getSourceRange();
15153 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15154 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15155 << OpTy << Op->getSourceRange();
15156 }
15157
15158 // Dereferences are usually l-values...
15159 VK = VK_LValue;
15160
15161 // ...except that certain expressions are never l-values in C.
15162 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15163 VK = VK_PRValue;
15164
15165 return Result;
15166}
15167
15168BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15169 BinaryOperatorKind Opc;
15170 switch (Kind) {
15171 default: llvm_unreachable("Unknown binop!");
15172 case tok::periodstar: Opc = BO_PtrMemD; break;
15173 case tok::arrowstar: Opc = BO_PtrMemI; break;
15174 case tok::star: Opc = BO_Mul; break;
15175 case tok::slash: Opc = BO_Div; break;
15176 case tok::percent: Opc = BO_Rem; break;
15177 case tok::plus: Opc = BO_Add; break;
15178 case tok::minus: Opc = BO_Sub; break;
15179 case tok::lessless: Opc = BO_Shl; break;
15180 case tok::greatergreater: Opc = BO_Shr; break;
15181 case tok::lessequal: Opc = BO_LE; break;
15182 case tok::less: Opc = BO_LT; break;
15183 case tok::greaterequal: Opc = BO_GE; break;
15184 case tok::greater: Opc = BO_GT; break;
15185 case tok::exclaimequal: Opc = BO_NE; break;
15186 case tok::equalequal: Opc = BO_EQ; break;
15187 case tok::spaceship: Opc = BO_Cmp; break;
15188 case tok::amp: Opc = BO_And; break;
15189 case tok::caret: Opc = BO_Xor; break;
15190 case tok::pipe: Opc = BO_Or; break;
15191 case tok::ampamp: Opc = BO_LAnd; break;
15192 case tok::pipepipe: Opc = BO_LOr; break;
15193 case tok::equal: Opc = BO_Assign; break;
15194 case tok::starequal: Opc = BO_MulAssign; break;
15195 case tok::slashequal: Opc = BO_DivAssign; break;
15196 case tok::percentequal: Opc = BO_RemAssign; break;
15197 case tok::plusequal: Opc = BO_AddAssign; break;
15198 case tok::minusequal: Opc = BO_SubAssign; break;
15199 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15200 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15201 case tok::ampequal: Opc = BO_AndAssign; break;
15202 case tok::caretequal: Opc = BO_XorAssign; break;
15203 case tok::pipeequal: Opc = BO_OrAssign; break;
15204 case tok::comma: Opc = BO_Comma; break;
15205 }
15206 return Opc;
15207}
15208
15209static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15210 tok::TokenKind Kind) {
15211 UnaryOperatorKind Opc;
15212 switch (Kind) {
15213 default: llvm_unreachable("Unknown unary op!");
15214 case tok::plusplus: Opc = UO_PreInc; break;
15215 case tok::minusminus: Opc = UO_PreDec; break;
15216 case tok::amp: Opc = UO_AddrOf; break;
15217 case tok::star: Opc = UO_Deref; break;
15218 case tok::plus: Opc = UO_Plus; break;
15219 case tok::minus: Opc = UO_Minus; break;
15220 case tok::tilde: Opc = UO_Not; break;
15221 case tok::exclaim: Opc = UO_LNot; break;
15222 case tok::kw___real: Opc = UO_Real; break;
15223 case tok::kw___imag: Opc = UO_Imag; break;
15224 case tok::kw___extension__: Opc = UO_Extension; break;
15225 }
15226 return Opc;
15227}
15228
15229const FieldDecl *
15230Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15231 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15232 // common for setters.
15233 // struct A {
15234 // int X;
15235 // -void setX(int X) { X = X; }
15236 // +void setX(int X) { this->X = X; }
15237 // };
15238
15239 // Only consider parameters for self assignment fixes.
15240 if (!isa<ParmVarDecl>(SelfAssigned))
15241 return nullptr;
15242 const auto *Method =
15243 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15244 if (!Method)
15245 return nullptr;
15246
15247 const CXXRecordDecl *Parent = Method->getParent();
15248 // In theory this is fixable if the lambda explicitly captures this, but
15249 // that's added complexity that's rarely going to be used.
15250 if (Parent->isLambda())
15251 return nullptr;
15252
15253 // FIXME: Use an actual Lookup operation instead of just traversing fields
15254 // in order to get base class fields.
15255 auto Field =
15256 llvm::find_if(Parent->fields(),
15257 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15258 return F->getDeclName() == Name;
15259 });
15260 return (Field != Parent->field_end()) ? *Field : nullptr;
15261}
15262
15263/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15264/// This warning suppressed in the event of macro expansions.
15265static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15266 SourceLocation OpLoc, bool IsBuiltin) {
15267 if (S.inTemplateInstantiation())
15268 return;
15269 if (S.isUnevaluatedContext())
15270 return;
15271 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15272 return;
15273 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15274 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15275 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15276 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15277 if (!LHSDeclRef || !RHSDeclRef ||
15278 LHSDeclRef->getLocation().isMacroID() ||
15279 RHSDeclRef->getLocation().isMacroID())
15280 return;
15281 const ValueDecl *LHSDecl =
15282 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15283 const ValueDecl *RHSDecl =
15284 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15285 if (LHSDecl != RHSDecl)
15286 return;
15287 if (LHSDecl->getType().isVolatileQualified())
15288 return;
15289 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15290 if (RefTy->getPointeeType().isVolatileQualified())
15291 return;
15292
15293 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15294 : diag::warn_self_assignment_overloaded)
15295 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15296 << RHSExpr->getSourceRange();
15297 if (const FieldDecl *SelfAssignField =
15298 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
15299 Diag << 1 << SelfAssignField
15300 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15301 else
15302 Diag << 0;
15303}
15304
15305/// Check if a bitwise-& is performed on an Objective-C pointer. This
15306/// is usually indicative of introspection within the Objective-C pointer.
15307static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15308 SourceLocation OpLoc) {
15309 if (!S.getLangOpts().ObjC)
15310 return;
15311
15312 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15313 const Expr *LHS = L.get();
15314 const Expr *RHS = R.get();
15315
15316 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15317 ObjCPointerExpr = LHS;
15318 OtherExpr = RHS;
15319 }
15320 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15321 ObjCPointerExpr = RHS;
15322 OtherExpr = LHS;
15323 }
15324
15325 // This warning is deliberately made very specific to reduce false
15326 // positives with logic that uses '&' for hashing. This logic mainly
15327 // looks for code trying to introspect into tagged pointers, which
15328 // code should generally never do.
15329 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15330 unsigned Diag = diag::warn_objc_pointer_masking;
15331 // Determine if we are introspecting the result of performSelectorXXX.
15332 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15333 // Special case messages to -performSelector and friends, which
15334 // can return non-pointer values boxed in a pointer value.
15335 // Some clients may wish to silence warnings in this subcase.
15336 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15337 Selector S = ME->getSelector();
15338 StringRef SelArg0 = S.getNameForSlot(0);
15339 if (SelArg0.startswith("performSelector"))
15340 Diag = diag::warn_objc_pointer_masking_performSelector;
15341 }
15342
15343 S.Diag(OpLoc, Diag)
15344 << ObjCPointerExpr->getSourceRange();
15345 }
15346}
15347
15348static NamedDecl *getDeclFromExpr(Expr *E) {
15349 if (!E)
15350 return nullptr;
15351 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15352 return DRE->getDecl();
15353 if (auto *ME = dyn_cast<MemberExpr>(E))
15354 return ME->getMemberDecl();
15355 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15356 return IRE->getDecl();
15357 return nullptr;
15358}
15359
15360// This helper function promotes a binary operator's operands (which are of a
15361// half vector type) to a vector of floats and then truncates the result to
15362// a vector of either half or short.
15363static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15364 BinaryOperatorKind Opc, QualType ResultTy,
15365 ExprValueKind VK, ExprObjectKind OK,
15366 bool IsCompAssign, SourceLocation OpLoc,
15367 FPOptionsOverride FPFeatures) {
15368 auto &Context = S.getASTContext();
15369 assert((isVector(ResultTy, Context.HalfTy) ||
15370 isVector(ResultTy, Context.ShortTy)) &&
15371 "Result must be a vector of half or short");
15372 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15373 isVector(RHS.get()->getType(), Context.HalfTy) &&
15374 "both operands expected to be a half vector");
15375
15376 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15377 QualType BinOpResTy = RHS.get()->getType();
15378
15379 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15380 // change BinOpResTy to a vector of ints.
15381 if (isVector(ResultTy, Context.ShortTy))
15382 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15383
15384 if (IsCompAssign)
15385 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15386 ResultTy, VK, OK, OpLoc, FPFeatures,
15387 BinOpResTy, BinOpResTy);
15388
15389 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15390 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15391 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15392 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15393}
15394
15395static std::pair<ExprResult, ExprResult>
15396CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15397 Expr *RHSExpr) {
15398 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15399 if (!S.Context.isDependenceAllowed()) {
15400 // C cannot handle TypoExpr nodes on either side of a binop because it
15401 // doesn't handle dependent types properly, so make sure any TypoExprs have
15402 // been dealt with before checking the operands.
15403 LHS = S.CorrectDelayedTyposInExpr(LHS);
15404 RHS = S.CorrectDelayedTyposInExpr(
15405 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15406 [Opc, LHS](Expr *E) {
15407 if (Opc != BO_Assign)
15408 return ExprResult(E);
15409 // Avoid correcting the RHS to the same Expr as the LHS.
15410 Decl *D = getDeclFromExpr(E);
15411 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15412 });
15413 }
15414 return std::make_pair(LHS, RHS);
15415}
15416
15417/// Returns true if conversion between vectors of halfs and vectors of floats
15418/// is needed.
15419static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15420 Expr *E0, Expr *E1 = nullptr) {
15421 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15422 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15423 return false;
15424
15425 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15426 QualType Ty = E->IgnoreImplicit()->getType();
15427
15428 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15429 // to vectors of floats. Although the element type of the vectors is __fp16,
15430 // the vectors shouldn't be treated as storage-only types. See the
15431 // discussion here: https://reviews.llvm.org/rG825235c140e7
15432 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15433 if (VT->getVectorKind() == VectorType::NeonVector)
15434 return false;
15435 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15436 }
15437 return false;
15438 };
15439
15440 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15441}
15442
15443/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15444/// operator @p Opc at location @c TokLoc. This routine only supports
15445/// built-in operations; ActOnBinOp handles overloaded operators.
15446ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15447 BinaryOperatorKind Opc,
15448 Expr *LHSExpr, Expr *RHSExpr) {
15449 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15450 // The syntax only allows initializer lists on the RHS of assignment,
15451 // so we don't need to worry about accepting invalid code for
15452 // non-assignment operators.
15453 // C++11 5.17p9:
15454 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15455 // of x = {} is x = T().
15456 InitializationKind Kind = InitializationKind::CreateDirectList(
15457 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15458 InitializedEntity Entity =
15459 InitializedEntity::InitializeTemporary(LHSExpr->getType());
15460 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15461 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15462 if (Init.isInvalid())
15463 return Init;
15464 RHSExpr = Init.get();
15465 }
15466
15467 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15468 QualType ResultTy; // Result type of the binary operator.
15469 // The following two variables are used for compound assignment operators
15470 QualType CompLHSTy; // Type of LHS after promotions for computation
15471 QualType CompResultTy; // Type of computation result
15472 ExprValueKind VK = VK_PRValue;
15473 ExprObjectKind OK = OK_Ordinary;
15474 bool ConvertHalfVec = false;
15475
15476 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15477 if (!LHS.isUsable() || !RHS.isUsable())
15478 return ExprError();
15479
15480 if (getLangOpts().OpenCL) {
15481 QualType LHSTy = LHSExpr->getType();
15482 QualType RHSTy = RHSExpr->getType();
15483 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15484 // the ATOMIC_VAR_INIT macro.
15485 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15486 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15487 if (BO_Assign == Opc)
15488 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15489 else
15490 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15491 return ExprError();
15492 }
15493
15494 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15495 // only with a builtin functions and therefore should be disallowed here.
15496 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15497 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15498 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15499 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15500 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15501 return ExprError();
15502 }
15503 }
15504
15505 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15506 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15507
15508 switch (Opc) {
15509 case BO_Assign:
15510 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15511 if (getLangOpts().CPlusPlus &&
15512 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15513 VK = LHS.get()->getValueKind();
15514 OK = LHS.get()->getObjectKind();
15515 }
15516 if (!ResultTy.isNull()) {
15517 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15518 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15519
15520 // Avoid copying a block to the heap if the block is assigned to a local
15521 // auto variable that is declared in the same scope as the block. This
15522 // optimization is unsafe if the local variable is declared in an outer
15523 // scope. For example:
15524 //
15525 // BlockTy b;
15526 // {
15527 // b = ^{...};
15528 // }
15529 // // It is unsafe to invoke the block here if it wasn't copied to the
15530 // // heap.
15531 // b();
15532
15533 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15534 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15535 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15536 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15537 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15538
15539 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15540 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15541 NTCUC_Assignment, NTCUK_Copy);
15542 }
15543 RecordModifiableNonNullParam(*this, LHS.get());
15544 break;
15545 case BO_PtrMemD:
15546 case BO_PtrMemI:
15547 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15548 Opc == BO_PtrMemI);
15549 break;
15550 case BO_Mul:
15551 case BO_Div:
15552 ConvertHalfVec = true;
15553 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15554 Opc == BO_Div);
15555 break;
15556 case BO_Rem:
15557 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15558 break;
15559 case BO_Add:
15560 ConvertHalfVec = true;
15561 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15562 break;
15563 case BO_Sub:
15564 ConvertHalfVec = true;
15565 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15566 break;
15567 case BO_Shl:
15568 case BO_Shr:
15569 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15570 break;
15571 case BO_LE:
15572 case BO_LT:
15573 case BO_GE:
15574 case BO_GT:
15575 ConvertHalfVec = true;
15576 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15577 break;
15578 case BO_EQ:
15579 case BO_NE:
15580 ConvertHalfVec = true;
15581 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15582 break;
15583 case BO_Cmp:
15584 ConvertHalfVec = true;
15585 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15586 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15587 break;
15588 case BO_And:
15589 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15590 [[fallthrough]];
15591 case BO_Xor:
15592 case BO_Or:
15593 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15594 break;
15595 case BO_LAnd:
15596 case BO_LOr:
15597 ConvertHalfVec = true;
15598 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15599 break;
15600 case BO_MulAssign:
15601 case BO_DivAssign:
15602 ConvertHalfVec = true;
15603 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15604 Opc == BO_DivAssign);
15605 CompLHSTy = CompResultTy;
15606 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15607 ResultTy =
15608 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15609 break;
15610 case BO_RemAssign:
15611 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15612 CompLHSTy = CompResultTy;
15613 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15614 ResultTy =
15615 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15616 break;
15617 case BO_AddAssign:
15618 ConvertHalfVec = true;
15619 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15620 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15621 ResultTy =
15622 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15623 break;
15624 case BO_SubAssign:
15625 ConvertHalfVec = true;
15626 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15627 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15628 ResultTy =
15629 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15630 break;
15631 case BO_ShlAssign:
15632 case BO_ShrAssign:
15633 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15634 CompLHSTy = CompResultTy;
15635 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15636 ResultTy =
15637 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15638 break;
15639 case BO_AndAssign:
15640 case BO_OrAssign: // fallthrough
15641 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15642 [[fallthrough]];
15643 case BO_XorAssign:
15644 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15645 CompLHSTy = CompResultTy;
15646 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15647 ResultTy =
15648 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15649 break;
15650 case BO_Comma:
15651 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15652 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15653 VK = RHS.get()->getValueKind();
15654 OK = RHS.get()->getObjectKind();
15655 }
15656 break;
15657 }
15658 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15659 return ExprError();
15660
15661 // Some of the binary operations require promoting operands of half vector to
15662 // float vectors and truncating the result back to half vector. For now, we do
15663 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15664 // arm64).
15665 assert(
15666 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15667 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15668 "both sides are half vectors or neither sides are");
15669 ConvertHalfVec =
15670 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15671
15672 // Check for array bounds violations for both sides of the BinaryOperator
15673 CheckArrayAccess(LHS.get());
15674 CheckArrayAccess(RHS.get());
15675
15676 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15677 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15678 &Context.Idents.get("object_setClass"),
15679 SourceLocation(), LookupOrdinaryName);
15680 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15681 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15682 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15683 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15684 "object_setClass(")
15685 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15686 ",")
15687 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15688 }
15689 else
15690 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15691 }
15692 else if (const ObjCIvarRefExpr *OIRE =
15693 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15694 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15695
15696 // Opc is not a compound assignment if CompResultTy is null.
15697 if (CompResultTy.isNull()) {
15698 if (ConvertHalfVec)
15699 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15700 OpLoc, CurFPFeatureOverrides());
15701 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15702 VK, OK, OpLoc, CurFPFeatureOverrides());
15703 }
15704
15705 // Handle compound assignments.
15706 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15707 OK_ObjCProperty) {
15708 VK = VK_LValue;
15709 OK = LHS.get()->getObjectKind();
15710 }
15711
15712 // The LHS is not converted to the result type for fixed-point compound
15713 // assignment as the common type is computed on demand. Reset the CompLHSTy
15714 // to the LHS type we would have gotten after unary conversions.
15715 if (CompResultTy->isFixedPointType())
15716 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15717
15718 if (ConvertHalfVec)
15719 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15720 OpLoc, CurFPFeatureOverrides());
15721
15722 return CompoundAssignOperator::Create(
15723 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15724 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15725}
15726
15727/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15728/// operators are mixed in a way that suggests that the programmer forgot that
15729/// comparison operators have higher precedence. The most typical example of
15730/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15731static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15732 SourceLocation OpLoc, Expr *LHSExpr,
15733 Expr *RHSExpr) {
15734 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15735 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15736
15737 // Check that one of the sides is a comparison operator and the other isn't.
15738 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15739 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15740 if (isLeftComp == isRightComp)
15741 return;
15742
15743 // Bitwise operations are sometimes used as eager logical ops.
15744 // Don't diagnose this.
15745 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15746 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15747 if (isLeftBitwise || isRightBitwise)
15748 return;
15749
15750 SourceRange DiagRange = isLeftComp
15751 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15752 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15753 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15754 SourceRange ParensRange =
15755 isLeftComp
15756 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15757 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15758
15759 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15760 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15761 SuggestParentheses(Self, OpLoc,
15762 Self.PDiag(diag::note_precedence_silence) << OpStr,
15763 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15764 SuggestParentheses(Self, OpLoc,
15765 Self.PDiag(diag::note_precedence_bitwise_first)
15766 << BinaryOperator::getOpcodeStr(Opc),
15767 ParensRange);
15768}
15769
15770/// It accepts a '&&' expr that is inside a '||' one.
15771/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15772/// in parentheses.
15773static void
15774EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15775 BinaryOperator *Bop) {
15776 assert(Bop->getOpcode() == BO_LAnd);
15777 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15778 << Bop->getSourceRange() << OpLoc;
15779 SuggestParentheses(Self, Bop->getOperatorLoc(),
15780 Self.PDiag(diag::note_precedence_silence)
15781 << Bop->getOpcodeStr(),
15782 Bop->getSourceRange());
15783}
15784
15785/// Look for '&&' in the left hand of a '||' expr.
15786static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15787 Expr *LHSExpr, Expr *RHSExpr) {
15788 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15789 if (Bop->getOpcode() == BO_LAnd) {
15790 // If it's "string_literal && a || b" don't warn since the precedence
15791 // doesn't matter.
15792 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15793 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15794 } else if (Bop->getOpcode() == BO_LOr) {
15795 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15796 // If it's "a || b && string_literal || c" we didn't warn earlier for
15797 // "a || b && string_literal", but warn now.
15798 if (RBop->getOpcode() == BO_LAnd &&
15799 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15800 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15801 }
15802 }
15803 }
15804}
15805
15806/// Look for '&&' in the right hand of a '||' expr.
15807static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15808 Expr *LHSExpr, Expr *RHSExpr) {
15809 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15810 if (Bop->getOpcode() == BO_LAnd) {
15811 // If it's "a || b && string_literal" don't warn since the precedence
15812 // doesn't matter.
15813 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15814 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15815 }
15816 }
15817}
15818
15819/// Look for bitwise op in the left or right hand of a bitwise op with
15820/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15821/// the '&' expression in parentheses.
15822static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15823 SourceLocation OpLoc, Expr *SubExpr) {
15824 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15825 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15826 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15827 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15828 << Bop->getSourceRange() << OpLoc;
15829 SuggestParentheses(S, Bop->getOperatorLoc(),
15830 S.PDiag(diag::note_precedence_silence)
15831 << Bop->getOpcodeStr(),
15832 Bop->getSourceRange());
15833 }
15834 }
15835}
15836
15837static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15838 Expr *SubExpr, StringRef Shift) {
15839 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15840 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15841 StringRef Op = Bop->getOpcodeStr();
15842 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15843 << Bop->getSourceRange() << OpLoc << Shift << Op;
15844 SuggestParentheses(S, Bop->getOperatorLoc(),
15845 S.PDiag(diag::note_precedence_silence) << Op,
15846 Bop->getSourceRange());
15847 }
15848 }
15849}
15850
15851static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15852 Expr *LHSExpr, Expr *RHSExpr) {
15853 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15854 if (!OCE)
15855 return;
15856
15857 FunctionDecl *FD = OCE->getDirectCallee();
15858 if (!FD || !FD->isOverloadedOperator())
15859 return;
15860
15861 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15862 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15863 return;
15864
15865 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15866 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15867 << (Kind == OO_LessLess);
15868 SuggestParentheses(S, OCE->getOperatorLoc(),
15869 S.PDiag(diag::note_precedence_silence)
15870 << (Kind == OO_LessLess ? "<<" : ">>"),
15871 OCE->getSourceRange());
15872 SuggestParentheses(
15873 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15874 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15875}
15876
15877/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15878/// precedence.
15879static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15880 SourceLocation OpLoc, Expr *LHSExpr,
15881 Expr *RHSExpr){
15882 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15883 if (BinaryOperator::isBitwiseOp(Opc))
15884 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15885
15886 // Diagnose "arg1 & arg2 | arg3"
15887 if ((Opc == BO_Or || Opc == BO_Xor) &&
15888 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15889 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15890 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15891 }
15892
15893 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15894 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15895 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15896 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15897 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15898 }
15899
15900 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15901 || Opc == BO_Shr) {
15902 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15903 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15904 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15905 }
15906
15907 // Warn on overloaded shift operators and comparisons, such as:
15908 // cout << 5 == 4;
15909 if (BinaryOperator::isComparisonOp(Opc))
15910 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15911}
15912
15913// Binary Operators. 'Tok' is the token for the operator.
15914ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15915 tok::TokenKind Kind,
15916 Expr *LHSExpr, Expr *RHSExpr) {
15917 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15918 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15919 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15920
15921 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15922 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15923
15924 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15925}
15926
15927void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15928 UnresolvedSetImpl &Functions) {
15929 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15930 if (OverOp != OO_None && OverOp != OO_Equal)
15931 LookupOverloadedOperatorName(OverOp, S, Functions);
15932
15933 // In C++20 onwards, we may have a second operator to look up.
15934 if (getLangOpts().CPlusPlus20) {
15935 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15936 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15937 }
15938}
15939
15940/// Build an overloaded binary operator expression in the given scope.
15941static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15942 BinaryOperatorKind Opc,
15943 Expr *LHS, Expr *RHS) {
15944 switch (Opc) {
15945 case BO_Assign:
15946 // In the non-overloaded case, we warn about self-assignment (x = x) for
15947 // both simple assignment and certain compound assignments where algebra
15948 // tells us the operation yields a constant result. When the operator is
15949 // overloaded, we can't do the latter because we don't want to assume that
15950 // those algebraic identities still apply; for example, a path-building
15951 // library might use operator/= to append paths. But it's still reasonable
15952 // to assume that simple assignment is just moving/copying values around
15953 // and so self-assignment is likely a bug.
15954 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15955 [[fallthrough]];
15956 case BO_DivAssign:
15957 case BO_RemAssign:
15958 case BO_SubAssign:
15959 case BO_AndAssign:
15960 case BO_OrAssign:
15961 case BO_XorAssign:
15962 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15963 break;
15964 default:
15965 break;
15966 }
15967
15968 // Find all of the overloaded operators visible from this point.
15969 UnresolvedSet<16> Functions;
15970 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15971
15972 // Build the (potentially-overloaded, potentially-dependent)
15973 // binary operation.
15974 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15975}
15976
15977ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15978 BinaryOperatorKind Opc,
15979 Expr *LHSExpr, Expr *RHSExpr) {
15980 ExprResult LHS, RHS;
15981 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15982 if (!LHS.isUsable() || !RHS.isUsable())
15983 return ExprError();
15984 LHSExpr = LHS.get();
15985 RHSExpr = RHS.get();
15986
15987 // We want to end up calling one of checkPseudoObjectAssignment
15988 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15989 // both expressions are overloadable or either is type-dependent),
15990 // or CreateBuiltinBinOp (in any other case). We also want to get
15991 // any placeholder types out of the way.
15992
15993 // Handle pseudo-objects in the LHS.
15994 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15995 // Assignments with a pseudo-object l-value need special analysis.
15996 if (pty->getKind() == BuiltinType::PseudoObject &&
15997 BinaryOperator::isAssignmentOp(Opc))
15998 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15999
16000 // Don't resolve overloads if the other type is overloadable.
16001 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16002 // We can't actually test that if we still have a placeholder,
16003 // though. Fortunately, none of the exceptions we see in that
16004 // code below are valid when the LHS is an overload set. Note
16005 // that an overload set can be dependently-typed, but it never
16006 // instantiates to having an overloadable type.
16007 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16008 if (resolvedRHS.isInvalid()) return ExprError();
16009 RHSExpr = resolvedRHS.get();
16010
16011 if (RHSExpr->isTypeDependent() ||
16012 RHSExpr->getType()->isOverloadableType())
16013 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16014 }
16015
16016 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16017 // template, diagnose the missing 'template' keyword instead of diagnosing
16018 // an invalid use of a bound member function.
16019 //
16020 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16021 // to C++1z [over.over]/1.4, but we already checked for that case above.
16022 if (Opc == BO_LT && inTemplateInstantiation() &&
16023 (pty->getKind() == BuiltinType::BoundMember ||
16024 pty->getKind() == BuiltinType::Overload)) {
16025 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16026 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16027 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16028 return isa<FunctionTemplateDecl>(ND);
16029 })) {
16030 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16031 : OE->getNameLoc(),
16032 diag::err_template_kw_missing)
16033 << OE->getName().getAsString() << "";
16034 return ExprError();
16035 }
16036 }
16037
16038 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16039 if (LHS.isInvalid()) return ExprError();
16040 LHSExpr = LHS.get();
16041 }
16042
16043 // Handle pseudo-objects in the RHS.
16044 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16045 // An overload in the RHS can potentially be resolved by the type
16046 // being assigned to.
16047 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16048 if (getLangOpts().CPlusPlus &&
16049 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16050 LHSExpr->getType()->isOverloadableType()))
16051 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16052
16053 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16054 }
16055
16056 // Don't resolve overloads if the other type is overloadable.
16057 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16058 LHSExpr->getType()->isOverloadableType())
16059 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16060
16061 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16062 if (!resolvedRHS.isUsable()) return ExprError();
16063 RHSExpr = resolvedRHS.get();
16064 }
16065
16066 if (getLangOpts().CPlusPlus) {
16067 // If either expression is type-dependent, always build an
16068 // overloaded op.
16069 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
16070 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16071
16072 // Otherwise, build an overloaded op if either expression has an
16073 // overloadable type.
16074 if (LHSExpr->getType()->isOverloadableType() ||
16075 RHSExpr->getType()->isOverloadableType())
16076 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16077 }
16078
16079 if (getLangOpts().RecoveryAST &&
16080 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16081 assert(!getLangOpts().CPlusPlus);
16082 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16083 "Should only occur in error-recovery path.");
16084 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16085 // C [6.15.16] p3:
16086 // An assignment expression has the value of the left operand after the
16087 // assignment, but is not an lvalue.
16088 return CompoundAssignOperator::Create(
16089 Context, LHSExpr, RHSExpr, Opc,
16090 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
16091 OpLoc, CurFPFeatureOverrides());
16092 QualType ResultType;
16093 switch (Opc) {
16094 case BO_Assign:
16095 ResultType = LHSExpr->getType().getUnqualifiedType();
16096 break;
16097 case BO_LT:
16098 case BO_GT:
16099 case BO_LE:
16100 case BO_GE:
16101 case BO_EQ:
16102 case BO_NE:
16103 case BO_LAnd:
16104 case BO_LOr:
16105 // These operators have a fixed result type regardless of operands.
16106 ResultType = Context.IntTy;
16107 break;
16108 case BO_Comma:
16109 ResultType = RHSExpr->getType();
16110 break;
16111 default:
16112 ResultType = Context.DependentTy;
16113 break;
16114 }
16115 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16116 VK_PRValue, OK_Ordinary, OpLoc,
16117 CurFPFeatureOverrides());
16118 }
16119
16120 // Build a built-in binary operation.
16121 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16122}
16123
16124static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16125 if (T.isNull() || T->isDependentType())
16126 return false;
16127
16128 if (!Ctx.isPromotableIntegerType(T))
16129 return true;
16130
16131 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16132}
16133
16134ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16135 UnaryOperatorKind Opc, Expr *InputExpr,
16136 bool IsAfterAmp) {
16137 ExprResult Input = InputExpr;
16138 ExprValueKind VK = VK_PRValue;
16139 ExprObjectKind OK = OK_Ordinary;
16140 QualType resultType;
16141 bool CanOverflow = false;
16142
16143 bool ConvertHalfVec = false;
16144 if (getLangOpts().OpenCL) {
16145 QualType Ty = InputExpr->getType();
16146 // The only legal unary operation for atomics is '&'.
16147 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16148 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16149 // only with a builtin functions and therefore should be disallowed here.
16150 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16151 || Ty->isBlockPointerType())) {
16152 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16153 << InputExpr->getType()
16154 << Input.get()->getSourceRange());
16155 }
16156 }
16157
16158 if (getLangOpts().HLSL && OpLoc.isValid()) {
16159 if (Opc == UO_AddrOf)
16160 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16161 if (Opc == UO_Deref)
16162 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16163 }
16164
16165 switch (Opc) {
16166 case UO_PreInc:
16167 case UO_PreDec:
16168 case UO_PostInc:
16169 case UO_PostDec:
16170 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
16171 OpLoc,
16172 Opc == UO_PreInc ||
16173 Opc == UO_PostInc,
16174 Opc == UO_PreInc ||
16175 Opc == UO_PreDec);
16176 CanOverflow = isOverflowingIntegerType(Context, resultType);
16177 break;
16178 case UO_AddrOf:
16179 resultType = CheckAddressOfOperand(Input, OpLoc);
16180 CheckAddressOfNoDeref(InputExpr);
16181 RecordModifiableNonNullParam(*this, InputExpr);
16182 break;
16183 case UO_Deref: {
16184 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16185 if (Input.isInvalid()) return ExprError();
16186 resultType =
16187 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16188 break;
16189 }
16190 case UO_Plus:
16191 case UO_Minus:
16192 CanOverflow = Opc == UO_Minus &&
16193 isOverflowingIntegerType(Context, Input.get()->getType());
16194 Input = UsualUnaryConversions(Input.get());
16195 if (Input.isInvalid()) return ExprError();
16196 // Unary plus and minus require promoting an operand of half vector to a
16197 // float vector and truncating the result back to a half vector. For now, we
16198 // do this only when HalfArgsAndReturns is set (that is, when the target is
16199 // arm or arm64).
16200 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16201
16202 // If the operand is a half vector, promote it to a float vector.
16203 if (ConvertHalfVec)
16204 Input = convertVector(Input.get(), Context.FloatTy, *this);
16205 resultType = Input.get()->getType();
16206 if (resultType->isDependentType())
16207 break;
16208 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16209 break;
16210 else if (resultType->isVectorType() &&
16211 // The z vector extensions don't allow + or - with bool vectors.
16212 (!Context.getLangOpts().ZVector ||
16213 resultType->castAs<VectorType>()->getVectorKind() !=
16214 VectorType::AltiVecBool))
16215 break;
16216 else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and -
16217 break;
16218 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16219 Opc == UO_Plus &&
16220 resultType->isPointerType())
16221 break;
16222
16223 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16224 << resultType << Input.get()->getSourceRange());
16225
16226 case UO_Not: // bitwise complement
16227 Input = UsualUnaryConversions(Input.get());
16228 if (Input.isInvalid())
16229 return ExprError();
16230 resultType = Input.get()->getType();
16231 if (resultType->isDependentType())
16232 break;
16233 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16234 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16235 // C99 does not support '~' for complex conjugation.
16236 Diag(OpLoc, diag::ext_integer_complement_complex)
16237 << resultType << Input.get()->getSourceRange();
16238 else if (resultType->hasIntegerRepresentation())
16239 break;
16240 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16241 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16242 // on vector float types.
16243 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16244 if (!T->isIntegerType())
16245 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16246 << resultType << Input.get()->getSourceRange());
16247 } else {
16248 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16249 << resultType << Input.get()->getSourceRange());
16250 }
16251 break;
16252
16253 case UO_LNot: // logical negation
16254 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16255 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16256 if (Input.isInvalid()) return ExprError();
16257 resultType = Input.get()->getType();
16258
16259 // Though we still have to promote half FP to float...
16260 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16261 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
16262 resultType = Context.FloatTy;
16263 }
16264
16265 // WebAsembly tables can't be used in unary expressions.
16266 if (resultType->isPointerType() &&
16267 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16268 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16269 << resultType << Input.get()->getSourceRange());
16270 }
16271
16272 if (resultType->isDependentType())
16273 break;
16274 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16275 // C99 6.5.3.3p1: ok, fallthrough;
16276 if (Context.getLangOpts().CPlusPlus) {
16277 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16278 // operand contextually converted to bool.
16279 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16280 ScalarTypeToBooleanCastKind(resultType));
16281 } else if (Context.getLangOpts().OpenCL &&
16282 Context.getLangOpts().OpenCLVersion < 120) {
16283 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16284 // operate on scalar float types.
16285 if (!resultType->isIntegerType() && !resultType->isPointerType())
16286 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16287 << resultType << Input.get()->getSourceRange());
16288 }
16289 } else if (resultType->isExtVectorType()) {
16290 if (Context.getLangOpts().OpenCL &&
16291 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16292 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16293 // operate on vector float types.
16294 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16295 if (!T->isIntegerType())
16296 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16297 << resultType << Input.get()->getSourceRange());
16298 }
16299 // Vector logical not returns the signed variant of the operand type.
16300 resultType = GetSignedVectorType(resultType);
16301 break;
16302 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
16303 const VectorType *VTy = resultType->castAs<VectorType>();
16304 if (VTy->getVectorKind() != VectorType::GenericVector)
16305 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16306 << resultType << Input.get()->getSourceRange());
16307
16308 // Vector logical not returns the signed variant of the operand type.
16309 resultType = GetSignedVectorType(resultType);
16310 break;
16311 } else {
16312 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16313 << resultType << Input.get()->getSourceRange());
16314 }
16315
16316 // LNot always has type int. C99 6.5.3.3p5.
16317 // In C++, it's bool. C++ 5.3.1p8
16318 resultType = Context.getLogicalOperationType();
16319 break;
16320 case UO_Real:
16321 case UO_Imag:
16322 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16323 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16324 // complex l-values to ordinary l-values and all other values to r-values.
16325 if (Input.isInvalid()) return ExprError();
16326 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16327 if (Input.get()->isGLValue() &&
16328 Input.get()->getObjectKind() == OK_Ordinary)
16329 VK = Input.get()->getValueKind();
16330 } else if (!getLangOpts().CPlusPlus) {
16331 // In C, a volatile scalar is read by __imag. In C++, it is not.
16332 Input = DefaultLvalueConversion(Input.get());
16333 }
16334 break;
16335 case UO_Extension:
16336 resultType = Input.get()->getType();
16337 VK = Input.get()->getValueKind();
16338 OK = Input.get()->getObjectKind();
16339 break;
16340 case UO_Coawait:
16341 // It's unnecessary to represent the pass-through operator co_await in the
16342 // AST; just return the input expression instead.
16343 assert(!Input.get()->getType()->isDependentType() &&
16344 "the co_await expression must be non-dependant before "
16345 "building operator co_await");
16346 return Input;
16347 }
16348 if (resultType.isNull() || Input.isInvalid())
16349 return ExprError();
16350
16351 // Check for array bounds violations in the operand of the UnaryOperator,
16352 // except for the '*' and '&' operators that have to be handled specially
16353 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16354 // that are explicitly defined as valid by the standard).
16355 if (Opc != UO_AddrOf && Opc != UO_Deref)
16356 CheckArrayAccess(Input.get());
16357
16358 auto *UO =
16359 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16360 OpLoc, CanOverflow, CurFPFeatureOverrides());
16361
16362 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16363 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16364 !isUnevaluatedContext())
16365 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16366
16367 // Convert the result back to a half vector.
16368 if (ConvertHalfVec)
16369 return convertVector(UO, Context.HalfTy, *this);
16370 return UO;
16371}
16372
16373/// Determine whether the given expression is a qualified member
16374/// access expression, of a form that could be turned into a pointer to member
16375/// with the address-of operator.
16376bool Sema::isQualifiedMemberAccess(Expr *E) {
16377 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16378 if (!DRE->getQualifier())
16379 return false;
16380
16381 ValueDecl *VD = DRE->getDecl();
16382 if (!VD->isCXXClassMember())
16383 return false;
16384
16385 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16386 return true;
16387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16388 return Method->isInstance();
16389
16390 return false;
16391 }
16392
16393 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16394 if (!ULE->getQualifier())
16395 return false;
16396
16397 for (NamedDecl *D : ULE->decls()) {
16398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16399 if (Method->isInstance())
16400 return true;
16401 } else {
16402 // Overload set does not contain methods.
16403 break;
16404 }
16405 }
16406
16407 return false;
16408 }
16409
16410 return false;
16411}
16412
16413ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16414 UnaryOperatorKind Opc, Expr *Input,
16415 bool IsAfterAmp) {
16416 // First things first: handle placeholders so that the
16417 // overloaded-operator check considers the right type.
16418 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16419 // Increment and decrement of pseudo-object references.
16420 if (pty->getKind() == BuiltinType::PseudoObject &&
16421 UnaryOperator::isIncrementDecrementOp(Opc))
16422 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16423
16424 // extension is always a builtin operator.
16425 if (Opc == UO_Extension)
16426 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16427
16428 // & gets special logic for several kinds of placeholder.
16429 // The builtin code knows what to do.
16430 if (Opc == UO_AddrOf &&
16431 (pty->getKind() == BuiltinType::Overload ||
16432 pty->getKind() == BuiltinType::UnknownAny ||
16433 pty->getKind() == BuiltinType::BoundMember))
16434 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16435
16436 // Anything else needs to be handled now.
16437 ExprResult Result = CheckPlaceholderExpr(Input);
16438 if (Result.isInvalid()) return ExprError();
16439 Input = Result.get();
16440 }
16441
16442 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16443 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16444 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16445 // Find all of the overloaded operators visible from this point.
16446 UnresolvedSet<16> Functions;
16447 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16448 if (S && OverOp != OO_None)
16449 LookupOverloadedOperatorName(OverOp, S, Functions);
16450
16451 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16452 }
16453
16454 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16455}
16456
16457// Unary Operators. 'Tok' is the token for the operator.
16458ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16459 Expr *Input, bool IsAfterAmp) {
16460 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16461 IsAfterAmp);
16462}
16463
16464/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16465ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16466 LabelDecl *TheDecl) {
16467 TheDecl->markUsed(Context);
16468 // Create the AST node. The address of a label always has type 'void*'.
16469 auto *Res = new (Context) AddrLabelExpr(
16470 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16471
16472 if (getCurFunction())
16473 getCurFunction()->AddrLabels.push_back(Res);
16474
16475 return Res;
16476}
16477
16478void Sema::ActOnStartStmtExpr() {
16479 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16480 // Make sure we diagnose jumping into a statement expression.
16481 setFunctionHasBranchProtectedScope();
16482}
16483
16484void Sema::ActOnStmtExprError() {
16485 // Note that function is also called by TreeTransform when leaving a
16486 // StmtExpr scope without rebuilding anything.
16487
16488 DiscardCleanupsInEvaluationContext();
16489 PopExpressionEvaluationContext();
16490}
16491
16492ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16493 SourceLocation RPLoc) {
16494 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16495}
16496
16497ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16498 SourceLocation RPLoc, unsigned TemplateDepth) {
16499 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16500 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16501
16502 if (hasAnyUnrecoverableErrorsInThisFunction())
16503 DiscardCleanupsInEvaluationContext();
16504 assert(!Cleanup.exprNeedsCleanups() &&
16505 "cleanups within StmtExpr not correctly bound!");
16506 PopExpressionEvaluationContext();
16507
16508 // FIXME: there are a variety of strange constraints to enforce here, for
16509 // example, it is not possible to goto into a stmt expression apparently.
16510 // More semantic analysis is needed.
16511
16512 // If there are sub-stmts in the compound stmt, take the type of the last one
16513 // as the type of the stmtexpr.
16514 QualType Ty = Context.VoidTy;
16515 bool StmtExprMayBindToTemp = false;
16516 if (!Compound->body_empty()) {
16517 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16518 if (const auto *LastStmt =
16519 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16520 if (const Expr *Value = LastStmt->getExprStmt()) {
16521 StmtExprMayBindToTemp = true;
16522 Ty = Value->getType();
16523 }
16524 }
16525 }
16526
16527 // FIXME: Check that expression type is complete/non-abstract; statement
16528 // expressions are not lvalues.
16529 Expr *ResStmtExpr =
16530 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16531 if (StmtExprMayBindToTemp)
16532 return MaybeBindToTemporary(ResStmtExpr);
16533 return ResStmtExpr;
16534}
16535
16536ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16537 if (ER.isInvalid())
16538 return ExprError();
16539
16540 // Do function/array conversion on the last expression, but not
16541 // lvalue-to-rvalue. However, initialize an unqualified type.
16542 ER = DefaultFunctionArrayConversion(ER.get());
16543 if (ER.isInvalid())
16544 return ExprError();
16545 Expr *E = ER.get();
16546
16547 if (E->isTypeDependent())
16548 return E;
16549
16550 // In ARC, if the final expression ends in a consume, splice
16551 // the consume out and bind it later. In the alternate case
16552 // (when dealing with a retainable type), the result
16553 // initialization will create a produce. In both cases the
16554 // result will be +1, and we'll need to balance that out with
16555 // a bind.
16556 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16557 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16558 return Cast->getSubExpr();
16559
16560 // FIXME: Provide a better location for the initialization.
16561 return PerformCopyInitialization(
16562 InitializedEntity::InitializeStmtExprResult(
16563 E->getBeginLoc(), E->getType().getUnqualifiedType()),
16564 SourceLocation(), E);
16565}
16566
16567ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16568 TypeSourceInfo *TInfo,
16569 ArrayRef<OffsetOfComponent> Components,
16570 SourceLocation RParenLoc) {
16571 QualType ArgTy = TInfo->getType();
16572 bool Dependent = ArgTy->isDependentType();
16573 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16574
16575 // We must have at least one component that refers to the type, and the first
16576 // one is known to be a field designator. Verify that the ArgTy represents
16577 // a struct/union/class.
16578 if (!Dependent && !ArgTy->isRecordType())
16579 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16580 << ArgTy << TypeRange);
16581
16582 // Type must be complete per C99 7.17p3 because a declaring a variable
16583 // with an incomplete type would be ill-formed.
16584 if (!Dependent
16585 && RequireCompleteType(BuiltinLoc, ArgTy,
16586 diag::err_offsetof_incomplete_type, TypeRange))
16587 return ExprError();
16588
16589 bool DidWarnAboutNonPOD = false;
16590 QualType CurrentType = ArgTy;
16591 SmallVector<OffsetOfNode, 4> Comps;
16592 SmallVector<Expr*, 4> Exprs;
16593 for (const OffsetOfComponent &OC : Components) {
16594 if (OC.isBrackets) {
16595 // Offset of an array sub-field. TODO: Should we allow vector elements?
16596 if (!CurrentType->isDependentType()) {
16597 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16598 if(!AT)
16599 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16600 << CurrentType);
16601 CurrentType = AT->getElementType();
16602 } else
16603 CurrentType = Context.DependentTy;
16604
16605 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16606 if (IdxRval.isInvalid())
16607 return ExprError();
16608 Expr *Idx = IdxRval.get();
16609
16610 // The expression must be an integral expression.
16611 // FIXME: An integral constant expression?
16612 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16613 !Idx->getType()->isIntegerType())
16614 return ExprError(
16615 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16616 << Idx->getSourceRange());
16617
16618 // Record this array index.
16619 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16620 Exprs.push_back(Idx);
16621 continue;
16622 }
16623
16624 // Offset of a field.
16625 if (CurrentType->isDependentType()) {
16626 // We have the offset of a field, but we can't look into the dependent
16627 // type. Just record the identifier of the field.
16628 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16629 CurrentType = Context.DependentTy;
16630 continue;
16631 }
16632
16633 // We need to have a complete type to look into.
16634 if (RequireCompleteType(OC.LocStart, CurrentType,
16635 diag::err_offsetof_incomplete_type))
16636 return ExprError();
16637
16638 // Look for the designated field.
16639 const RecordType *RC = CurrentType->getAs<RecordType>();
16640 if (!RC)
16641 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16642 << CurrentType);
16643 RecordDecl *RD = RC->getDecl();
16644
16645 // C++ [lib.support.types]p5:
16646 // The macro offsetof accepts a restricted set of type arguments in this
16647 // International Standard. type shall be a POD structure or a POD union
16648 // (clause 9).
16649 // C++11 [support.types]p4:
16650 // If type is not a standard-layout class (Clause 9), the results are
16651 // undefined.
16652 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16653 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16654 unsigned DiagID =
16655 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16656 : diag::ext_offsetof_non_pod_type;
16657
16658 if (!IsSafe && !DidWarnAboutNonPOD &&
16659 DiagRuntimeBehavior(BuiltinLoc, nullptr,
16660 PDiag(DiagID)
16661 << SourceRange(Components[0].LocStart, OC.LocEnd)
16662 << CurrentType))
16663 DidWarnAboutNonPOD = true;
16664 }
16665
16666 // Look for the field.
16667 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16668 LookupQualifiedName(R, RD);
16669 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16670 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16671 if (!MemberDecl) {
16672 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16673 MemberDecl = IndirectMemberDecl->getAnonField();
16674 }
16675
16676 if (!MemberDecl)
16677 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
16678 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
16679 OC.LocEnd));
16680
16681 // C99 7.17p3:
16682 // (If the specified member is a bit-field, the behavior is undefined.)
16683 //
16684 // We diagnose this as an error.
16685 if (MemberDecl->isBitField()) {
16686 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16687 << MemberDecl->getDeclName()
16688 << SourceRange(BuiltinLoc, RParenLoc);
16689 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16690 return ExprError();
16691 }
16692
16693 RecordDecl *Parent = MemberDecl->getParent();
16694 if (IndirectMemberDecl)
16695 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16696
16697 // If the member was found in a base class, introduce OffsetOfNodes for
16698 // the base class indirections.
16699 CXXBasePaths Paths;
16700 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16701 Paths)) {
16702 if (Paths.getDetectedVirtual()) {
16703 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16704 << MemberDecl->getDeclName()
16705 << SourceRange(BuiltinLoc, RParenLoc);
16706 return ExprError();
16707 }
16708
16709 CXXBasePath &Path = Paths.front();
16710 for (const CXXBasePathElement &B : Path)
16711 Comps.push_back(OffsetOfNode(B.Base));
16712 }
16713
16714 if (IndirectMemberDecl) {
16715 for (auto *FI : IndirectMemberDecl->chain()) {
16716 assert(isa<FieldDecl>(FI));
16717 Comps.push_back(OffsetOfNode(OC.LocStart,
16718 cast<FieldDecl>(FI), OC.LocEnd));
16719 }
16720 } else
16721 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16722
16723 CurrentType = MemberDecl->getType().getNonReferenceType();
16724 }
16725
16726 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16727 Comps, Exprs, RParenLoc);
16728}
16729
16730ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16731 SourceLocation BuiltinLoc,
16732 SourceLocation TypeLoc,
16733 ParsedType ParsedArgTy,
16734 ArrayRef<OffsetOfComponent> Components,
16735 SourceLocation RParenLoc) {
16736
16737 TypeSourceInfo *ArgTInfo;
16738 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16739 if (ArgTy.isNull())
16740 return ExprError();
16741
16742 if (!ArgTInfo)
16743 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16744
16745 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16746}
16747
16748
16749ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16750 Expr *CondExpr,
16751 Expr *LHSExpr, Expr *RHSExpr,
16752 SourceLocation RPLoc) {
16753 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16754
16755 ExprValueKind VK = VK_PRValue;
16756 ExprObjectKind OK = OK_Ordinary;
16757 QualType resType;
16758 bool CondIsTrue = false;
16759 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16760 resType = Context.DependentTy;
16761 } else {
16762 // The conditional expression is required to be a constant expression.
16763 llvm::APSInt condEval(32);
16764 ExprResult CondICE = VerifyIntegerConstantExpression(
16765 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16766 if (CondICE.isInvalid())
16767 return ExprError();
16768 CondExpr = CondICE.get();
16769 CondIsTrue = condEval.getZExtValue();
16770
16771 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16772 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16773
16774 resType = ActiveExpr->getType();
16775 VK = ActiveExpr->getValueKind();
16776 OK = ActiveExpr->getObjectKind();
16777 }
16778
16779 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16780 resType, VK, OK, RPLoc, CondIsTrue);
16781}
16782
16783//===----------------------------------------------------------------------===//
16784// Clang Extensions.
16785//===----------------------------------------------------------------------===//
16786
16787/// ActOnBlockStart - This callback is invoked when a block literal is started.
16788void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16789 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16790
16791 if (LangOpts.CPlusPlus) {
16792 MangleNumberingContext *MCtx;
16793 Decl *ManglingContextDecl;
16794 std::tie(MCtx, ManglingContextDecl) =
16795 getCurrentMangleNumberContext(Block->getDeclContext());
16796 if (MCtx) {
16797 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16798 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16799 }
16800 }
16801
16802 PushBlockScope(CurScope, Block);
16803 CurContext->addDecl(Block);
16804 if (CurScope)
16805 PushDeclContext(CurScope, Block);
16806 else
16807 CurContext = Block;
16808
16809 getCurBlock()->HasImplicitReturnType = true;
16810
16811 // Enter a new evaluation context to insulate the block from any
16812 // cleanups from the enclosing full-expression.
16813 PushExpressionEvaluationContext(
16814 ExpressionEvaluationContext::PotentiallyEvaluated);
16815}
16816
16817void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16818 Scope *CurScope) {
16819 assert(ParamInfo.getIdentifier() == nullptr &&
16820 "block-id should have no identifier!");
16821 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16822 BlockScopeInfo *CurBlock = getCurBlock();
16823
16824 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16825 QualType T = Sig->getType();
16826
16827 // FIXME: We should allow unexpanded parameter packs here, but that would,
16828 // in turn, make the block expression contain unexpanded parameter packs.
16829 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16830 // Drop the parameters.
16831 FunctionProtoType::ExtProtoInfo EPI;
16832 EPI.HasTrailingReturn = false;
16833 EPI.TypeQuals.addConst();
16834 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16835 Sig = Context.getTrivialTypeSourceInfo(T);
16836 }
16837
16838 // GetTypeForDeclarator always produces a function type for a block
16839 // literal signature. Furthermore, it is always a FunctionProtoType
16840 // unless the function was written with a typedef.
16841 assert(T->isFunctionType() &&
16842 "GetTypeForDeclarator made a non-function block signature");
16843
16844 // Look for an explicit signature in that function type.
16845 FunctionProtoTypeLoc ExplicitSignature;
16846
16847 if ((ExplicitSignature = Sig->getTypeLoc()
16848 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16849
16850 // Check whether that explicit signature was synthesized by
16851 // GetTypeForDeclarator. If so, don't save that as part of the
16852 // written signature.
16853 if (ExplicitSignature.getLocalRangeBegin() ==
16854 ExplicitSignature.getLocalRangeEnd()) {
16855 // This would be much cheaper if we stored TypeLocs instead of
16856 // TypeSourceInfos.
16857 TypeLoc Result = ExplicitSignature.getReturnLoc();
16858 unsigned Size = Result.getFullDataSize();
16859 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16860 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16861
16862 ExplicitSignature = FunctionProtoTypeLoc();
16863 }
16864 }
16865
16866 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16867 CurBlock->FunctionType = T;
16868
16869 const auto *Fn = T->castAs<FunctionType>();
16870 QualType RetTy = Fn->getReturnType();
16871 bool isVariadic =
16872 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16873
16874 CurBlock->TheDecl->setIsVariadic(isVariadic);
16875
16876 // Context.DependentTy is used as a placeholder for a missing block
16877 // return type. TODO: what should we do with declarators like:
16878 // ^ * { ... }
16879 // If the answer is "apply template argument deduction"....
16880 if (RetTy != Context.DependentTy) {
16881 CurBlock->ReturnType = RetTy;
16882 CurBlock->TheDecl->setBlockMissingReturnType(false);
16883 CurBlock->HasImplicitReturnType = false;
16884 }
16885
16886 // Push block parameters from the declarator if we had them.
16887 SmallVector<ParmVarDecl*, 8> Params;
16888 if (ExplicitSignature) {
16889 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16890 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16891 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16892 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16893 // Diagnose this as an extension in C17 and earlier.
16894 if (!getLangOpts().C2x)
16895 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16896 }
16897 Params.push_back(Param);
16898 }
16899
16900 // Fake up parameter variables if we have a typedef, like
16901 // ^ fntype { ... }
16902 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16903 for (const auto &I : Fn->param_types()) {
16904 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16905 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16906 Params.push_back(Param);
16907 }
16908 }
16909
16910 // Set the parameters on the block decl.
16911 if (!Params.empty()) {
16912 CurBlock->TheDecl->setParams(Params);
16913 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16914 /*CheckParameterNames=*/false);
16915 }
16916
16917 // Finally we can process decl attributes.
16918 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16919
16920 // Put the parameter variables in scope.
16921 for (auto *AI : CurBlock->TheDecl->parameters()) {
16922 AI->setOwningFunction(CurBlock->TheDecl);
16923
16924 // If this has an identifier, add it to the scope stack.
16925 if (AI->getIdentifier()) {
16926 CheckShadow(CurBlock->TheScope, AI);
16927
16928 PushOnScopeChains(AI, CurBlock->TheScope);
16929 }
16930
16931 if (AI->isInvalidDecl())
16932 CurBlock->TheDecl->setInvalidDecl();
16933 }
16934}
16935
16936/// ActOnBlockError - If there is an error parsing a block, this callback
16937/// is invoked to pop the information about the block from the action impl.
16938void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16939 // Leave the expression-evaluation context.
16940 DiscardCleanupsInEvaluationContext();
16941 PopExpressionEvaluationContext();
16942
16943 // Pop off CurBlock, handle nested blocks.
16944 PopDeclContext();
16945 PopFunctionScopeInfo();
16946}
16947
16948/// ActOnBlockStmtExpr - This is called when the body of a block statement
16949/// literal was successfully completed. ^(int x){...}
16950ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16951 Stmt *Body, Scope *CurScope) {
16952 // If blocks are disabled, emit an error.
16953 if (!LangOpts.Blocks)
16954 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16955
16956 // Leave the expression-evaluation context.
16957 if (hasAnyUnrecoverableErrorsInThisFunction())
16958 DiscardCleanupsInEvaluationContext();
16959 assert(!Cleanup.exprNeedsCleanups() &&
16960 "cleanups within block not correctly bound!");
16961 PopExpressionEvaluationContext();
16962
16963 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16964 BlockDecl *BD = BSI->TheDecl;
16965
16966 if (BSI->HasImplicitReturnType)
16967 deduceClosureReturnType(*BSI);
16968
16969 QualType RetTy = Context.VoidTy;
16970 if (!BSI->ReturnType.isNull())
16971 RetTy = BSI->ReturnType;
16972
16973 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16974 QualType BlockTy;
16975
16976 // If the user wrote a function type in some form, try to use that.
16977 if (!BSI->FunctionType.isNull()) {
16978 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16979
16980 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16981 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16982
16983 // Turn protoless block types into nullary block types.
16984 if (isa<FunctionNoProtoType>(FTy)) {
16985 FunctionProtoType::ExtProtoInfo EPI;
16986 EPI.ExtInfo = Ext;
16987 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16988
16989 // Otherwise, if we don't need to change anything about the function type,
16990 // preserve its sugar structure.
16991 } else if (FTy->getReturnType() == RetTy &&
16992 (!NoReturn || FTy->getNoReturnAttr())) {
16993 BlockTy = BSI->FunctionType;
16994
16995 // Otherwise, make the minimal modifications to the function type.
16996 } else {
16997 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16998 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16999 EPI.TypeQuals = Qualifiers();
17000 EPI.ExtInfo = Ext;
17001 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17002 }
17003
17004 // If we don't have a function type, just build one from nothing.
17005 } else {
17006 FunctionProtoType::ExtProtoInfo EPI;
17007 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17008 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
17009 }
17010
17011 DiagnoseUnusedParameters(BD->parameters());
17012 BlockTy = Context.getBlockPointerType(BlockTy);
17013
17014 // If needed, diagnose invalid gotos and switches in the block.
17015 if (getCurFunction()->NeedsScopeChecking() &&
17016 !PP.isCodeCompletionEnabled())
17017 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
17018
17019 BD->setBody(cast<CompoundStmt>(Body));
17020
17021 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17022 DiagnoseUnguardedAvailabilityViolations(BD);
17023
17024 // Try to apply the named return value optimization. We have to check again
17025 // if we can do this, though, because blocks keep return statements around
17026 // to deduce an implicit return type.
17027 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17028 !BD->isDependentContext())
17029 computeNRVO(Body, BSI);
17030
17031 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17032 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17033 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
17034 NTCUK_Destruct|NTCUK_Copy);
17035
17036 PopDeclContext();
17037
17038 // Set the captured variables on the block.
17039 SmallVector<BlockDecl::Capture, 4> Captures;
17040 for (Capture &Cap : BSI->Captures) {
17041 if (Cap.isInvalid() || Cap.isThisCapture())
17042 continue;
17043 // Cap.getVariable() is always a VarDecl because
17044 // blocks cannot capture structured bindings or other ValueDecl kinds.
17045 auto *Var = cast<VarDecl>(Cap.getVariable());
17046 Expr *CopyExpr = nullptr;
17047 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17048 if (const RecordType *Record =
17049 Cap.getCaptureType()->getAs<RecordType>()) {
17050 // The capture logic needs the destructor, so make sure we mark it.
17051 // Usually this is unnecessary because most local variables have
17052 // their destructors marked at declaration time, but parameters are
17053 // an exception because it's technically only the call site that
17054 // actually requires the destructor.
17055 if (isa<ParmVarDecl>(Var))
17056 FinalizeVarWithDestructor(Var, Record);
17057
17058 // Enter a separate potentially-evaluated context while building block
17059 // initializers to isolate their cleanups from those of the block
17060 // itself.
17061 // FIXME: Is this appropriate even when the block itself occurs in an
17062 // unevaluated operand?
17063 EnterExpressionEvaluationContext EvalContext(
17064 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17065
17066 SourceLocation Loc = Cap.getLocation();
17067
17068 ExprResult Result = BuildDeclarationNameExpr(
17069 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17070
17071 // According to the blocks spec, the capture of a variable from
17072 // the stack requires a const copy constructor. This is not true
17073 // of the copy/move done to move a __block variable to the heap.
17074 if (!Result.isInvalid() &&
17075 !Result.get()->getType().isConstQualified()) {
17076 Result = ImpCastExprToType(Result.get(),
17077 Result.get()->getType().withConst(),
17078 CK_NoOp, VK_LValue);
17079 }
17080
17081 if (!Result.isInvalid()) {
17082 Result = PerformCopyInitialization(
17083 InitializedEntity::InitializeBlock(Var->getLocation(),
17084 Cap.getCaptureType()),
17085 Loc, Result.get());
17086 }
17087
17088 // Build a full-expression copy expression if initialization
17089 // succeeded and used a non-trivial constructor. Recover from
17090 // errors by pretending that the copy isn't necessary.
17091 if (!Result.isInvalid() &&
17092 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17093 ->isTrivial()) {
17094 Result = MaybeCreateExprWithCleanups(Result);
17095 CopyExpr = Result.get();
17096 }
17097 }
17098 }
17099
17100 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17101 CopyExpr);
17102 Captures.push_back(NewCap);
17103 }
17104 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17105
17106 // Pop the block scope now but keep it alive to the end of this function.
17107 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
17108 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17109
17110 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
17111
17112 // If the block isn't obviously global, i.e. it captures anything at
17113 // all, then we need to do a few things in the surrounding context:
17114 if (Result->getBlockDecl()->hasCaptures()) {
17115 // First, this expression has a new cleanup object.
17116 ExprCleanupObjects.push_back(Result->getBlockDecl());
17117 Cleanup.setExprNeedsCleanups(true);
17118
17119 // It also gets a branch-protected scope if any of the captured
17120 // variables needs destruction.
17121 for (const auto &CI : Result->getBlockDecl()->captures()) {
17122 const VarDecl *var = CI.getVariable();
17123 if (var->getType().isDestructedType() != QualType::DK_none) {
17124 setFunctionHasBranchProtectedScope();
17125 break;
17126 }
17127 }
17128 }
17129
17130 if (getCurFunction())
17131 getCurFunction()->addBlock(BD);
17132
17133 if (BD->isInvalidDecl())
17134 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17135 {Result}, Result->getType());
17136 return Result;
17137}
17138
17139ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17140 SourceLocation RPLoc) {
17141 TypeSourceInfo *TInfo;
17142 GetTypeFromParser(Ty, &TInfo);
17143 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17144}
17145
17146ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17147 Expr *E, TypeSourceInfo *TInfo,
17148 SourceLocation RPLoc) {
17149 Expr *OrigExpr = E;
17150 bool IsMS = false;
17151
17152 // CUDA device code does not support varargs.
17153 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17154 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17155 CUDAFunctionTarget T = IdentifyCUDATarget(F);
17156 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
17157 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17158 }
17159 }
17160
17161 // NVPTX does not support va_arg expression.
17162 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17163 Context.getTargetInfo().getTriple().isNVPTX())
17164 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17165
17166 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17167 // as Microsoft ABI on an actual Microsoft platform, where
17168 // __builtin_ms_va_list and __builtin_va_list are the same.)
17169 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17170 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17171 QualType MSVaListType = Context.getBuiltinMSVaListType();
17172 if (Context.hasSameType(MSVaListType, E->getType())) {
17173 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17174 return ExprError();
17175 IsMS = true;
17176 }
17177 }
17178
17179 // Get the va_list type
17180 QualType VaListType = Context.getBuiltinVaListType();
17181 if (!IsMS) {
17182 if (VaListType->isArrayType()) {
17183 // Deal with implicit array decay; for example, on x86-64,
17184 // va_list is an array, but it's supposed to decay to
17185 // a pointer for va_arg.
17186 VaListType = Context.getArrayDecayedType(VaListType);
17187 // Make sure the input expression also decays appropriately.
17188 ExprResult Result = UsualUnaryConversions(E);
17189 if (Result.isInvalid())
17190 return ExprError();
17191 E = Result.get();
17192 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17193 // If va_list is a record type and we are compiling in C++ mode,
17194 // check the argument using reference binding.
17195 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17196 Context, Context.getLValueReferenceType(VaListType), false);
17197 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
17198 if (Init.isInvalid())
17199 return ExprError();
17200 E = Init.getAs<Expr>();
17201 } else {
17202 // Otherwise, the va_list argument must be an l-value because
17203 // it is modified by va_arg.
17204 if (!E->isTypeDependent() &&
17205 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17206 return ExprError();
17207 }
17208 }
17209
17210 if (!IsMS && !E->isTypeDependent() &&
17211 !Context.hasSameType(VaListType, E->getType()))
17212 return ExprError(
17213 Diag(E->getBeginLoc(),
17214 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17215 << OrigExpr->getType() << E->getSourceRange());
17216
17217 if (!TInfo->getType()->isDependentType()) {
17218 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17219 diag::err_second_parameter_to_va_arg_incomplete,
17220 TInfo->getTypeLoc()))
17221 return ExprError();
17222
17223 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17224 TInfo->getType(),
17225 diag::err_second_parameter_to_va_arg_abstract,
17226 TInfo->getTypeLoc()))
17227 return ExprError();
17228
17229 if (!TInfo->getType().isPODType(Context)) {
17230 Diag(TInfo->getTypeLoc().getBeginLoc(),
17231 TInfo->getType()->isObjCLifetimeType()
17232 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17233 : diag::warn_second_parameter_to_va_arg_not_pod)
17234 << TInfo->getType()
17235 << TInfo->getTypeLoc().getSourceRange();
17236 }
17237
17238 // Check for va_arg where arguments of the given type will be promoted
17239 // (i.e. this va_arg is guaranteed to have undefined behavior).
17240 QualType PromoteType;
17241 if (Context.isPromotableIntegerType(TInfo->getType())) {
17242 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17243 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17244 // and C2x 7.16.1.1p2 says, in part:
17245 // If type is not compatible with the type of the actual next argument
17246 // (as promoted according to the default argument promotions), the
17247 // behavior is undefined, except for the following cases:
17248 // - both types are pointers to qualified or unqualified versions of
17249 // compatible types;
17250 // - one type is a signed integer type, the other type is the
17251 // corresponding unsigned integer type, and the value is
17252 // representable in both types;
17253 // - one type is pointer to qualified or unqualified void and the
17254 // other is a pointer to a qualified or unqualified character type.
17255 // Given that type compatibility is the primary requirement (ignoring
17256 // qualifications), you would think we could call typesAreCompatible()
17257 // directly to test this. However, in C++, that checks for *same type*,
17258 // which causes false positives when passing an enumeration type to
17259 // va_arg. Instead, get the underlying type of the enumeration and pass
17260 // that.
17261 QualType UnderlyingType = TInfo->getType();
17262 if (const auto *ET = UnderlyingType->getAs<EnumType>())
17263 UnderlyingType = ET->getDecl()->getIntegerType();
17264 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17265 /*CompareUnqualified*/ true))
17266 PromoteType = QualType();
17267
17268 // If the types are still not compatible, we need to test whether the
17269 // promoted type and the underlying type are the same except for
17270 // signedness. Ask the AST for the correctly corresponding type and see
17271 // if that's compatible.
17272 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17273 PromoteType->isUnsignedIntegerType() !=
17274 UnderlyingType->isUnsignedIntegerType()) {
17275 UnderlyingType =
17276 UnderlyingType->isUnsignedIntegerType()
17277 ? Context.getCorrespondingSignedType(UnderlyingType)
17278 : Context.getCorrespondingUnsignedType(UnderlyingType);
17279 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17280 /*CompareUnqualified*/ true))
17281 PromoteType = QualType();
17282 }
17283 }
17284 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17285 PromoteType = Context.DoubleTy;
17286 if (!PromoteType.isNull())
17287 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17288 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17289 << TInfo->getType()
17290 << PromoteType
17291 << TInfo->getTypeLoc().getSourceRange());
17292 }
17293
17294 QualType T = TInfo->getType().getNonLValueExprType(Context);
17295 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17296}
17297
17298ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17299 // The type of __null will be int or long, depending on the size of
17300 // pointers on the target.
17301 QualType Ty;
17302 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17303 if (pw == Context.getTargetInfo().getIntWidth())
17304 Ty = Context.IntTy;
17305 else if (pw == Context.getTargetInfo().getLongWidth())
17306 Ty = Context.LongTy;
17307 else if (pw == Context.getTargetInfo().getLongLongWidth())
17308 Ty = Context.LongLongTy;
17309 else {
17310 llvm_unreachable("I don't know size of pointer!");
17311 }
17312
17313 return new (Context) GNUNullExpr(Ty, TokenLoc);
17314}
17315
17316static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17317 CXXRecordDecl *ImplDecl = nullptr;
17318
17319 // Fetch the std::source_location::__impl decl.
17320 if (NamespaceDecl *Std = S.getStdNamespace()) {
17321 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17322 Loc, Sema::LookupOrdinaryName);
17323 if (S.LookupQualifiedName(ResultSL, Std)) {
17324 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17325 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17326 Loc, Sema::LookupOrdinaryName);
17327 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17328 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17329 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17330 }
17331 }
17332 }
17333 }
17334
17335 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17336 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17337 return nullptr;
17338 }
17339
17340 // Verify that __impl is a trivial struct type, with no base classes, and with
17341 // only the four expected fields.
17342 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17343 ImplDecl->getNumBases() != 0) {
17344 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17345 return nullptr;
17346 }
17347
17348 unsigned Count = 0;
17349 for (FieldDecl *F : ImplDecl->fields()) {
17350 StringRef Name = F->getName();
17351
17352 if (Name == "_M_file_name") {
17353 if (F->getType() !=
17354 S.Context.getPointerType(S.Context.CharTy.withConst()))
17355 break;
17356 Count++;
17357 } else if (Name == "_M_function_name") {
17358 if (F->getType() !=
17359 S.Context.getPointerType(S.Context.CharTy.withConst()))
17360 break;
17361 Count++;
17362 } else if (Name == "_M_line") {
17363 if (!F->getType()->isIntegerType())
17364 break;
17365 Count++;
17366 } else if (Name == "_M_column") {
17367 if (!F->getType()->isIntegerType())
17368 break;
17369 Count++;
17370 } else {
17371 Count = 100; // invalid
17372 break;
17373 }
17374 }
17375 if (Count != 4) {
17376 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17377 return nullptr;
17378 }
17379
17380 return ImplDecl;
17381}
17382
17383ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
17384 SourceLocation BuiltinLoc,
17385 SourceLocation RPLoc) {
17386 QualType ResultTy;
17387 switch (Kind) {
17388 case SourceLocExpr::File:
17389 case SourceLocExpr::FileName:
17390 case SourceLocExpr::Function:
17391 case SourceLocExpr::FuncSig: {
17392 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17393 ResultTy =
17394 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17395 break;
17396 }
17397 case SourceLocExpr::Line:
17398 case SourceLocExpr::Column:
17399 ResultTy = Context.UnsignedIntTy;
17400 break;
17401 case SourceLocExpr::SourceLocStruct:
17402 if (!StdSourceLocationImplDecl) {
17403 StdSourceLocationImplDecl =
17404 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17405 if (!StdSourceLocationImplDecl)
17406 return ExprError();
17407 }
17408 ResultTy = Context.getPointerType(
17409 Context.getRecordType(StdSourceLocationImplDecl).withConst());
17410 break;
17411 }
17412
17413 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17414}
17415
17416ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
17417 QualType ResultTy,
17418 SourceLocation BuiltinLoc,
17419 SourceLocation RPLoc,
17420 DeclContext *ParentContext) {
17421 return new (Context)
17422 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17423}
17424
17425bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17426 bool Diagnose) {
17427 if (!getLangOpts().ObjC)
17428 return false;
17429
17430 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17431 if (!PT)
17432 return false;
17433 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17434
17435 // Ignore any parens, implicit casts (should only be
17436 // array-to-pointer decays), and not-so-opaque values. The last is
17437 // important for making this trigger for property assignments.
17438 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17439 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17440 if (OV->getSourceExpr())
17441 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17442
17443 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17444 if (!PT->isObjCIdType() &&
17445 !(ID && ID->getIdentifier()->isStr("NSString")))
17446 return false;
17447 if (!SL->isOrdinary())
17448 return false;
17449
17450 if (Diagnose) {
17451 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17452 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17453 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17454 }
17455 return true;
17456 }
17457
17458 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17459 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17460 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17461 !SrcExpr->isNullPointerConstant(
17462 getASTContext(), Expr::NPC_NeverValueDependent)) {
17463 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17464 return false;
17465 if (Diagnose) {
17466 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17467 << /*number*/1
17468 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17469 Expr *NumLit =
17470 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17471 if (NumLit)
17472 Exp = NumLit;
17473 }
17474 return true;
17475 }
17476
17477 return false;
17478}
17479
17480static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17481 const Expr *SrcExpr) {
17482 if (!DstType->isFunctionPointerType() ||
17483 !SrcExpr->getType()->isFunctionType())
17484 return false;
17485
17486 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17487 if (!DRE)
17488 return false;
17489
17490 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17491 if (!FD)
17492 return false;
17493
17494 return !S.checkAddressOfFunctionIsAvailable(FD,
17495 /*Complain=*/true,
17496 SrcExpr->getBeginLoc());
17497}
17498
17499bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17500 SourceLocation Loc,
17501 QualType DstType, QualType SrcType,
17502 Expr *SrcExpr, AssignmentAction Action,
17503 bool *Complained) {
17504 if (Complained)
17505 *Complained = false;
17506
17507 // Decode the result (notice that AST's are still created for extensions).
17508 bool CheckInferredResultType = false;
17509 bool isInvalid = false;
17510 unsigned DiagKind = 0;
17511 ConversionFixItGenerator ConvHints;
17512 bool MayHaveConvFixit = false;
17513 bool MayHaveFunctionDiff = false;
17514 const ObjCInterfaceDecl *IFace = nullptr;
17515 const ObjCProtocolDecl *PDecl = nullptr;
17516
17517 switch (ConvTy) {
17518 case Compatible:
17519 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17520 return false;
17521
17522 case PointerToInt:
17523 if (getLangOpts().CPlusPlus) {
17524 DiagKind = diag::err_typecheck_convert_pointer_int;
17525 isInvalid = true;
17526 } else {
17527 DiagKind = diag::ext_typecheck_convert_pointer_int;
17528 }
17529 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17530 MayHaveConvFixit = true;
17531 break;
17532 case IntToPointer:
17533 if (getLangOpts().CPlusPlus) {
17534 DiagKind = diag::err_typecheck_convert_int_pointer;
17535 isInvalid = true;
17536 } else {
17537 DiagKind = diag::ext_typecheck_convert_int_pointer;
17538 }
17539 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17540 MayHaveConvFixit = true;
17541 break;
17542 case IncompatibleFunctionPointerStrict:
17543 DiagKind =
17544 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17545 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17546 MayHaveConvFixit = true;
17547 break;
17548 case IncompatibleFunctionPointer:
17549 if (getLangOpts().CPlusPlus) {
17550 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17551 isInvalid = true;
17552 } else {
17553 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17554 }
17555 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17556 MayHaveConvFixit = true;
17557 break;
17558 case IncompatiblePointer:
17559 if (Action == AA_Passing_CFAudited) {
17560 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17561 } else if (getLangOpts().CPlusPlus) {
17562 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17563 isInvalid = true;
17564 } else {
17565 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17566 }
17567 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17568 SrcType->isObjCObjectPointerType();
17569 if (!CheckInferredResultType) {
17570 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17571 } else if (CheckInferredResultType) {
17572 SrcType = SrcType.getUnqualifiedType();
17573 DstType = DstType.getUnqualifiedType();
17574 }
17575 MayHaveConvFixit = true;
17576 break;
17577 case IncompatiblePointerSign:
17578 if (getLangOpts().CPlusPlus) {
17579 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17580 isInvalid = true;
17581 } else {
17582 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17583 }
17584 break;
17585 case FunctionVoidPointer:
17586 if (getLangOpts().CPlusPlus) {
17587 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17588 isInvalid = true;
17589 } else {
17590 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17591 }
17592 break;
17593 case IncompatiblePointerDiscardsQualifiers: {
17594 // Perform array-to-pointer decay if necessary.
17595 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17596
17597 isInvalid = true;
17598
17599 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17600 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17601 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17602 DiagKind = diag::err_typecheck_incompatible_address_space;
17603 break;
17604
17605 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17606 DiagKind = diag::err_typecheck_incompatible_ownership;
17607 break;
17608 }
17609
17610 llvm_unreachable("unknown error case for discarding qualifiers!");
17611 // fallthrough
17612 }
17613 case CompatiblePointerDiscardsQualifiers:
17614 // If the qualifiers lost were because we were applying the
17615 // (deprecated) C++ conversion from a string literal to a char*
17616 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17617 // Ideally, this check would be performed in
17618 // checkPointerTypesForAssignment. However, that would require a
17619 // bit of refactoring (so that the second argument is an
17620 // expression, rather than a type), which should be done as part
17621 // of a larger effort to fix checkPointerTypesForAssignment for
17622 // C++ semantics.
17623 if (getLangOpts().CPlusPlus &&
17624 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17625 return false;
17626 if (getLangOpts().CPlusPlus) {
17627 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17628 isInvalid = true;
17629 } else {
17630 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17631 }
17632
17633 break;
17634 case IncompatibleNestedPointerQualifiers:
17635 if (getLangOpts().CPlusPlus) {
17636 isInvalid = true;
17637 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17638 } else {
17639 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17640 }
17641 break;
17642 case IncompatibleNestedPointerAddressSpaceMismatch:
17643 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17644 isInvalid = true;
17645 break;
17646 case IntToBlockPointer:
17647 DiagKind = diag::err_int_to_block_pointer;
17648 isInvalid = true;
17649 break;
17650 case IncompatibleBlockPointer:
17651 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17652 isInvalid = true;
17653 break;
17654 case IncompatibleObjCQualifiedId: {
17655 if (SrcType->isObjCQualifiedIdType()) {
17656 const ObjCObjectPointerType *srcOPT =
17657 SrcType->castAs<ObjCObjectPointerType>();
17658 for (auto *srcProto : srcOPT->quals()) {
17659 PDecl = srcProto;
17660 break;
17661 }
17662 if (const ObjCInterfaceType *IFaceT =
17663 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17664 IFace = IFaceT->getDecl();
17665 }
17666 else if (DstType->isObjCQualifiedIdType()) {
17667 const ObjCObjectPointerType *dstOPT =
17668 DstType->castAs<ObjCObjectPointerType>();
17669 for (auto *dstProto : dstOPT->quals()) {
17670 PDecl = dstProto;
17671 break;
17672 }
17673 if (const ObjCInterfaceType *IFaceT =
17674 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17675 IFace = IFaceT->getDecl();
17676 }
17677 if (getLangOpts().CPlusPlus) {
17678 DiagKind = diag::err_incompatible_qualified_id;
17679 isInvalid = true;
17680 } else {
17681 DiagKind = diag::warn_incompatible_qualified_id;
17682 }
17683 break;
17684 }
17685 case IncompatibleVectors:
17686 if (getLangOpts().CPlusPlus) {
17687 DiagKind = diag::err_incompatible_vectors;
17688 isInvalid = true;
17689 } else {
17690 DiagKind = diag::warn_incompatible_vectors;
17691 }
17692 break;
17693 case IncompatibleObjCWeakRef:
17694 DiagKind = diag::err_arc_weak_unavailable_assign;
17695 isInvalid = true;
17696 break;
17697 case Incompatible:
17698 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17699 if (Complained)
17700 *Complained = true;
17701 return true;
17702 }
17703
17704 DiagKind = diag::err_typecheck_convert_incompatible;
17705 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17706 MayHaveConvFixit = true;
17707 isInvalid = true;
17708 MayHaveFunctionDiff = true;
17709 break;
17710 }
17711
17712 QualType FirstType, SecondType;
17713 switch (Action) {
17714 case AA_Assigning:
17715 case AA_Initializing:
17716 // The destination type comes first.
17717 FirstType = DstType;
17718 SecondType = SrcType;
17719 break;
17720
17721 case AA_Returning:
17722 case AA_Passing:
17723 case AA_Passing_CFAudited:
17724 case AA_Converting:
17725 case AA_Sending:
17726 case AA_Casting:
17727 // The source type comes first.
17728 FirstType = SrcType;
17729 SecondType = DstType;
17730 break;
17731 }
17732
17733 PartialDiagnostic FDiag = PDiag(DiagKind);
17734 AssignmentAction ActionForDiag = Action;
17735 if (Action == AA_Passing_CFAudited)
17736 ActionForDiag = AA_Passing;
17737
17738 FDiag << FirstType << SecondType << ActionForDiag
17739 << SrcExpr->getSourceRange();
17740
17741 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17742 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17743 auto isPlainChar = [](const clang::Type *Type) {
17744 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17745 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17746 };
17747 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17748 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17749 }
17750
17751 // If we can fix the conversion, suggest the FixIts.
17752 if (!ConvHints.isNull()) {
17753 for (FixItHint &H : ConvHints.Hints)
17754 FDiag << H;
17755 }
17756
17757 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17758
17759 if (MayHaveFunctionDiff)
17760 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17761
17762 Diag(Loc, FDiag);
17763 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17764 DiagKind == diag::err_incompatible_qualified_id) &&
17765 PDecl && IFace && !IFace->hasDefinition())
17766 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17767 << IFace << PDecl;
17768
17769 if (SecondType == Context.OverloadTy)
17770 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17771 FirstType, /*TakingAddress=*/true);
17772
17773 if (CheckInferredResultType)
17774 EmitRelatedResultTypeNote(SrcExpr);
17775
17776 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17777 EmitRelatedResultTypeNoteForReturn(DstType);
17778
17779 if (Complained)
17780 *Complained = true;
17781 return isInvalid;
17782}
17783
17784ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17785 llvm::APSInt *Result,
17786 AllowFoldKind CanFold) {
17787 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17788 public:
17789 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17790 QualType T) override {
17791 return S.Diag(Loc, diag::err_ice_not_integral)
17792 << T << S.LangOpts.CPlusPlus;
17793 }
17794 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17795 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17796 }
17797 } Diagnoser;
17798
17799 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17800}
17801
17802ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17803 llvm::APSInt *Result,
17804 unsigned DiagID,
17805 AllowFoldKind CanFold) {
17806 class IDDiagnoser : public VerifyICEDiagnoser {
17807 unsigned DiagID;
17808
17809 public:
17810 IDDiagnoser(unsigned DiagID)
17811 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17812
17813 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17814 return S.Diag(Loc, DiagID);
17815 }
17816 } Diagnoser(DiagID);
17817
17818 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17819}
17820
17821Sema::SemaDiagnosticBuilder
17822Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17823 QualType T) {
17824 return diagnoseNotICE(S, Loc);
17825}
17826
17827Sema::SemaDiagnosticBuilder
17828Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17829 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17830}
17831
17832ExprResult
17833Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17834 VerifyICEDiagnoser &Diagnoser,
17835 AllowFoldKind CanFold) {
17836 SourceLocation DiagLoc = E->getBeginLoc();
17837
17838 if (getLangOpts().CPlusPlus11) {
17839 // C++11 [expr.const]p5:
17840 // If an expression of literal class type is used in a context where an
17841 // integral constant expression is required, then that class type shall
17842 // have a single non-explicit conversion function to an integral or
17843 // unscoped enumeration type
17844 ExprResult Converted;
17845 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17846 VerifyICEDiagnoser &BaseDiagnoser;
17847 public:
17848 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17849 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17850 BaseDiagnoser.Suppress, true),
17851 BaseDiagnoser(BaseDiagnoser) {}
17852
17853 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17854 QualType T) override {
17855 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17856 }
17857
17858 SemaDiagnosticBuilder diagnoseIncomplete(
17859 Sema &S, SourceLocation Loc, QualType T) override {
17860 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17861 }
17862
17863 SemaDiagnosticBuilder diagnoseExplicitConv(
17864 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17865 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17866 }
17867
17868 SemaDiagnosticBuilder noteExplicitConv(
17869 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17870 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17871 << ConvTy->isEnumeralType() << ConvTy;
17872 }
17873
17874 SemaDiagnosticBuilder diagnoseAmbiguous(
17875 Sema &S, SourceLocation Loc, QualType T) override {
17876 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17877 }
17878
17879 SemaDiagnosticBuilder noteAmbiguous(
17880 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17881 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17882 << ConvTy->isEnumeralType() << ConvTy;
17883 }
17884
17885 SemaDiagnosticBuilder diagnoseConversion(
17886 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17887 llvm_unreachable("conversion functions are permitted");
17888 }
17889 } ConvertDiagnoser(Diagnoser);
17890
17891 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17892 ConvertDiagnoser);
17893 if (Converted.isInvalid())
17894 return Converted;
17895 E = Converted.get();
17896 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17897 return ExprError();
17898 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17899 // An ICE must be of integral or unscoped enumeration type.
17900 if (!Diagnoser.Suppress)
17901 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17902 << E->getSourceRange();
17903 return ExprError();
17904 }
17905
17906 ExprResult RValueExpr = DefaultLvalueConversion(E);
17907 if (RValueExpr.isInvalid())
17908 return ExprError();
17909
17910 E = RValueExpr.get();
17911
17912 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17913 // in the non-ICE case.
17914 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17915 if (Result)
17916 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17917 if (!isa<ConstantExpr>(E))
17918 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17919 : ConstantExpr::Create(Context, E);
17920 return E;
17921 }
17922
17923 Expr::EvalResult EvalResult;
17924 SmallVector<PartialDiagnosticAt, 8> Notes;
17925 EvalResult.Diag = &Notes;
17926
17927 // Try to evaluate the expression, and produce diagnostics explaining why it's
17928 // not a constant expression as a side-effect.
17929 bool Folded =
17930 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17931 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17932
17933 if (!isa<ConstantExpr>(E))
17934 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17935
17936 // In C++11, we can rely on diagnostics being produced for any expression
17937 // which is not a constant expression. If no diagnostics were produced, then
17938 // this is a constant expression.
17939 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17940 if (Result)
17941 *Result = EvalResult.Val.getInt();
17942 return E;
17943 }
17944
17945 // If our only note is the usual "invalid subexpression" note, just point
17946 // the caret at its location rather than producing an essentially
17947 // redundant note.
17948 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17949 diag::note_invalid_subexpr_in_const_expr) {
17950 DiagLoc = Notes[0].first;
17951 Notes.clear();
17952 }
17953
17954 if (!Folded || !CanFold) {
17955 if (!Diagnoser.Suppress) {
17956 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17957 for (const PartialDiagnosticAt &Note : Notes)
17958 Diag(Note.first, Note.second);
17959 }
17960
17961 return ExprError();
17962 }
17963
17964 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17965 for (const PartialDiagnosticAt &Note : Notes)
17966 Diag(Note.first, Note.second);
17967
17968 if (Result)
17969 *Result = EvalResult.Val.getInt();
17970 return E;
17971}
17972
17973namespace {
17974 // Handle the case where we conclude a expression which we speculatively
17975 // considered to be unevaluated is actually evaluated.
17976 class TransformToPE : public TreeTransform<TransformToPE> {
17977 typedef TreeTransform<TransformToPE> BaseTransform;
17978
17979 public:
17980 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17981
17982 // Make sure we redo semantic analysis
17983 bool AlwaysRebuild() { return true; }
17984 bool ReplacingOriginal() { return true; }
17985
17986 // We need to special-case DeclRefExprs referring to FieldDecls which
17987 // are not part of a member pointer formation; normal TreeTransforming
17988 // doesn't catch this case because of the way we represent them in the AST.
17989 // FIXME: This is a bit ugly; is it really the best way to handle this
17990 // case?
17991 //
17992 // Error on DeclRefExprs referring to FieldDecls.
17993 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17994 if (isa<FieldDecl>(E->getDecl()) &&
17995 !SemaRef.isUnevaluatedContext())
17996 return SemaRef.Diag(E->getLocation(),
17997 diag::err_invalid_non_static_member_use)
17998 << E->getDecl() << E->getSourceRange();
17999
18000 return BaseTransform::TransformDeclRefExpr(E);
18001 }
18002
18003 // Exception: filter out member pointer formation
18004 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18005 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18006 return E;
18007
18008 return BaseTransform::TransformUnaryOperator(E);
18009 }
18010
18011 // The body of a lambda-expression is in a separate expression evaluation
18012 // context so never needs to be transformed.
18013 // FIXME: Ideally we wouldn't transform the closure type either, and would
18014 // just recreate the capture expressions and lambda expression.
18015 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18016 return SkipLambdaBody(E, Body);
18017 }
18018 };
18019}
18020
18021ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18022 assert(isUnevaluatedContext() &&
18023 "Should only transform unevaluated expressions");
18024 ExprEvalContexts.back().Context =
18025 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18026 if (isUnevaluatedContext())
18027 return E;
18028 return TransformToPE(*this).TransformExpr(E);
18029}
18030
18031TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18032 assert(isUnevaluatedContext() &&
18033 "Should only transform unevaluated expressions");
18034 ExprEvalContexts.back().Context =
18035 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
18036 if (isUnevaluatedContext())
18037 return TInfo;
18038 return TransformToPE(*this).TransformType(TInfo);
18039}
18040
18041void
18042Sema::PushExpressionEvaluationContext(
18043 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18044 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18045 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18046 LambdaContextDecl, ExprContext);
18047
18048 // Discarded statements and immediate contexts nested in other
18049 // discarded statements or immediate context are themselves
18050 // a discarded statement or an immediate context, respectively.
18051 ExprEvalContexts.back().InDiscardedStatement =
18052 ExprEvalContexts[ExprEvalContexts.size() - 2]
18053 .isDiscardedStatementContext();
18054
18055 // C++23 [expr.const]/p15
18056 // An expression or conversion is in an immediate function context if [...]
18057 // it is a subexpression of a manifestly constant-evaluated expression or
18058 // conversion.
18059 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
18060 ExprEvalContexts.back().InImmediateFunctionContext =
18061 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18062
18063 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18064 Prev.InImmediateEscalatingFunctionContext;
18065
18066 Cleanup.reset();
18067 if (!MaybeODRUseExprs.empty())
18068 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18069}
18070
18071void
18072Sema::PushExpressionEvaluationContext(
18073 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18074 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18075 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18076 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18077}
18078
18079namespace {
18080
18081const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18082 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18083 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18084 if (E->getOpcode() == UO_Deref)
18085 return CheckPossibleDeref(S, E->getSubExpr());
18086 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18087 return CheckPossibleDeref(S, E->getBase());
18088 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18089 return CheckPossibleDeref(S, E->getBase());
18090 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18091 QualType Inner;
18092 QualType Ty = E->getType();
18093 if (const auto *Ptr = Ty->getAs<PointerType>())
18094 Inner = Ptr->getPointeeType();
18095 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18096 Inner = Arr->getElementType();
18097 else
18098 return nullptr;
18099
18100 if (Inner->hasAttr(attr::NoDeref))
18101 return E;
18102 }
18103 return nullptr;
18104}
18105
18106} // namespace
18107
18108void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18109 for (const Expr *E : Rec.PossibleDerefs) {
18110 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18111 if (DeclRef) {
18112 const ValueDecl *Decl = DeclRef->getDecl();
18113 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18114 << Decl->getName() << E->getSourceRange();
18115 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18116 } else {
18117 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18118 << E->getSourceRange();
18119 }
18120 }
18121 Rec.PossibleDerefs.clear();
18122}
18123
18124/// Check whether E, which is either a discarded-value expression or an
18125/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
18126/// and if so, remove it from the list of volatile-qualified assignments that
18127/// we are going to warn are deprecated.
18128void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18129 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18130 return;
18131
18132 // Note: ignoring parens here is not justified by the standard rules, but
18133 // ignoring parentheses seems like a more reasonable approach, and this only
18134 // drives a deprecation warning so doesn't affect conformance.
18135 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18136 if (BO->getOpcode() == BO_Assign) {
18137 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18138 llvm::erase_value(LHSs, BO->getLHS());
18139 }
18140 }
18141}
18142
18143void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18144 assert(!FunctionScopes.empty() && "Expected a function scope");
18145 assert(getLangOpts().CPlusPlus20 &&
18146 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18147 "Cannot mark an immediate escalating expression outside of an "
18148 "immediate escalating context");
18149 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18150 Call && Call->getCallee()) {
18151 if (auto *DeclRef =
18152 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18153 DeclRef->setIsImmediateEscalating(true);
18154 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18155 Ctr->setIsImmediateEscalating(true);
18156 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18157 DeclRef->setIsImmediateEscalating(true);
18158 } else {
18159 assert(false && "expected an immediately escalating expression");
18160 }
18161 getCurFunction()->FoundImmediateEscalatingExpression = true;
18162}
18163
18164ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18165 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18166 !Decl->isImmediateFunction() || isConstantEvaluated() ||
18167 isCheckingDefaultArgumentOrInitializer() ||
18168 RebuildingImmediateInvocation || isImmediateFunctionContext())
18169 return E;
18170
18171 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18172 /// It's OK if this fails; we'll also remove this in
18173 /// HandleImmediateInvocations, but catching it here allows us to avoid
18174 /// walking the AST looking for it in simple cases.
18175 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18176 if (auto *DeclRef =
18177 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18178 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18179
18180 // C++23 [expr.const]/p16
18181 // An expression or conversion is immediate-escalating if it is not initially
18182 // in an immediate function context and it is [...] an immediate invocation
18183 // that is not a constant expression and is not a subexpression of an
18184 // immediate invocation.
18185 APValue Cached;
18186 auto CheckConstantExpressionAndKeepResult = [&]() {
18187 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18188 Expr::EvalResult Eval;
18189 Eval.Diag = &Notes;
18190 bool Res = E.get()->EvaluateAsConstantExpr(
18191 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18192 if (Res && Notes.empty()) {
18193 Cached = std::move(Eval.Val);
18194 return true;
18195 }
18196 return false;
18197 };
18198
18199 if (!E.get()->isValueDependent() &&
18200 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18201 !CheckConstantExpressionAndKeepResult()) {
18202 MarkExpressionAsImmediateEscalating(E.get());
18203 return E;
18204 }
18205
18206 if (Cleanup.exprNeedsCleanups()) {
18207 // Since an immediate invocation is a full expression itself - it requires
18208 // an additional ExprWithCleanups node, but it can participate to a bigger
18209 // full expression which actually requires cleanups to be run after so
18210 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18211 // may discard cleanups for outer expression too early.
18212
18213 // Note that ExprWithCleanups created here must always have empty cleanup
18214 // objects:
18215 // - compound literals do not create cleanup objects in C++ and immediate
18216 // invocations are C++-only.
18217 // - blocks are not allowed inside constant expressions and compiler will
18218 // issue an error if they appear there.
18219 //
18220 // Hence, in correct code any cleanup objects created inside current
18221 // evaluation context must be outside the immediate invocation.
18222 E = ExprWithCleanups::Create(getASTContext(), E.get(),
18223 Cleanup.cleanupsHaveSideEffects(), {});
18224 }
18225
18226 ConstantExpr *Res = ConstantExpr::Create(
18227 getASTContext(), E.get(),
18228 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18229 getASTContext()),
18230 /*IsImmediateInvocation*/ true);
18231 if (Cached.hasValue())
18232 Res->MoveIntoResult(Cached, getASTContext());
18233 /// Value-dependent constant expressions should not be immediately
18234 /// evaluated until they are instantiated.
18235 if (!Res->isValueDependent())
18236 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18237 return Res;
18238}
18239
18240static void EvaluateAndDiagnoseImmediateInvocation(
18241 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18242 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18243 Expr::EvalResult Eval;
18244 Eval.Diag = &Notes;
18245 ConstantExpr *CE = Candidate.getPointer();
18246 bool Result = CE->EvaluateAsConstantExpr(
18247 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18248 if (!Result || !Notes.empty()) {
18249 SemaRef.FailedImmediateInvocations.insert(CE);
18250 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18251 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18252 InnerExpr = FunctionalCast->getSubExpr();
18253 FunctionDecl *FD = nullptr;
18254 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18255 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18256 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18257 FD = Call->getConstructor();
18258 else
18259 llvm_unreachable("unhandled decl kind");
18260 assert(FD && FD->isImmediateFunction());
18261 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18262 << FD << FD->isConsteval();
18263 if (auto Context =
18264 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18265 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18266 << Context->Decl;
18267 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18268 }
18269 if (!FD->isConsteval())
18270 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18271 for (auto &Note : Notes)
18272 SemaRef.Diag(Note.first, Note.second);
18273 return;
18274 }
18275 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
18276}
18277
18278static void RemoveNestedImmediateInvocation(
18279 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18280 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18281 struct ComplexRemove : TreeTransform<ComplexRemove> {
18282 using Base = TreeTransform<ComplexRemove>;
18283 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18284 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18285 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18286 CurrentII;
18287 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18288 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18289 SmallVector<Sema::ImmediateInvocationCandidate,
18290 4>::reverse_iterator Current)
18291 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18292 void RemoveImmediateInvocation(ConstantExpr* E) {
18293 auto It = std::find_if(CurrentII, IISet.rend(),
18294 [E](Sema::ImmediateInvocationCandidate Elem) {
18295 return Elem.getPointer() == E;
18296 });
18297 // It is possible that some subexpression of the current immediate
18298 // invocation was handled from another expression evaluation context. Do
18299 // not handle the current immediate invocation if some of its
18300 // subexpressions failed before.
18301 if (It == IISet.rend()) {
18302 if (SemaRef.FailedImmediateInvocations.contains(E))
18303 CurrentII->setInt(1);
18304 } else {
18305 It->setInt(1); // Mark as deleted
18306 }
18307 }
18308 ExprResult TransformConstantExpr(ConstantExpr *E) {
18309 if (!E->isImmediateInvocation())
18310 return Base::TransformConstantExpr(E);
18311 RemoveImmediateInvocation(E);
18312 return Base::TransformExpr(E->getSubExpr());
18313 }
18314 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18315 /// we need to remove its DeclRefExpr from the DRSet.
18316 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18317 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18318 return Base::TransformCXXOperatorCallExpr(E);
18319 }
18320 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
18321 /// here.
18322 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18323 if (!Init)
18324 return Init;
18325 /// ConstantExpr are the first layer of implicit node to be removed so if
18326 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18327 if (auto *CE = dyn_cast<ConstantExpr>(Init))
18328 if (CE->isImmediateInvocation())
18329 RemoveImmediateInvocation(CE);
18330 return Base::TransformInitializer(Init, NotCopyInit);
18331 }
18332 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18333 DRSet.erase(E);
18334 return E;
18335 }
18336 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18337 // Do not rebuild lambdas to avoid creating a new type.
18338 // Lambdas have already been processed inside their eval context.
18339 return E;
18340 }
18341 bool AlwaysRebuild() { return false; }
18342 bool ReplacingOriginal() { return true; }
18343 bool AllowSkippingCXXConstructExpr() {
18344 bool Res = AllowSkippingFirstCXXConstructExpr;
18345 AllowSkippingFirstCXXConstructExpr = true;
18346 return Res;
18347 }
18348 bool AllowSkippingFirstCXXConstructExpr = true;
18349 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18350 Rec.ImmediateInvocationCandidates, It);
18351
18352 /// CXXConstructExpr with a single argument are getting skipped by
18353 /// TreeTransform in some situtation because they could be implicit. This
18354 /// can only occur for the top-level CXXConstructExpr because it is used
18355 /// nowhere in the expression being transformed therefore will not be rebuilt.
18356 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18357 /// skipping the first CXXConstructExpr.
18358 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18359 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18360
18361 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18362 // The result may not be usable in case of previous compilation errors.
18363 // In this case evaluation of the expression may result in crash so just
18364 // don't do anything further with the result.
18365 if (Res.isUsable()) {
18366 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
18367 It->getPointer()->setSubExpr(Res.get());
18368 }
18369}
18370
18371static void
18372HandleImmediateInvocations(Sema &SemaRef,
18373 Sema::ExpressionEvaluationContextRecord &Rec) {
18374 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18375 Rec.ReferenceToConsteval.size() == 0) ||
18376 SemaRef.RebuildingImmediateInvocation)
18377 return;
18378
18379 /// When we have more than 1 ImmediateInvocationCandidates or previously
18380 /// failed immediate invocations, we need to check for nested
18381 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18382 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18383 /// invocation.
18384 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18385 !SemaRef.FailedImmediateInvocations.empty()) {
18386
18387 /// Prevent sema calls during the tree transform from adding pointers that
18388 /// are already in the sets.
18389 llvm::SaveAndRestore DisableIITracking(
18390 SemaRef.RebuildingImmediateInvocation, true);
18391
18392 /// Prevent diagnostic during tree transfrom as they are duplicates
18393 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18394
18395 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18396 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18397 if (!It->getInt())
18398 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18399 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18400 Rec.ReferenceToConsteval.size()) {
18401 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18402 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18403 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18404 bool VisitDeclRefExpr(DeclRefExpr *E) {
18405 DRSet.erase(E);
18406 return DRSet.size();
18407 }
18408 } Visitor(Rec.ReferenceToConsteval);
18409 Visitor.TraverseStmt(
18410 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18411 }
18412 for (auto CE : Rec.ImmediateInvocationCandidates)
18413 if (!CE.getInt())
18414 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18415 for (auto *DR : Rec.ReferenceToConsteval) {
18416 // If the expression is immediate escalating, it is not an error;
18417 // The outer context itself becomes immediate and further errors,
18418 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18419 if (DR->isImmediateEscalating())
18420 continue;
18421 auto *FD = cast<FunctionDecl>(DR->getDecl());
18422 const NamedDecl *ND = FD;
18423 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18424 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18425 ND = MD->getParent();
18426
18427 // C++23 [expr.const]/p16
18428 // An expression or conversion is immediate-escalating if it is not
18429 // initially in an immediate function context and it is [...] a
18430 // potentially-evaluated id-expression that denotes an immediate function
18431 // that is not a subexpression of an immediate invocation.
18432 bool ImmediateEscalating = false;
18433 bool IsPotentiallyEvaluated =
18434 Rec.Context ==
18435 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18436 Rec.Context ==
18437 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18438 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18439 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18440
18441 if (!Rec.InImmediateEscalatingFunctionContext ||
18442 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18443 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18444 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18445 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18446 if (auto Context =
18447 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18448 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18449 << Context->Decl;
18450 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18451 }
18452 if (FD->isImmediateEscalating() && !FD->isConsteval())
18453 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18454
18455 } else {
18456 SemaRef.MarkExpressionAsImmediateEscalating(DR);
18457 }
18458 }
18459}
18460
18461void Sema::PopExpressionEvaluationContext() {
18462 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18463 unsigned NumTypos = Rec.NumTypos;
18464
18465 if (!Rec.Lambdas.empty()) {
18466 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18467 if (!getLangOpts().CPlusPlus20 &&
18468 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18469 Rec.isUnevaluated() ||
18470 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18471 unsigned D;
18472 if (Rec.isUnevaluated()) {
18473 // C++11 [expr.prim.lambda]p2:
18474 // A lambda-expression shall not appear in an unevaluated operand
18475 // (Clause 5).
18476 D = diag::err_lambda_unevaluated_operand;
18477 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18478 // C++1y [expr.const]p2:
18479 // A conditional-expression e is a core constant expression unless the
18480 // evaluation of e, following the rules of the abstract machine, would
18481 // evaluate [...] a lambda-expression.
18482 D = diag::err_lambda_in_constant_expression;
18483 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18484 // C++17 [expr.prim.lamda]p2:
18485 // A lambda-expression shall not appear [...] in a template-argument.
18486 D = diag::err_lambda_in_invalid_context;
18487 } else
18488 llvm_unreachable("Couldn't infer lambda error message.");
18489
18490 for (const auto *L : Rec.Lambdas)
18491 Diag(L->getBeginLoc(), D);
18492 }
18493 }
18494
18495 WarnOnPendingNoDerefs(Rec);
18496 HandleImmediateInvocations(*this, Rec);
18497
18498 // Warn on any volatile-qualified simple-assignments that are not discarded-
18499 // value expressions nor unevaluated operands (those cases get removed from
18500 // this list by CheckUnusedVolatileAssignment).
18501 for (auto *BO : Rec.VolatileAssignmentLHSs)
18502 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18503 << BO->getType();
18504
18505 // When are coming out of an unevaluated context, clear out any
18506 // temporaries that we may have created as part of the evaluation of
18507 // the expression in that context: they aren't relevant because they
18508 // will never be constructed.
18509 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18510 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18511 ExprCleanupObjects.end());
18512 Cleanup = Rec.ParentCleanup;
18513 CleanupVarDeclMarking();
18514 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18515 // Otherwise, merge the contexts together.
18516 } else {
18517 Cleanup.mergeFrom(Rec.ParentCleanup);
18518 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18519 Rec.SavedMaybeODRUseExprs.end());
18520 }
18521
18522 // Pop the current expression evaluation context off the stack.
18523 ExprEvalContexts.pop_back();
18524
18525 // The global expression evaluation context record is never popped.
18526 ExprEvalContexts.back().NumTypos += NumTypos;
18527}
18528
18529void Sema::DiscardCleanupsInEvaluationContext() {
18530 ExprCleanupObjects.erase(
18531 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18532 ExprCleanupObjects.end());
18533 Cleanup.reset();
18534 MaybeODRUseExprs.clear();
18535}
18536
18537ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18538 ExprResult Result = CheckPlaceholderExpr(E);
18539 if (Result.isInvalid())
18540 return ExprError();
18541 E = Result.get();
18542 if (!E->getType()->isVariablyModifiedType())
18543 return E;
18544 return TransformToPotentiallyEvaluated(E);
18545}
18546
18547/// Are we in a context that is potentially constant evaluated per C++20
18548/// [expr.const]p12?
18549static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18550 /// C++2a [expr.const]p12:
18551 // An expression or conversion is potentially constant evaluated if it is
18552 switch (SemaRef.ExprEvalContexts.back().Context) {
18553 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18554 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18555
18556 // -- a manifestly constant-evaluated expression,
18557 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18558 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18559 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18560 // -- a potentially-evaluated expression,
18561 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18562 // -- an immediate subexpression of a braced-init-list,
18563
18564 // -- [FIXME] an expression of the form & cast-expression that occurs
18565 // within a templated entity
18566 // -- a subexpression of one of the above that is not a subexpression of
18567 // a nested unevaluated operand.
18568 return true;
18569
18570 case Sema::ExpressionEvaluationContext::Unevaluated:
18571 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18572 // Expressions in this context are never evaluated.
18573 return false;
18574 }
18575 llvm_unreachable("Invalid context");
18576}
18577
18578/// Return true if this function has a calling convention that requires mangling
18579/// in the size of the parameter pack.
18580static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18581 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18582 // we don't need parameter type sizes.
18583 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18584 if (!TT.isOSWindows() || !TT.isX86())
18585 return false;
18586
18587 // If this is C++ and this isn't an extern "C" function, parameters do not
18588 // need to be complete. In this case, C++ mangling will apply, which doesn't
18589 // use the size of the parameters.
18590 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18591 return false;
18592
18593 // Stdcall, fastcall, and vectorcall need this special treatment.
18594 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18595 switch (CC) {
18596 case CC_X86StdCall:
18597 case CC_X86FastCall:
18598 case CC_X86VectorCall:
18599 return true;
18600 default:
18601 break;
18602 }
18603 return false;
18604}
18605
18606/// Require that all of the parameter types of function be complete. Normally,
18607/// parameter types are only required to be complete when a function is called
18608/// or defined, but to mangle functions with certain calling conventions, the
18609/// mangler needs to know the size of the parameter list. In this situation,
18610/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18611/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18612/// result in a linker error. Clang doesn't implement this behavior, and instead
18613/// attempts to error at compile time.
18614static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18615 SourceLocation Loc) {
18616 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18617 FunctionDecl *FD;
18618 ParmVarDecl *Param;
18619
18620 public:
18621 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18622 : FD(FD), Param(Param) {}
18623
18624 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18625 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18626 StringRef CCName;
18627 switch (CC) {
18628 case CC_X86StdCall:
18629 CCName = "stdcall";
18630 break;
18631 case CC_X86FastCall:
18632 CCName = "fastcall";
18633 break;
18634 case CC_X86VectorCall:
18635 CCName = "vectorcall";
18636 break;
18637 default:
18638 llvm_unreachable("CC does not need mangling");
18639 }
18640
18641 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18642 << Param->getDeclName() << FD->getDeclName() << CCName;
18643 }
18644 };
18645
18646 for (ParmVarDecl *Param : FD->parameters()) {
18647 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18648 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18649 }
18650}
18651
18652namespace {
18653enum class OdrUseContext {
18654 /// Declarations in this context are not odr-used.
18655 None,
18656 /// Declarations in this context are formally odr-used, but this is a
18657 /// dependent context.
18658 Dependent,
18659 /// Declarations in this context are odr-used but not actually used (yet).
18660 FormallyOdrUsed,
18661 /// Declarations in this context are used.
18662 Used
18663};
18664}
18665
18666/// Are we within a context in which references to resolved functions or to
18667/// variables result in odr-use?
18668static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18669 OdrUseContext Result;
18670
18671 switch (SemaRef.ExprEvalContexts.back().Context) {
18672 case Sema::ExpressionEvaluationContext::Unevaluated:
18673 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18674 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18675 return OdrUseContext::None;
18676
18677 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18678 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18679 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18680 Result = OdrUseContext::Used;
18681 break;
18682
18683 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18684 Result = OdrUseContext::FormallyOdrUsed;
18685 break;
18686
18687 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18688 // A default argument formally results in odr-use, but doesn't actually
18689 // result in a use in any real sense until it itself is used.
18690 Result = OdrUseContext::FormallyOdrUsed;
18691 break;
18692 }
18693
18694 if (SemaRef.CurContext->isDependentContext())
18695 return OdrUseContext::Dependent;
18696
18697 return Result;
18698}
18699
18700static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18701 if (!Func->isConstexpr())
18702 return false;
18703
18704 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18705 return true;
18706 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18707 return CCD && CCD->getInheritedConstructor();
18708}
18709
18710/// Mark a function referenced, and check whether it is odr-used
18711/// (C++ [basic.def.odr]p2, C99 6.9p3)
18712void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18713 bool MightBeOdrUse) {
18714 assert(Func && "No function?");
18715
18716 Func->setReferenced();
18717
18718 // Recursive functions aren't really used until they're used from some other
18719 // context.
18720 bool IsRecursiveCall = CurContext == Func;
18721
18722 // C++11 [basic.def.odr]p3:
18723 // A function whose name appears as a potentially-evaluated expression is
18724 // odr-used if it is the unique lookup result or the selected member of a
18725 // set of overloaded functions [...].
18726 //
18727 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18728 // can just check that here.
18729 OdrUseContext OdrUse =
18730 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18731 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18732 OdrUse = OdrUseContext::FormallyOdrUsed;
18733
18734 // Trivial default constructors and destructors are never actually used.
18735 // FIXME: What about other special members?
18736 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18737 OdrUse == OdrUseContext::Used) {
18738 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18739 if (Constructor->isDefaultConstructor())
18740 OdrUse = OdrUseContext::FormallyOdrUsed;
18741 if (isa<CXXDestructorDecl>(Func))
18742 OdrUse = OdrUseContext::FormallyOdrUsed;
18743 }
18744
18745 // C++20 [expr.const]p12:
18746 // A function [...] is needed for constant evaluation if it is [...] a
18747 // constexpr function that is named by an expression that is potentially
18748 // constant evaluated
18749 bool NeededForConstantEvaluation =
18750 isPotentiallyConstantEvaluatedContext(*this) &&
18751 isImplicitlyDefinableConstexprFunction(Func);
18752
18753 // Determine whether we require a function definition to exist, per
18754 // C++11 [temp.inst]p3:
18755 // Unless a function template specialization has been explicitly
18756 // instantiated or explicitly specialized, the function template
18757 // specialization is implicitly instantiated when the specialization is
18758 // referenced in a context that requires a function definition to exist.
18759 // C++20 [temp.inst]p7:
18760 // The existence of a definition of a [...] function is considered to
18761 // affect the semantics of the program if the [...] function is needed for
18762 // constant evaluation by an expression
18763 // C++20 [basic.def.odr]p10:
18764 // Every program shall contain exactly one definition of every non-inline
18765 // function or variable that is odr-used in that program outside of a
18766 // discarded statement
18767 // C++20 [special]p1:
18768 // The implementation will implicitly define [defaulted special members]
18769 // if they are odr-used or needed for constant evaluation.
18770 //
18771 // Note that we skip the implicit instantiation of templates that are only
18772 // used in unused default arguments or by recursive calls to themselves.
18773 // This is formally non-conforming, but seems reasonable in practice.
18774 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18775 NeededForConstantEvaluation);
18776
18777 // C++14 [temp.expl.spec]p6:
18778 // If a template [...] is explicitly specialized then that specialization
18779 // shall be declared before the first use of that specialization that would
18780 // cause an implicit instantiation to take place, in every translation unit
18781 // in which such a use occurs
18782 if (NeedDefinition &&
18783 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18784 Func->getMemberSpecializationInfo()))
18785 checkSpecializationReachability(Loc, Func);
18786
18787 if (getLangOpts().CUDA)
18788 CheckCUDACall(Loc, Func);
18789
18790 // If we need a definition, try to create one.
18791 if (NeedDefinition && !Func->getBody()) {
18792 runWithSufficientStackSpace(Loc, [&] {
18793 if (CXXConstructorDecl *Constructor =
18794 dyn_cast<CXXConstructorDecl>(Func)) {
18795 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18796 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18797 if (Constructor->isDefaultConstructor()) {
18798 if (Constructor->isTrivial() &&
18799 !Constructor->hasAttr<DLLExportAttr>())
18800 return;
18801 DefineImplicitDefaultConstructor(Loc, Constructor);
18802 } else if (Constructor->isCopyConstructor()) {
18803 DefineImplicitCopyConstructor(Loc, Constructor);
18804 } else if (Constructor->isMoveConstructor()) {
18805 DefineImplicitMoveConstructor(Loc, Constructor);
18806 }
18807 } else if (Constructor->getInheritedConstructor()) {
18808 DefineInheritingConstructor(Loc, Constructor);
18809 }
18810 } else if (CXXDestructorDecl *Destructor =
18811 dyn_cast<CXXDestructorDecl>(Func)) {
18812 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18813 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18814 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18815 return;
18816 DefineImplicitDestructor(Loc, Destructor);
18817 }
18818 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18819 MarkVTableUsed(Loc, Destructor->getParent());
18820 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18821 if (MethodDecl->isOverloadedOperator() &&
18822 MethodDecl->getOverloadedOperator() == OO_Equal) {
18823 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18824 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18825 if (MethodDecl->isCopyAssignmentOperator())
18826 DefineImplicitCopyAssignment(Loc, MethodDecl);
18827 else if (MethodDecl->isMoveAssignmentOperator())
18828 DefineImplicitMoveAssignment(Loc, MethodDecl);
18829 }
18830 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18831 MethodDecl->getParent()->isLambda()) {
18832 CXXConversionDecl *Conversion =
18833 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18834 if (Conversion->isLambdaToBlockPointerConversion())
18835 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18836 else
18837 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18838 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18839 MarkVTableUsed(Loc, MethodDecl->getParent());
18840 }
18841
18842 if (Func->isDefaulted() && !Func->isDeleted()) {
18843 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18844 if (DCK != DefaultedComparisonKind::None)
18845 DefineDefaultedComparison(Loc, Func, DCK);
18846 }
18847
18848 // Implicit instantiation of function templates and member functions of
18849 // class templates.
18850 if (Func->isImplicitlyInstantiable()) {
18851 TemplateSpecializationKind TSK =
18852 Func->getTemplateSpecializationKindForInstantiation();
18853 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18854 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18855 if (FirstInstantiation) {
18856 PointOfInstantiation = Loc;
18857 if (auto *MSI = Func->getMemberSpecializationInfo())
18858 MSI->setPointOfInstantiation(Loc);
18859 // FIXME: Notify listener.
18860 else
18861 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18862 } else if (TSK != TSK_ImplicitInstantiation) {
18863 // Use the point of use as the point of instantiation, instead of the
18864 // point of explicit instantiation (which we track as the actual point
18865 // of instantiation). This gives better backtraces in diagnostics.
18866 PointOfInstantiation = Loc;
18867 }
18868
18869 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18870 Func->isConstexpr()) {
18871 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18872 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18873 CodeSynthesisContexts.size())
18874 PendingLocalImplicitInstantiations.push_back(
18875 std::make_pair(Func, PointOfInstantiation));
18876 else if (Func->isConstexpr())
18877 // Do not defer instantiations of constexpr functions, to avoid the
18878 // expression evaluator needing to call back into Sema if it sees a
18879 // call to such a function.
18880 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18881 else {
18882 Func->setInstantiationIsPending(true);
18883 PendingInstantiations.push_back(
18884 std::make_pair(Func, PointOfInstantiation));
18885 // Notify the consumer that a function was implicitly instantiated.
18886 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18887 }
18888 }
18889 } else {
18890 // Walk redefinitions, as some of them may be instantiable.
18891 for (auto *i : Func->redecls()) {
18892 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18893 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18894 }
18895 }
18896 });
18897 }
18898
18899 // If a constructor was defined in the context of a default parameter
18900 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18901 // context), its initializers may not be referenced yet.
18902 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18903 EnterExpressionEvaluationContext EvalContext(
18904 *this,
18905 Constructor->isImmediateFunction()
18906 ? ExpressionEvaluationContext::ImmediateFunctionContext
18907 : ExpressionEvaluationContext::PotentiallyEvaluated,
18908 Constructor);
18909 for (CXXCtorInitializer *Init : Constructor->inits()) {
18910 if (Init->isInClassMemberInitializer())
18911 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18912 MarkDeclarationsReferencedInExpr(Init->getInit());
18913 });
18914 }
18915 }
18916
18917 // C++14 [except.spec]p17:
18918 // An exception-specification is considered to be needed when:
18919 // - the function is odr-used or, if it appears in an unevaluated operand,
18920 // would be odr-used if the expression were potentially-evaluated;
18921 //
18922 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18923 // function is a pure virtual function we're calling, and in that case the
18924 // function was selected by overload resolution and we need to resolve its
18925 // exception specification for a different reason.
18926 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18927 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18928 ResolveExceptionSpec(Loc, FPT);
18929
18930 // If this is the first "real" use, act on that.
18931 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18932 // Keep track of used but undefined functions.
18933 if (!Func->isDefined()) {
18934 if (mightHaveNonExternalLinkage(Func))
18935 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18936 else if (Func->getMostRecentDecl()->isInlined() &&
18937 !LangOpts.GNUInline &&
18938 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18939 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18940 else if (isExternalWithNoLinkageType(Func))
18941 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18942 }
18943
18944 // Some x86 Windows calling conventions mangle the size of the parameter
18945 // pack into the name. Computing the size of the parameters requires the
18946 // parameter types to be complete. Check that now.
18947 if (funcHasParameterSizeMangling(*this, Func))
18948 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18949
18950 // In the MS C++ ABI, the compiler emits destructor variants where they are
18951 // used. If the destructor is used here but defined elsewhere, mark the
18952 // virtual base destructors referenced. If those virtual base destructors
18953 // are inline, this will ensure they are defined when emitting the complete
18954 // destructor variant. This checking may be redundant if the destructor is
18955 // provided later in this TU.
18956 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18957 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18958 CXXRecordDecl *Parent = Dtor->getParent();
18959 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18960 CheckCompleteDestructorVariant(Loc, Dtor);
18961 }
18962 }
18963
18964 Func->markUsed(Context);
18965 }
18966}
18967
18968/// Directly mark a variable odr-used. Given a choice, prefer to use
18969/// MarkVariableReferenced since it does additional checks and then
18970/// calls MarkVarDeclODRUsed.
18971/// If the variable must be captured:
18972/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18973/// - else capture it in the DeclContext that maps to the
18974/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18975static void
18976MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
18977 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18978 // Keep track of used but undefined variables.
18979 // FIXME: We shouldn't suppress this warning for static data members.
18980 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18981 assert(Var && "expected a capturable variable");
18982
18983 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18984 (!Var->isExternallyVisible() || Var->isInline() ||
18985 SemaRef.isExternalWithNoLinkageType(Var)) &&
18986 !(Var->isStaticDataMember() && Var->hasInit())) {
18987 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18988 if (old.isInvalid())
18989 old = Loc;
18990 }
18991 QualType CaptureType, DeclRefType;
18992 if (SemaRef.LangOpts.OpenMP)
18993 SemaRef.tryCaptureOpenMPLambdas(V);
18994 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
18995 /*EllipsisLoc*/ SourceLocation(),
18996 /*BuildAndDiagnose*/ true, CaptureType,
18997 DeclRefType, FunctionScopeIndexToStopAt);
18998
18999 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19000 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19001 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
19002 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
19003 if (VarTarget == Sema::CVT_Host &&
19004 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
19005 UserTarget == Sema::CFT_Global)) {
19006 // Diagnose ODR-use of host global variables in device functions.
19007 // Reference of device global variables in host functions is allowed
19008 // through shadow variables therefore it is not diagnosed.
19009 if (SemaRef.LangOpts.CUDAIsDevice) {
19010 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19011 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19012 SemaRef.targetDiag(Var->getLocation(),
19013 Var->getType().isConstQualified()
19014 ? diag::note_cuda_const_var_unpromoted
19015 : diag::note_cuda_host_var);
19016 }
19017 } else if (VarTarget == Sema::CVT_Device &&
19018 (UserTarget == Sema::CFT_Host ||
19019 UserTarget == Sema::CFT_HostDevice)) {
19020 // Record a CUDA/HIP device side variable if it is ODR-used
19021 // by host code. This is done conservatively, when the variable is
19022 // referenced in any of the following contexts:
19023 // - a non-function context
19024 // - a host function
19025 // - a host device function
19026 // This makes the ODR-use of the device side variable by host code to
19027 // be visible in the device compilation for the compiler to be able to
19028 // emit template variables instantiated by host code only and to
19029 // externalize the static device side variable ODR-used by host code.
19030 if (!Var->hasExternalStorage())
19031 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
19032 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
19033 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
19034 }
19035 }
19036
19037 V->markUsed(SemaRef.Context);
19038}
19039
19040void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19041 SourceLocation Loc,
19042 unsigned CapturingScopeIndex) {
19043 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19044}
19045
19046void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
19047 ValueDecl *var) {
19048 DeclContext *VarDC = var->getDeclContext();
19049
19050 // If the parameter still belongs to the translation unit, then
19051 // we're actually just using one parameter in the declaration of
19052 // the next.
19053 if (isa<ParmVarDecl>(var) &&
19054 isa<TranslationUnitDecl>(VarDC))
19055 return;
19056
19057 // For C code, don't diagnose about capture if we're not actually in code
19058 // right now; it's impossible to write a non-constant expression outside of
19059 // function context, so we'll get other (more useful) diagnostics later.
19060 //
19061 // For C++, things get a bit more nasty... it would be nice to suppress this
19062 // diagnostic for certain cases like using a local variable in an array bound
19063 // for a member of a local class, but the correct predicate is not obvious.
19064 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19065 return;
19066
19067 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19068 unsigned ContextKind = 3; // unknown
19069 if (isa<CXXMethodDecl>(VarDC) &&
19070 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19071 ContextKind = 2;
19072 } else if (isa<FunctionDecl>(VarDC)) {
19073 ContextKind = 0;
19074 } else if (isa<BlockDecl>(VarDC)) {
19075 ContextKind = 1;
19076 }
19077
19078 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19079 << var << ValueKind << ContextKind << VarDC;
19080 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19081 << var;
19082
19083 // FIXME: Add additional diagnostic info about class etc. which prevents
19084 // capture.
19085}
19086
19087static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19088 ValueDecl *Var,
19089 bool &SubCapturesAreNested,
19090 QualType &CaptureType,
19091 QualType &DeclRefType) {
19092 // Check whether we've already captured it.
19093 if (CSI->CaptureMap.count(Var)) {
19094 // If we found a capture, any subcaptures are nested.
19095 SubCapturesAreNested = true;
19096
19097 // Retrieve the capture type for this variable.
19098 CaptureType = CSI->getCapture(Var).getCaptureType();
19099
19100 // Compute the type of an expression that refers to this variable.
19101 DeclRefType = CaptureType.getNonReferenceType();
19102
19103 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19104 // are mutable in the sense that user can change their value - they are
19105 // private instances of the captured declarations.
19106 const Capture &Cap = CSI->getCapture(Var);
19107 if (Cap.isCopyCapture() &&
19108 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
19109 !(isa<CapturedRegionScopeInfo>(CSI) &&
19110 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19111 DeclRefType.addConst();
19112 return true;
19113 }
19114 return false;
19115}
19116
19117// Only block literals, captured statements, and lambda expressions can
19118// capture; other scopes don't work.
19119static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19120 ValueDecl *Var,
19121 SourceLocation Loc,
19122 const bool Diagnose,
19123 Sema &S) {
19124 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
19125 return getLambdaAwareParentOfDeclContext(DC);
19126
19127 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19128 if (Underlying) {
19129 if (Underlying->hasLocalStorage() && Diagnose)
19130 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19131 }
19132 return nullptr;
19133}
19134
19135// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19136// certain types of variables (unnamed, variably modified types etc.)
19137// so check for eligibility.
19138static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19139 SourceLocation Loc, const bool Diagnose,
19140 Sema &S) {
19141
19142 assert((isa<VarDecl, BindingDecl>(Var)) &&
19143 "Only variables and structured bindings can be captured");
19144
19145 bool IsBlock = isa<BlockScopeInfo>(CSI);
19146 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19147
19148 // Lambdas are not allowed to capture unnamed variables
19149 // (e.g. anonymous unions).
19150 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19151 // assuming that's the intent.
19152 if (IsLambda && !Var->getDeclName()) {
19153 if (Diagnose) {
19154 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19155 S.Diag(Var->getLocation(), diag::note_declared_at);
19156 }
19157 return false;
19158 }
19159
19160 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19161 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19162 if (Diagnose) {
19163 S.Diag(Loc, diag::err_ref_vm_type);
19164 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19165 }
19166 return false;
19167 }
19168 // Prohibit structs with flexible array members too.
19169 // We cannot capture what is in the tail end of the struct.
19170 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
19171 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
19172 if (Diagnose) {
19173 if (IsBlock)
19174 S.Diag(Loc, diag::err_ref_flexarray_type);
19175 else
19176 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19177 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19178 }
19179 return false;
19180 }
19181 }
19182 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19183 // Lambdas and captured statements are not allowed to capture __block
19184 // variables; they don't support the expected semantics.
19185 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19186 if (Diagnose) {
19187 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19188 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19189 }
19190 return false;
19191 }
19192 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19193 if (S.getLangOpts().OpenCL && IsBlock &&
19194 Var->getType()->isBlockPointerType()) {
19195 if (Diagnose)
19196 S.Diag(Loc, diag::err_opencl_block_ref_block);
19197 return false;
19198 }
19199
19200 if (isa<BindingDecl>(Var)) {
19201 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19202 if (Diagnose)
19203 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19204 return false;
19205 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19206 S.Diag(Loc, S.LangOpts.CPlusPlus20
19207 ? diag::warn_cxx17_compat_capture_binding
19208 : diag::ext_capture_binding)
19209 << Var;
19210 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19211 }
19212 }
19213
19214 return true;
19215}
19216
19217// Returns true if the capture by block was successful.
19218static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19219 SourceLocation Loc, const bool BuildAndDiagnose,
19220 QualType &CaptureType, QualType &DeclRefType,
19221 const bool Nested, Sema &S, bool Invalid) {
19222 bool ByRef = false;
19223
19224 // Blocks are not allowed to capture arrays, excepting OpenCL.
19225 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19226 // (decayed to pointers).
19227 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19228 if (BuildAndDiagnose) {
19229 S.Diag(Loc, diag::err_ref_array_type);
19230 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19231 Invalid = true;
19232 } else {
19233 return false;
19234 }
19235 }
19236
19237 // Forbid the block-capture of autoreleasing variables.
19238 if (!Invalid &&
19239 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19240 if (BuildAndDiagnose) {
19241 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19242 << /*block*/ 0;
19243 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19244 Invalid = true;
19245 } else {
19246 return false;
19247 }
19248 }
19249
19250 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19251 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19252 QualType PointeeTy = PT->getPointeeType();
19253
19254 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19255 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19256 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19257 if (BuildAndDiagnose) {
19258 SourceLocation VarLoc = Var->getLocation();
19259 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19260 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19261 }
19262 }
19263 }
19264
19265 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19266 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19267 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
19268 // Block capture by reference does not change the capture or
19269 // declaration reference types.
19270 ByRef = true;
19271 } else {
19272 // Block capture by copy introduces 'const'.
19273 CaptureType = CaptureType.getNonReferenceType().withConst();
19274 DeclRefType = CaptureType;
19275 }
19276
19277 // Actually capture the variable.
19278 if (BuildAndDiagnose)
19279 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19280 CaptureType, Invalid);
19281
19282 return !Invalid;
19283}
19284
19285/// Capture the given variable in the captured region.
19286static bool captureInCapturedRegion(
19287 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19288 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19289 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
19290 bool IsTopScope, Sema &S, bool Invalid) {
19291 // By default, capture variables by reference.
19292 bool ByRef = true;
19293 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19294 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19295 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19296 // Using an LValue reference type is consistent with Lambdas (see below).
19297 if (S.isOpenMPCapturedDecl(Var)) {
19298 bool HasConst = DeclRefType.isConstQualified();
19299 DeclRefType = DeclRefType.getUnqualifiedType();
19300 // Don't lose diagnostics about assignments to const.
19301 if (HasConst)
19302 DeclRefType.addConst();
19303 }
19304 // Do not capture firstprivates in tasks.
19305 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
19306 OMPC_unknown)
19307 return true;
19308 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19309 RSI->OpenMPCaptureLevel);
19310 }
19311
19312 if (ByRef)
19313 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19314 else
19315 CaptureType = DeclRefType;
19316
19317 // Actually capture the variable.
19318 if (BuildAndDiagnose)
19319 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19320 Loc, SourceLocation(), CaptureType, Invalid);
19321
19322 return !Invalid;
19323}
19324
19325/// Capture the given variable in the lambda.
19326static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19327 SourceLocation Loc, const bool BuildAndDiagnose,
19328 QualType &CaptureType, QualType &DeclRefType,
19329 const bool RefersToCapturedVariable,
19330 const Sema::TryCaptureKind Kind,
19331 SourceLocation EllipsisLoc, const bool IsTopScope,
19332 Sema &S, bool Invalid) {
19333 // Determine whether we are capturing by reference or by value.
19334 bool ByRef = false;
19335 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19336 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19337 } else {
19338 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19339 }
19340
19341 BindingDecl *BD = dyn_cast<BindingDecl>(Var);
19342 // FIXME: We should support capturing structured bindings in OpenMP.
19343 if (!Invalid && BD && S.LangOpts.OpenMP) {
19344 if (BuildAndDiagnose) {
19345 S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
19346 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19347 }
19348 Invalid = true;
19349 }
19350
19351 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19352 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19353 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19354 Invalid = true;
19355 }
19356
19357 // Compute the type of the field that will capture this variable.
19358 if (ByRef) {
19359 // C++11 [expr.prim.lambda]p15:
19360 // An entity is captured by reference if it is implicitly or
19361 // explicitly captured but not captured by copy. It is
19362 // unspecified whether additional unnamed non-static data
19363 // members are declared in the closure type for entities
19364 // captured by reference.
19365 //
19366 // FIXME: It is not clear whether we want to build an lvalue reference
19367 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19368 // to do the former, while EDG does the latter. Core issue 1249 will
19369 // clarify, but for now we follow GCC because it's a more permissive and
19370 // easily defensible position.
19371 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19372 } else {
19373 // C++11 [expr.prim.lambda]p14:
19374 // For each entity captured by copy, an unnamed non-static
19375 // data member is declared in the closure type. The
19376 // declaration order of these members is unspecified. The type
19377 // of such a data member is the type of the corresponding
19378 // captured entity if the entity is not a reference to an
19379 // object, or the referenced type otherwise. [Note: If the
19380 // captured entity is a reference to a function, the
19381 // corresponding data member is also a reference to a
19382 // function. - end note ]
19383 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19384 if (!RefType->getPointeeType()->isFunctionType())
19385 CaptureType = RefType->getPointeeType();
19386 }
19387
19388 // Forbid the lambda copy-capture of autoreleasing variables.
19389 if (!Invalid &&
19390 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19391 if (BuildAndDiagnose) {
19392 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19393 S.Diag(Var->getLocation(), diag::note_previous_decl)
19394 << Var->getDeclName();
19395 Invalid = true;
19396 } else {
19397 return false;
19398 }
19399 }
19400
19401 // Make sure that by-copy captures are of a complete and non-abstract type.
19402 if (!Invalid && BuildAndDiagnose) {
19403 if (!CaptureType->isDependentType() &&
19404 S.RequireCompleteSizedType(
19405 Loc, CaptureType,
19406 diag::err_capture_of_incomplete_or_sizeless_type,
19407 Var->getDeclName()))
19408 Invalid = true;
19409 else if (S.RequireNonAbstractType(Loc, CaptureType,
19410 diag::err_capture_of_abstract_type))
19411 Invalid = true;
19412 }
19413 }
19414
19415 // Compute the type of a reference to this captured variable.
19416 if (ByRef)
19417 DeclRefType = CaptureType.getNonReferenceType();
19418 else {
19419 // C++ [expr.prim.lambda]p5:
19420 // The closure type for a lambda-expression has a public inline
19421 // function call operator [...]. This function call operator is
19422 // declared const (9.3.1) if and only if the lambda-expression's
19423 // parameter-declaration-clause is not followed by mutable.
19424 DeclRefType = CaptureType.getNonReferenceType();
19425 if (!LSI->Mutable && !CaptureType->isReferenceType())
19426 DeclRefType.addConst();
19427 }
19428
19429 // Add the capture.
19430 if (BuildAndDiagnose)
19431 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19432 Loc, EllipsisLoc, CaptureType, Invalid);
19433
19434 return !Invalid;
19435}
19436
19437static bool canCaptureVariableByCopy(ValueDecl *Var,
19438 const ASTContext &Context) {
19439 // Offer a Copy fix even if the type is dependent.
19440 if (Var->getType()->isDependentType())
19441 return true;
19442 QualType T = Var->getType().getNonReferenceType();
19443 if (T.isTriviallyCopyableType(Context))
19444 return true;
19445 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19446
19447 if (!(RD = RD->getDefinition()))
19448 return false;
19449 if (RD->hasSimpleCopyConstructor())
19450 return true;
19451 if (RD->hasUserDeclaredCopyConstructor())
19452 for (CXXConstructorDecl *Ctor : RD->ctors())
19453 if (Ctor->isCopyConstructor())
19454 return !Ctor->isDeleted();
19455 }
19456 return false;
19457}
19458
19459/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19460/// default capture. Fixes may be omitted if they aren't allowed by the
19461/// standard, for example we can't emit a default copy capture fix-it if we
19462/// already explicitly copy capture capture another variable.
19463static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19464 ValueDecl *Var) {
19465 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19466 // Don't offer Capture by copy of default capture by copy fixes if Var is
19467 // known not to be copy constructible.
19468 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19469
19470 SmallString<32> FixBuffer;
19471 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19472 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19473 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19474 if (ShouldOfferCopyFix) {
19475 // Offer fixes to insert an explicit capture for the variable.
19476 // [] -> [VarName]
19477 // [OtherCapture] -> [OtherCapture, VarName]
19478 FixBuffer.assign({Separator, Var->getName()});
19479 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19480 << Var << /*value*/ 0
19481 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19482 }
19483 // As above but capture by reference.
19484 FixBuffer.assign({Separator, "&", Var->getName()});
19485 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19486 << Var << /*reference*/ 1
19487 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19488 }
19489
19490 // Only try to offer default capture if there are no captures excluding this
19491 // and init captures.
19492 // [this]: OK.
19493 // [X = Y]: OK.
19494 // [&A, &B]: Don't offer.
19495 // [A, B]: Don't offer.
19496 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19497 return !C.isThisCapture() && !C.isInitCapture();
19498 }))
19499 return;
19500
19501 // The default capture specifiers, '=' or '&', must appear first in the
19502 // capture body.
19503 SourceLocation DefaultInsertLoc =
19504 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19505
19506 if (ShouldOfferCopyFix) {
19507 bool CanDefaultCopyCapture = true;
19508 // [=, *this] OK since c++17
19509 // [=, this] OK since c++20
19510 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19511 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19512 ? LSI->getCXXThisCapture().isCopyCapture()
19513 : false;
19514 // We can't use default capture by copy if any captures already specified
19515 // capture by copy.
19516 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19517 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19518 })) {
19519 FixBuffer.assign({"=", Separator});
19520 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19521 << /*value*/ 0
19522 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19523 }
19524 }
19525
19526 // We can't use default capture by reference if any captures already specified
19527 // capture by reference.
19528 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19529 return !C.isInitCapture() && C.isReferenceCapture() &&
19530 !C.isThisCapture();
19531 })) {
19532 FixBuffer.assign({"&", Separator});
19533 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19534 << /*reference*/ 1
19535 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19536 }
19537}
19538
19539bool Sema::tryCaptureVariable(
19540 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19541 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19542 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19543 // An init-capture is notionally from the context surrounding its
19544 // declaration, but its parent DC is the lambda class.
19545 DeclContext *VarDC = Var->getDeclContext();
19546 DeclContext *DC = CurContext;
19547
19548 // tryCaptureVariable is called every time a DeclRef is formed,
19549 // it can therefore have non-negigible impact on performances.
19550 // For local variables and when there is no capturing scope,
19551 // we can bailout early.
19552 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19553 return true;
19554
19555 const auto *VD = dyn_cast<VarDecl>(Var);
19556 if (VD) {
19557 if (VD->isInitCapture())
19558 VarDC = VarDC->getParent();
19559 } else {
19560 VD = Var->getPotentiallyDecomposedVarDecl();
19561 }
19562 assert(VD && "Cannot capture a null variable");
19563
19564 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19565 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19566 // We need to sync up the Declaration Context with the
19567 // FunctionScopeIndexToStopAt
19568 if (FunctionScopeIndexToStopAt) {
19569 unsigned FSIndex = FunctionScopes.size() - 1;
19570 while (FSIndex != MaxFunctionScopesIndex) {
19571 DC = getLambdaAwareParentOfDeclContext(DC);
19572 --FSIndex;
19573 }
19574 }
19575
19576 // Capture global variables if it is required to use private copy of this
19577 // variable.
19578 bool IsGlobal = !VD->hasLocalStorage();
19579 if (IsGlobal &&
19580 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19581 MaxFunctionScopesIndex)))
19582 return true;
19583
19584 if (isa<VarDecl>(Var))
19585 Var = cast<VarDecl>(Var->getCanonicalDecl());
19586
19587 // Walk up the stack to determine whether we can capture the variable,
19588 // performing the "simple" checks that don't depend on type. We stop when
19589 // we've either hit the declared scope of the variable or find an existing
19590 // capture of that variable. We start from the innermost capturing-entity
19591 // (the DC) and ensure that all intervening capturing-entities
19592 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19593 // declcontext can either capture the variable or have already captured
19594 // the variable.
19595 CaptureType = Var->getType();
19596 DeclRefType = CaptureType.getNonReferenceType();
19597 bool Nested = false;
19598 bool Explicit = (Kind != TryCapture_Implicit);
19599 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19600 do {
19601
19602 LambdaScopeInfo *LSI = nullptr;
19603 if (!FunctionScopes.empty())
19604 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19605 FunctionScopes[FunctionScopesIndex]);
19606
19607 bool IsInScopeDeclarationContext =
19608 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19609
19610 if (LSI && !LSI->AfterParameterList) {
19611 // This allows capturing parameters from a default value which does not
19612 // seems correct
19613 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19614 return true;
19615 }
19616 // If the variable is declared in the current context, there is no need to
19617 // capture it.
19618 if (IsInScopeDeclarationContext &&
19619 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19620 return true;
19621
19622 // When evaluating some attributes (like enable_if) we might refer to a
19623 // function parameter appertaining to the same declaration as that
19624 // attribute.
19625 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19626 Parm && Parm->getDeclContext() == DC)
19627 return true;
19628
19629 // Only block literals, captured statements, and lambda expressions can
19630 // capture; other scopes don't work.
19631 DeclContext *ParentDC =
19632 !IsInScopeDeclarationContext
19633 ? DC->getParent()
19634 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19635 BuildAndDiagnose, *this);
19636 // We need to check for the parent *first* because, if we *have*
19637 // private-captured a global variable, we need to recursively capture it in
19638 // intermediate blocks, lambdas, etc.
19639 if (!ParentDC) {
19640 if (IsGlobal) {
19641 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19642 break;
19643 }
19644 return true;
19645 }
19646
19647 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19648 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19649
19650 // Check whether we've already captured it.
19651 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19652 DeclRefType)) {
19653 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19654 break;
19655 }
19656 // If we are instantiating a generic lambda call operator body,
19657 // we do not want to capture new variables. What was captured
19658 // during either a lambdas transformation or initial parsing
19659 // should be used.
19660 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19661 if (BuildAndDiagnose) {
19662 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19663 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19664 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19665 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19666 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19667 buildLambdaCaptureFixit(*this, LSI, Var);
19668 } else
19669 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19670 }
19671 return true;
19672 }
19673
19674 // Try to capture variable-length arrays types.
19675 if (Var->getType()->isVariablyModifiedType()) {
19676 // We're going to walk down into the type and look for VLA
19677 // expressions.
19678 QualType QTy = Var->getType();
19679 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19680 QTy = PVD->getOriginalType();
19681 captureVariablyModifiedType(Context, QTy, CSI);
19682 }
19683
19684 if (getLangOpts().OpenMP) {
19685 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19686 // OpenMP private variables should not be captured in outer scope, so
19687 // just break here. Similarly, global variables that are captured in a
19688 // target region should not be captured outside the scope of the region.
19689 if (RSI->CapRegionKind == CR_OpenMP) {
19690 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19691 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19692 // If the variable is private (i.e. not captured) and has variably
19693 // modified type, we still need to capture the type for correct
19694 // codegen in all regions, associated with the construct. Currently,
19695 // it is captured in the innermost captured region only.
19696 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19697 Var->getType()->isVariablyModifiedType()) {
19698 QualType QTy = Var->getType();
19699 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19700 QTy = PVD->getOriginalType();
19701 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19702 I < E; ++I) {
19703 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19704 FunctionScopes[FunctionScopesIndex - I]);
19705 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19706 "Wrong number of captured regions associated with the "
19707 "OpenMP construct.");
19708 captureVariablyModifiedType(Context, QTy, OuterRSI);
19709 }
19710 }
19711 bool IsTargetCap =
19712 IsOpenMPPrivateDecl != OMPC_private &&
19713 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19714 RSI->OpenMPCaptureLevel);
19715 // Do not capture global if it is not privatized in outer regions.
19716 bool IsGlobalCap =
19717 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19718 RSI->OpenMPCaptureLevel);
19719
19720 // When we detect target captures we are looking from inside the
19721 // target region, therefore we need to propagate the capture from the
19722 // enclosing region. Therefore, the capture is not initially nested.
19723 if (IsTargetCap)
19724 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19725
19726 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19727 (IsGlobal && !IsGlobalCap)) {
19728 Nested = !IsTargetCap;
19729 bool HasConst = DeclRefType.isConstQualified();
19730 DeclRefType = DeclRefType.getUnqualifiedType();
19731 // Don't lose diagnostics about assignments to const.
19732 if (HasConst)
19733 DeclRefType.addConst();
19734 CaptureType = Context.getLValueReferenceType(DeclRefType);
19735 break;
19736 }
19737 }
19738 }
19739 }
19740 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19741 // No capture-default, and this is not an explicit capture
19742 // so cannot capture this variable.
19743 if (BuildAndDiagnose) {
19744 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19745 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19746 auto *LSI = cast<LambdaScopeInfo>(CSI);
19747 if (LSI->Lambda) {
19748 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19749 buildLambdaCaptureFixit(*this, LSI, Var);
19750 }
19751 // FIXME: If we error out because an outer lambda can not implicitly
19752 // capture a variable that an inner lambda explicitly captures, we
19753 // should have the inner lambda do the explicit capture - because
19754 // it makes for cleaner diagnostics later. This would purely be done
19755 // so that the diagnostic does not misleadingly claim that a variable
19756 // can not be captured by a lambda implicitly even though it is captured
19757 // explicitly. Suggestion:
19758 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19759 // at the function head
19760 // - cache the StartingDeclContext - this must be a lambda
19761 // - captureInLambda in the innermost lambda the variable.
19762 }
19763 return true;
19764 }
19765 Explicit = false;
19766 FunctionScopesIndex--;
19767 if (IsInScopeDeclarationContext)
19768 DC = ParentDC;
19769 } while (!VarDC->Equals(DC));
19770
19771 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19772 // computing the type of the capture at each step, checking type-specific
19773 // requirements, and adding captures if requested.
19774 // If the variable had already been captured previously, we start capturing
19775 // at the lambda nested within that one.
19776 bool Invalid = false;
19777 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19778 ++I) {
19779 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19780
19781 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19782 // certain types of variables (unnamed, variably modified types etc.)
19783 // so check for eligibility.
19784 if (!Invalid)
19785 Invalid =
19786 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19787
19788 // After encountering an error, if we're actually supposed to capture, keep
19789 // capturing in nested contexts to suppress any follow-on diagnostics.
19790 if (Invalid && !BuildAndDiagnose)
19791 return true;
19792
19793 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19794 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19795 DeclRefType, Nested, *this, Invalid);
19796 Nested = true;
19797 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19798 Invalid = !captureInCapturedRegion(
19799 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19800 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19801 Nested = true;
19802 } else {
19803 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19804 Invalid =
19805 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19806 DeclRefType, Nested, Kind, EllipsisLoc,
19807 /*IsTopScope*/ I == N - 1, *this, Invalid);
19808 Nested = true;
19809 }
19810
19811 if (Invalid && !BuildAndDiagnose)
19812 return true;
19813 }
19814 return Invalid;
19815}
19816
19817bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19818 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19819 QualType CaptureType;
19820 QualType DeclRefType;
19821 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19822 /*BuildAndDiagnose=*/true, CaptureType,
19823 DeclRefType, nullptr);
19824}
19825
19826bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19827 QualType CaptureType;
19828 QualType DeclRefType;
19829 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19830 /*BuildAndDiagnose=*/false, CaptureType,
19831 DeclRefType, nullptr);
19832}
19833
19834QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19835 QualType CaptureType;
19836 QualType DeclRefType;
19837
19838 // Determine whether we can capture this variable.
19839 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19840 /*BuildAndDiagnose=*/false, CaptureType,
19841 DeclRefType, nullptr))
19842 return QualType();
19843
19844 return DeclRefType;
19845}
19846
19847namespace {
19848// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19849// The produced TemplateArgumentListInfo* points to data stored within this
19850// object, so should only be used in contexts where the pointer will not be
19851// used after the CopiedTemplateArgs object is destroyed.
19852class CopiedTemplateArgs {
19853 bool HasArgs;
19854 TemplateArgumentListInfo TemplateArgStorage;
19855public:
19856 template<typename RefExpr>
19857 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19858 if (HasArgs)
19859 E->copyTemplateArgumentsInto(TemplateArgStorage);
19860 }
19861 operator TemplateArgumentListInfo*()
19862#ifdef __has_cpp_attribute
19863#if __has_cpp_attribute(clang::lifetimebound)
19864 [[clang::lifetimebound]]
19865#endif
19866#endif
19867 {
19868 return HasArgs ? &TemplateArgStorage : nullptr;
19869 }
19870};
19871}
19872
19873/// Walk the set of potential results of an expression and mark them all as
19874/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19875///
19876/// \return A new expression if we found any potential results, ExprEmpty() if
19877/// not, and ExprError() if we diagnosed an error.
19878static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19879 NonOdrUseReason NOUR) {
19880 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19881 // an object that satisfies the requirements for appearing in a
19882 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19883 // is immediately applied." This function handles the lvalue-to-rvalue
19884 // conversion part.
19885 //
19886 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19887 // transform it into the relevant kind of non-odr-use node and rebuild the
19888 // tree of nodes leading to it.
19889 //
19890 // This is a mini-TreeTransform that only transforms a restricted subset of
19891 // nodes (and only certain operands of them).
19892
19893 // Rebuild a subexpression.
19894 auto Rebuild = [&](Expr *Sub) {
19895 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19896 };
19897
19898 // Check whether a potential result satisfies the requirements of NOUR.
19899 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19900 // Any entity other than a VarDecl is always odr-used whenever it's named
19901 // in a potentially-evaluated expression.
19902 auto *VD = dyn_cast<VarDecl>(D);
19903 if (!VD)
19904 return true;
19905
19906 // C++2a [basic.def.odr]p4:
19907 // A variable x whose name appears as a potentially-evalauted expression
19908 // e is odr-used by e unless
19909 // -- x is a reference that is usable in constant expressions, or
19910 // -- x is a variable of non-reference type that is usable in constant
19911 // expressions and has no mutable subobjects, and e is an element of
19912 // the set of potential results of an expression of
19913 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19914 // conversion is applied, or
19915 // -- x is a variable of non-reference type, and e is an element of the
19916 // set of potential results of a discarded-value expression to which
19917 // the lvalue-to-rvalue conversion is not applied
19918 //
19919 // We check the first bullet and the "potentially-evaluated" condition in
19920 // BuildDeclRefExpr. We check the type requirements in the second bullet
19921 // in CheckLValueToRValueConversionOperand below.
19922 switch (NOUR) {
19923 case NOUR_None:
19924 case NOUR_Unevaluated:
19925 llvm_unreachable("unexpected non-odr-use-reason");
19926
19927 case NOUR_Constant:
19928 // Constant references were handled when they were built.
19929 if (VD->getType()->isReferenceType())
19930 return true;
19931 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19932 if (RD->hasMutableFields())
19933 return true;
19934 if (!VD->isUsableInConstantExpressions(S.Context))
19935 return true;
19936 break;
19937
19938 case NOUR_Discarded:
19939 if (VD->getType()->isReferenceType())
19940 return true;
19941 break;
19942 }
19943 return false;
19944 };
19945
19946 // Mark that this expression does not constitute an odr-use.
19947 auto MarkNotOdrUsed = [&] {
19948 S.MaybeODRUseExprs.remove(E);
19949 if (LambdaScopeInfo *LSI = S.getCurLambda())
19950 LSI->markVariableExprAsNonODRUsed(E);
19951 };
19952
19953 // C++2a [basic.def.odr]p2:
19954 // The set of potential results of an expression e is defined as follows:
19955 switch (E->getStmtClass()) {
19956 // -- If e is an id-expression, ...
19957 case Expr::DeclRefExprClass: {
19958 auto *DRE = cast<DeclRefExpr>(E);
19959 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19960 break;
19961
19962 // Rebuild as a non-odr-use DeclRefExpr.
19963 MarkNotOdrUsed();
19964 return DeclRefExpr::Create(
19965 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19966 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19967 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19968 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19969 }
19970
19971 case Expr::FunctionParmPackExprClass: {
19972 auto *FPPE = cast<FunctionParmPackExpr>(E);
19973 // If any of the declarations in the pack is odr-used, then the expression
19974 // as a whole constitutes an odr-use.
19975 for (VarDecl *D : *FPPE)
19976 if (IsPotentialResultOdrUsed(D))
19977 return ExprEmpty();
19978
19979 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19980 // nothing cares about whether we marked this as an odr-use, but it might
19981 // be useful for non-compiler tools.
19982 MarkNotOdrUsed();
19983 break;
19984 }
19985
19986 // -- If e is a subscripting operation with an array operand...
19987 case Expr::ArraySubscriptExprClass: {
19988 auto *ASE = cast<ArraySubscriptExpr>(E);
19989 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19990 if (!OldBase->getType()->isArrayType())
19991 break;
19992 ExprResult Base = Rebuild(OldBase);
19993 if (!Base.isUsable())
19994 return Base;
19995 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19996 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19997 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19998 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19999 ASE->getRBracketLoc());
20000 }
20001
20002 case Expr::MemberExprClass: {
20003 auto *ME = cast<MemberExpr>(E);
20004 // -- If e is a class member access expression [...] naming a non-static
20005 // data member...
20006 if (isa<FieldDecl>(ME->getMemberDecl())) {
20007 ExprResult Base = Rebuild(ME->getBase());
20008 if (!Base.isUsable())
20009 return Base;
20010 return MemberExpr::Create(
20011 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20012 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20013 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20014 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20015 ME->getObjectKind(), ME->isNonOdrUse());
20016 }
20017
20018 if (ME->getMemberDecl()->isCXXInstanceMember())
20019 break;
20020
20021 // -- If e is a class member access expression naming a static data member,
20022 // ...
20023 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20024 break;
20025
20026 // Rebuild as a non-odr-use MemberExpr.
20027 MarkNotOdrUsed();
20028 return MemberExpr::Create(
20029 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20030 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20031 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20032 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20033 }
20034
20035 case Expr::BinaryOperatorClass: {
20036 auto *BO = cast<BinaryOperator>(E);
20037 Expr *LHS = BO->getLHS();
20038 Expr *RHS = BO->getRHS();
20039 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20040 if (BO->getOpcode() == BO_PtrMemD) {
20041 ExprResult Sub = Rebuild(LHS);
20042 if (!Sub.isUsable())
20043 return Sub;
20044 LHS = Sub.get();
20045 // -- If e is a comma expression, ...
20046 } else if (BO->getOpcode() == BO_Comma) {
20047 ExprResult Sub = Rebuild(RHS);
20048 if (!Sub.isUsable())
20049 return Sub;
20050 RHS = Sub.get();
20051 } else {
20052 break;
20053 }
20054 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
20055 LHS, RHS);
20056 }
20057
20058 // -- If e has the form (e1)...
20059 case Expr::ParenExprClass: {
20060 auto *PE = cast<ParenExpr>(E);
20061 ExprResult Sub = Rebuild(PE->getSubExpr());
20062 if (!Sub.isUsable())
20063 return Sub;
20064 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20065 }
20066
20067 // -- If e is a glvalue conditional expression, ...
20068 // We don't apply this to a binary conditional operator. FIXME: Should we?
20069 case Expr::ConditionalOperatorClass: {
20070 auto *CO = cast<ConditionalOperator>(E);
20071 ExprResult LHS = Rebuild(CO->getLHS());
20072 if (LHS.isInvalid())
20073 return ExprError();
20074 ExprResult RHS = Rebuild(CO->getRHS());
20075 if (RHS.isInvalid())
20076 return ExprError();
20077 if (!LHS.isUsable() && !RHS.isUsable())
20078 return ExprEmpty();
20079 if (!LHS.isUsable())
20080 LHS = CO->getLHS();
20081 if (!RHS.isUsable())
20082 RHS = CO->getRHS();
20083 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20084 CO->getCond(), LHS.get(), RHS.get());
20085 }
20086
20087 // [Clang extension]
20088 // -- If e has the form __extension__ e1...
20089 case Expr::UnaryOperatorClass: {
20090 auto *UO = cast<UnaryOperator>(E);
20091 if (UO->getOpcode() != UO_Extension)
20092 break;
20093 ExprResult Sub = Rebuild(UO->getSubExpr());
20094 if (!Sub.isUsable())
20095 return Sub;
20096 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20097 Sub.get());
20098 }
20099
20100 // [Clang extension]
20101 // -- If e has the form _Generic(...), the set of potential results is the
20102 // union of the sets of potential results of the associated expressions.
20103 case Expr::GenericSelectionExprClass: {
20104 auto *GSE = cast<GenericSelectionExpr>(E);
20105
20106 SmallVector<Expr *, 4> AssocExprs;
20107 bool AnyChanged = false;
20108 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20109 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20110 if (AssocExpr.isInvalid())
20111 return ExprError();
20112 if (AssocExpr.isUsable()) {
20113 AssocExprs.push_back(AssocExpr.get());
20114 AnyChanged = true;
20115 } else {
20116 AssocExprs.push_back(OrigAssocExpr);
20117 }
20118 }
20119
20120 void *ExOrTy = nullptr;
20121 bool IsExpr = GSE->isExprPredicate();
20122 if (IsExpr)
20123 ExOrTy = GSE->getControllingExpr();
20124 else
20125 ExOrTy = GSE->getControllingType();
20126 return AnyChanged ? S.CreateGenericSelectionExpr(
20127 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20128 GSE->getRParenLoc(), IsExpr, ExOrTy,
20129 GSE->getAssocTypeSourceInfos(), AssocExprs)
20130 : ExprEmpty();
20131 }
20132
20133 // [Clang extension]
20134 // -- If e has the form __builtin_choose_expr(...), the set of potential
20135 // results is the union of the sets of potential results of the
20136 // second and third subexpressions.
20137 case Expr::ChooseExprClass: {
20138 auto *CE = cast<ChooseExpr>(E);
20139
20140 ExprResult LHS = Rebuild(CE->getLHS());
20141 if (LHS.isInvalid())
20142 return ExprError();
20143
20144 ExprResult RHS = Rebuild(CE->getLHS());
20145 if (RHS.isInvalid())
20146 return ExprError();
20147
20148 if (!LHS.get() && !RHS.get())
20149 return ExprEmpty();
20150 if (!LHS.isUsable())
20151 LHS = CE->getLHS();
20152 if (!RHS.isUsable())
20153 RHS = CE->getRHS();
20154
20155 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20156 RHS.get(), CE->getRParenLoc());
20157 }
20158
20159 // Step through non-syntactic nodes.
20160 case Expr::ConstantExprClass: {
20161 auto *CE = cast<ConstantExpr>(E);
20162 ExprResult Sub = Rebuild(CE->getSubExpr());
20163 if (!Sub.isUsable())
20164 return Sub;
20165 return ConstantExpr::Create(S.Context, Sub.get());
20166 }
20167
20168 // We could mostly rely on the recursive rebuilding to rebuild implicit
20169 // casts, but not at the top level, so rebuild them here.
20170 case Expr::ImplicitCastExprClass: {
20171 auto *ICE = cast<ImplicitCastExpr>(E);
20172 // Only step through the narrow set of cast kinds we expect to encounter.
20173 // Anything else suggests we've left the region in which potential results
20174 // can be found.
20175 switch (ICE->getCastKind()) {
20176 case CK_NoOp:
20177 case CK_DerivedToBase:
20178 case CK_UncheckedDerivedToBase: {
20179 ExprResult Sub = Rebuild(ICE->getSubExpr());
20180 if (!Sub.isUsable())
20181 return Sub;
20182 CXXCastPath Path(ICE->path());
20183 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20184 ICE->getValueKind(), &Path);
20185 }
20186
20187 default:
20188 break;
20189 }
20190 break;
20191 }
20192
20193 default:
20194 break;
20195 }
20196
20197 // Can't traverse through this node. Nothing to do.
20198 return ExprEmpty();
20199}
20200
20201ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20202 // Check whether the operand is or contains an object of non-trivial C union
20203 // type.
20204 if (E->getType().isVolatileQualified() &&
20205 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20206 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20207 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
20208 Sema::NTCUC_LValueToRValueVolatile,
20209 NTCUK_Destruct|NTCUK_Copy);
20210
20211 // C++2a [basic.def.odr]p4:
20212 // [...] an expression of non-volatile-qualified non-class type to which
20213 // the lvalue-to-rvalue conversion is applied [...]
20214 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
20215 return E;
20216
20217 ExprResult Result =
20218 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
20219 if (Result.isInvalid())
20220 return ExprError();
20221 return Result.get() ? Result : E;
20222}
20223
20224ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20225 Res = CorrectDelayedTyposInExpr(Res);
20226
20227 if (!Res.isUsable())
20228 return Res;
20229
20230 // If a constant-expression is a reference to a variable where we delay
20231 // deciding whether it is an odr-use, just assume we will apply the
20232 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20233 // (a non-type template argument), we have special handling anyway.
20234 return CheckLValueToRValueConversionOperand(Res.get());
20235}
20236
20237void Sema::CleanupVarDeclMarking() {
20238 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20239 // call.
20240 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20241 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20242
20243 for (Expr *E : LocalMaybeODRUseExprs) {
20244 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20245 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20246 DRE->getLocation(), *this);
20247 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20248 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20249 *this);
20250 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20251 for (VarDecl *VD : *FP)
20252 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20253 } else {
20254 llvm_unreachable("Unexpected expression");
20255 }
20256 }
20257
20258 assert(MaybeODRUseExprs.empty() &&
20259 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20260}
20261
20262static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20263 ValueDecl *Var, Expr *E) {
20264 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20265 if (!VD)
20266 return;
20267
20268 const bool RefersToEnclosingScope =
20269 (SemaRef.CurContext != VD->getDeclContext() &&
20270 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20271 if (RefersToEnclosingScope) {
20272 LambdaScopeInfo *const LSI =
20273 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20274 if (LSI && (!LSI->CallOperator ||
20275 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20276 // If a variable could potentially be odr-used, defer marking it so
20277 // until we finish analyzing the full expression for any
20278 // lvalue-to-rvalue
20279 // or discarded value conversions that would obviate odr-use.
20280 // Add it to the list of potential captures that will be analyzed
20281 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20282 // unless the variable is a reference that was initialized by a constant
20283 // expression (this will never need to be captured or odr-used).
20284 //
20285 // FIXME: We can simplify this a lot after implementing P0588R1.
20286 assert(E && "Capture variable should be used in an expression.");
20287 if (!Var->getType()->isReferenceType() ||
20288 !VD->isUsableInConstantExpressions(SemaRef.Context))
20289 LSI->addPotentialCapture(E->IgnoreParens());
20290 }
20291 }
20292}
20293
20294static void DoMarkVarDeclReferenced(
20295 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20296 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20297 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20298 isa<FunctionParmPackExpr>(E)) &&
20299 "Invalid Expr argument to DoMarkVarDeclReferenced");
20300 Var->setReferenced();
20301
20302 if (Var->isInvalidDecl())
20303 return;
20304
20305 auto *MSI = Var->getMemberSpecializationInfo();
20306 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20307 : Var->getTemplateSpecializationKind();
20308
20309 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20310 bool UsableInConstantExpr =
20311 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
20312
20313 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20314 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20315 }
20316
20317 // C++20 [expr.const]p12:
20318 // A variable [...] is needed for constant evaluation if it is [...] a
20319 // variable whose name appears as a potentially constant evaluated
20320 // expression that is either a contexpr variable or is of non-volatile
20321 // const-qualified integral type or of reference type
20322 bool NeededForConstantEvaluation =
20323 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20324
20325 bool NeedDefinition =
20326 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
20327
20328 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20329 "Can't instantiate a partial template specialization.");
20330
20331 // If this might be a member specialization of a static data member, check
20332 // the specialization is visible. We already did the checks for variable
20333 // template specializations when we created them.
20334 if (NeedDefinition && TSK != TSK_Undeclared &&
20335 !isa<VarTemplateSpecializationDecl>(Var))
20336 SemaRef.checkSpecializationVisibility(Loc, Var);
20337
20338 // Perform implicit instantiation of static data members, static data member
20339 // templates of class templates, and variable template specializations. Delay
20340 // instantiations of variable templates, except for those that could be used
20341 // in a constant expression.
20342 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20343 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20344 // instantiation declaration if a variable is usable in a constant
20345 // expression (among other cases).
20346 bool TryInstantiating =
20347 TSK == TSK_ImplicitInstantiation ||
20348 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20349
20350 if (TryInstantiating) {
20351 SourceLocation PointOfInstantiation =
20352 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20353 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20354 if (FirstInstantiation) {
20355 PointOfInstantiation = Loc;
20356 if (MSI)
20357 MSI->setPointOfInstantiation(PointOfInstantiation);
20358 // FIXME: Notify listener.
20359 else
20360 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20361 }
20362
20363 if (UsableInConstantExpr) {
20364 // Do not defer instantiations of variables that could be used in a
20365 // constant expression.
20366 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20367 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20368 });
20369
20370 // Re-set the member to trigger a recomputation of the dependence bits
20371 // for the expression.
20372 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20373 DRE->setDecl(DRE->getDecl());
20374 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20375 ME->setMemberDecl(ME->getMemberDecl());
20376 } else if (FirstInstantiation) {
20377 SemaRef.PendingInstantiations
20378 .push_back(std::make_pair(Var, PointOfInstantiation));
20379 } else {
20380 bool Inserted = false;
20381 for (auto &I : SemaRef.SavedPendingInstantiations) {
20382 auto Iter = llvm::find_if(
20383 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20384 return P.first == Var;
20385 });
20386 if (Iter != I.end()) {
20387 SemaRef.PendingInstantiations.push_back(*Iter);
20388 I.erase(Iter);
20389 Inserted = true;
20390 break;
20391 }
20392 }
20393
20394 // FIXME: For a specialization of a variable template, we don't
20395 // distinguish between "declaration and type implicitly instantiated"
20396 // and "implicit instantiation of definition requested", so we have
20397 // no direct way to avoid enqueueing the pending instantiation
20398 // multiple times.
20399 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20400 SemaRef.PendingInstantiations
20401 .push_back(std::make_pair(Var, PointOfInstantiation));
20402 }
20403 }
20404 }
20405
20406 // C++2a [basic.def.odr]p4:
20407 // A variable x whose name appears as a potentially-evaluated expression e
20408 // is odr-used by e unless
20409 // -- x is a reference that is usable in constant expressions
20410 // -- x is a variable of non-reference type that is usable in constant
20411 // expressions and has no mutable subobjects [FIXME], and e is an
20412 // element of the set of potential results of an expression of
20413 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20414 // conversion is applied
20415 // -- x is a variable of non-reference type, and e is an element of the set
20416 // of potential results of a discarded-value expression to which the
20417 // lvalue-to-rvalue conversion is not applied [FIXME]
20418 //
20419 // We check the first part of the second bullet here, and
20420 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20421 // FIXME: To get the third bullet right, we need to delay this even for
20422 // variables that are not usable in constant expressions.
20423
20424 // If we already know this isn't an odr-use, there's nothing more to do.
20425 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20426 if (DRE->isNonOdrUse())
20427 return;
20428 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20429 if (ME->isNonOdrUse())
20430 return;
20431
20432 switch (OdrUse) {
20433 case OdrUseContext::None:
20434 // In some cases, a variable may not have been marked unevaluated, if it
20435 // appears in a defaukt initializer.
20436 assert((!E || isa<FunctionParmPackExpr>(E) ||
20437 SemaRef.isUnevaluatedContext()) &&
20438 "missing non-odr-use marking for unevaluated decl ref");
20439 break;
20440
20441 case OdrUseContext::FormallyOdrUsed:
20442 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20443 // behavior.
20444 break;
20445
20446 case OdrUseContext::Used:
20447 // If we might later find that this expression isn't actually an odr-use,
20448 // delay the marking.
20449 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
20450 SemaRef.MaybeODRUseExprs.insert(E);
20451 else
20452 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20453 break;
20454
20455 case OdrUseContext::Dependent:
20456 // If this is a dependent context, we don't need to mark variables as
20457 // odr-used, but we may still need to track them for lambda capture.
20458 // FIXME: Do we also need to do this inside dependent typeid expressions
20459 // (which are modeled as unevaluated at this point)?
20460 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20461 break;
20462 }
20463}
20464
20465static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20466 BindingDecl *BD, Expr *E) {
20467 BD->setReferenced();
20468
20469 if (BD->isInvalidDecl())
20470 return;
20471
20472 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20473 if (OdrUse == OdrUseContext::Used) {
20474 QualType CaptureType, DeclRefType;
20475 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20476 /*EllipsisLoc*/ SourceLocation(),
20477 /*BuildAndDiagnose*/ true, CaptureType,
20478 DeclRefType,
20479 /*FunctionScopeIndexToStopAt*/ nullptr);
20480 } else if (OdrUse == OdrUseContext::Dependent) {
20481 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20482 }
20483}
20484
20485/// Mark a variable referenced, and check whether it is odr-used
20486/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20487/// used directly for normal expressions referring to VarDecl.
20488void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20489 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20490}
20491
20492static void
20493MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20494 bool MightBeOdrUse,
20495 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20496 if (SemaRef.isInOpenMPDeclareTargetContext())
20497 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20498
20499 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20500 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20501 return;
20502 }
20503
20504 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20505 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20506 return;
20507 }
20508
20509 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20510
20511 // If this is a call to a method via a cast, also mark the method in the
20512 // derived class used in case codegen can devirtualize the call.
20513 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20514 if (!ME)
20515 return;
20516 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20517 if (!MD)
20518 return;
20519 // Only attempt to devirtualize if this is truly a virtual call.
20520 bool IsVirtualCall = MD->isVirtual() &&
20521 ME->performsVirtualDispatch(SemaRef.getLangOpts());
20522 if (!IsVirtualCall)
20523 return;
20524
20525 // If it's possible to devirtualize the call, mark the called function
20526 // referenced.
20527 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20528 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20529 if (DM)
20530 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20531}
20532
20533/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20534///
20535/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20536/// handled with care if the DeclRefExpr is not newly-created.
20537void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20538 // TODO: update this with DR# once a defect report is filed.
20539 // C++11 defect. The address of a pure member should not be an ODR use, even
20540 // if it's a qualified reference.
20541 bool OdrUse = true;
20542 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20543 if (Method->isVirtual() &&
20544 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20545 OdrUse = false;
20546
20547 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20548 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
20549 !isImmediateFunctionContext() &&
20550 !isCheckingDefaultArgumentOrInitializer() &&
20551 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20552 !FD->isDependentContext())
20553 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20554 }
20555 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20556 RefsMinusAssignments);
20557}
20558
20559/// Perform reference-marking and odr-use handling for a MemberExpr.
20560void Sema::MarkMemberReferenced(MemberExpr *E) {
20561 // C++11 [basic.def.odr]p2:
20562 // A non-overloaded function whose name appears as a potentially-evaluated
20563 // expression or a member of a set of candidate functions, if selected by
20564 // overload resolution when referred to from a potentially-evaluated
20565 // expression, is odr-used, unless it is a pure virtual function and its
20566 // name is not explicitly qualified.
20567 bool MightBeOdrUse = true;
20568 if (E->performsVirtualDispatch(getLangOpts())) {
20569 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20570 if (Method->isPure())
20571 MightBeOdrUse = false;
20572 }
20573 SourceLocation Loc =
20574 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20575 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20576 RefsMinusAssignments);
20577}
20578
20579/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20580void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20581 for (VarDecl *VD : *E)
20582 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20583 RefsMinusAssignments);
20584}
20585
20586/// Perform marking for a reference to an arbitrary declaration. It
20587/// marks the declaration referenced, and performs odr-use checking for
20588/// functions and variables. This method should not be used when building a
20589/// normal expression which refers to a variable.
20590void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20591 bool MightBeOdrUse) {
20592 if (MightBeOdrUse) {
20593 if (auto *VD = dyn_cast<VarDecl>(D)) {
20594 MarkVariableReferenced(Loc, VD);
20595 return;
20596 }
20597 }
20598 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20599 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20600 return;
20601 }
20602 D->setReferenced();
20603}
20604
20605namespace {
20606 // Mark all of the declarations used by a type as referenced.
20607 // FIXME: Not fully implemented yet! We need to have a better understanding
20608 // of when we're entering a context we should not recurse into.
20609 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20610 // TreeTransforms rebuilding the type in a new context. Rather than
20611 // duplicating the TreeTransform logic, we should consider reusing it here.
20612 // Currently that causes problems when rebuilding LambdaExprs.
20613 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20614 Sema &S;
20615 SourceLocation Loc;
20616
20617 public:
20618 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20619
20620 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20621
20622 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20623 };
20624}
20625
20626bool MarkReferencedDecls::TraverseTemplateArgument(
20627 const TemplateArgument &Arg) {
20628 {
20629 // A non-type template argument is a constant-evaluated context.
20630 EnterExpressionEvaluationContext Evaluated(
20631 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20632 if (Arg.getKind() == TemplateArgument::Declaration) {
20633 if (Decl *D = Arg.getAsDecl())
20634 S.MarkAnyDeclReferenced(Loc, D, true);
20635 } else if (Arg.getKind() == TemplateArgument::Expression) {
20636 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20637 }
20638 }
20639
20640 return Inherited::TraverseTemplateArgument(Arg);
20641}
20642
20643void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20644 MarkReferencedDecls Marker(*this, Loc);
20645 Marker.TraverseType(T);
20646}
20647
20648namespace {
20649/// Helper class that marks all of the declarations referenced by
20650/// potentially-evaluated subexpressions as "referenced".
20651class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20652public:
20653 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20654 bool SkipLocalVariables;
20655 ArrayRef<const Expr *> StopAt;
20656
20657 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20658 ArrayRef<const Expr *> StopAt)
20659 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20660
20661 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20662 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20663 }
20664
20665 void Visit(Expr *E) {
20666 if (llvm::is_contained(StopAt, E))
20667 return;
20668 Inherited::Visit(E);
20669 }
20670
20671 void VisitConstantExpr(ConstantExpr *E) {
20672 // Don't mark declarations within a ConstantExpression, as this expression
20673 // will be evaluated and folded to a value.
20674 }
20675
20676 void VisitDeclRefExpr(DeclRefExpr *E) {
20677 // If we were asked not to visit local variables, don't.
20678 if (SkipLocalVariables) {
20679 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20680 if (VD->hasLocalStorage())
20681 return;
20682 }
20683
20684 // FIXME: This can trigger the instantiation of the initializer of a
20685 // variable, which can cause the expression to become value-dependent
20686 // or error-dependent. Do we need to propagate the new dependence bits?
20687 S.MarkDeclRefReferenced(E);
20688 }
20689
20690 void VisitMemberExpr(MemberExpr *E) {
20691 S.MarkMemberReferenced(E);
20692 Visit(E->getBase());
20693 }
20694};
20695} // namespace
20696
20697/// Mark any declarations that appear within this expression or any
20698/// potentially-evaluated subexpressions as "referenced".
20699///
20700/// \param SkipLocalVariables If true, don't mark local variables as
20701/// 'referenced'.
20702/// \param StopAt Subexpressions that we shouldn't recurse into.
20703void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20704 bool SkipLocalVariables,
20705 ArrayRef<const Expr*> StopAt) {
20706 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20707}
20708
20709/// Emit a diagnostic when statements are reachable.
20710/// FIXME: check for reachability even in expressions for which we don't build a
20711/// CFG (eg, in the initializer of a global or in a constant expression).
20712/// For example,
20713/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20714bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20715 const PartialDiagnostic &PD) {
20716 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20717 if (!FunctionScopes.empty())
20718 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20719 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20720 return true;
20721 }
20722
20723 // The initializer of a constexpr variable or of the first declaration of a
20724 // static data member is not syntactically a constant evaluated constant,
20725 // but nonetheless is always required to be a constant expression, so we
20726 // can skip diagnosing.
20727 // FIXME: Using the mangling context here is a hack.
20728 if (auto *VD = dyn_cast_or_null<VarDecl>(
20729 ExprEvalContexts.back().ManglingContextDecl)) {
20730 if (VD->isConstexpr() ||
20731 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20732 return false;
20733 // FIXME: For any other kind of variable, we should build a CFG for its
20734 // initializer and check whether the context in question is reachable.
20735 }
20736
20737 Diag(Loc, PD);
20738 return true;
20739}
20740
20741/// Emit a diagnostic that describes an effect on the run-time behavior
20742/// of the program being compiled.
20743///
20744/// This routine emits the given diagnostic when the code currently being
20745/// type-checked is "potentially evaluated", meaning that there is a
20746/// possibility that the code will actually be executable. Code in sizeof()
20747/// expressions, code used only during overload resolution, etc., are not
20748/// potentially evaluated. This routine will suppress such diagnostics or,
20749/// in the absolutely nutty case of potentially potentially evaluated
20750/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20751/// later.
20752///
20753/// This routine should be used for all diagnostics that describe the run-time
20754/// behavior of a program, such as passing a non-POD value through an ellipsis.
20755/// Failure to do so will likely result in spurious diagnostics or failures
20756/// during overload resolution or within sizeof/alignof/typeof/typeid.
20757bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20758 const PartialDiagnostic &PD) {
20759
20760 if (ExprEvalContexts.back().isDiscardedStatementContext())
20761 return false;
20762
20763 switch (ExprEvalContexts.back().Context) {
20764 case ExpressionEvaluationContext::Unevaluated:
20765 case ExpressionEvaluationContext::UnevaluatedList:
20766 case ExpressionEvaluationContext::UnevaluatedAbstract:
20767 case ExpressionEvaluationContext::DiscardedStatement:
20768 // The argument will never be evaluated, so don't complain.
20769 break;
20770
20771 case ExpressionEvaluationContext::ConstantEvaluated:
20772 case ExpressionEvaluationContext::ImmediateFunctionContext:
20773 // Relevant diagnostics should be produced by constant evaluation.
20774 break;
20775
20776 case ExpressionEvaluationContext::PotentiallyEvaluated:
20777 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20778 return DiagIfReachable(Loc, Stmts, PD);
20779 }
20780
20781 return false;
20782}
20783
20784bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20785 const PartialDiagnostic &PD) {
20786 return DiagRuntimeBehavior(
20787 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20788}
20789
20790bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20791 CallExpr *CE, FunctionDecl *FD) {
20792 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20793 return false;
20794
20795 // If we're inside a decltype's expression, don't check for a valid return
20796 // type or construct temporaries until we know whether this is the last call.
20797 if (ExprEvalContexts.back().ExprContext ==
20798 ExpressionEvaluationContextRecord::EK_Decltype) {
20799 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20800 return false;
20801 }
20802
20803 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20804 FunctionDecl *FD;
20805 CallExpr *CE;
20806
20807 public:
20808 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20809 : FD(FD), CE(CE) { }
20810
20811 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20812 if (!FD) {
20813 S.Diag(Loc, diag::err_call_incomplete_return)
20814 << T << CE->getSourceRange();
20815 return;
20816 }
20817
20818 S.Diag(Loc, diag::err_call_function_incomplete_return)
20819 << CE->getSourceRange() << FD << T;
20820 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20821 << FD->getDeclName();
20822 }
20823 } Diagnoser(FD, CE);
20824
20825 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20826 return true;
20827
20828 return false;
20829}
20830
20831// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20832// will prevent this condition from triggering, which is what we want.
20833void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20834 SourceLocation Loc;
20835
20836 unsigned diagnostic = diag::warn_condition_is_assignment;
20837 bool IsOrAssign = false;
20838
20839 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20840 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20841 return;
20842
20843 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20844
20845 // Greylist some idioms by putting them into a warning subcategory.
20846 if (ObjCMessageExpr *ME
20847 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20848 Selector Sel = ME->getSelector();
20849
20850 // self = [<foo> init...]
20851 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20852 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20853
20854 // <foo> = [<bar> nextObject]
20855 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20856 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20857 }
20858
20859 Loc = Op->getOperatorLoc();
20860 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20861 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20862 return;
20863
20864 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20865 Loc = Op->getOperatorLoc();
20866 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20867 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20868 else {
20869 // Not an assignment.
20870 return;
20871 }
20872
20873 Diag(Loc, diagnostic) << E->getSourceRange();
20874
20875 SourceLocation Open = E->getBeginLoc();
20876 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20877 Diag(Loc, diag::note_condition_assign_silence)
20878 << FixItHint::CreateInsertion(Open, "(")
20879 << FixItHint::CreateInsertion(Close, ")");
20880
20881 if (IsOrAssign)
20882 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20883 << FixItHint::CreateReplacement(Loc, "!=");
20884 else
20885 Diag(Loc, diag::note_condition_assign_to_comparison)
20886 << FixItHint::CreateReplacement(Loc, "==");
20887}
20888
20889/// Redundant parentheses over an equality comparison can indicate
20890/// that the user intended an assignment used as condition.
20891void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20892 // Don't warn if the parens came from a macro.
20893 SourceLocation parenLoc = ParenE->getBeginLoc();
20894 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20895 return;
20896 // Don't warn for dependent expressions.
20897 if (ParenE->isTypeDependent())
20898 return;
20899
20900 Expr *E = ParenE->IgnoreParens();
20901
20902 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20903 if (opE->getOpcode() == BO_EQ &&
20904 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20905 == Expr::MLV_Valid) {
20906 SourceLocation Loc = opE->getOperatorLoc();
20907
20908 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20909 SourceRange ParenERange = ParenE->getSourceRange();
20910 Diag(Loc, diag::note_equality_comparison_silence)
20911 << FixItHint::CreateRemoval(ParenERange.getBegin())
20912 << FixItHint::CreateRemoval(ParenERange.getEnd());
20913 Diag(Loc, diag::note_equality_comparison_to_assign)
20914 << FixItHint::CreateReplacement(Loc, "=");
20915 }
20916}
20917
20918ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20919 bool IsConstexpr) {
20920 DiagnoseAssignmentAsCondition(E);
20921 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20922 DiagnoseEqualityWithExtraParens(parenE);
20923
20924 ExprResult result = CheckPlaceholderExpr(E);
20925 if (result.isInvalid()) return ExprError();
20926 E = result.get();
20927
20928 if (!E->isTypeDependent()) {
20929 if (getLangOpts().CPlusPlus)
20930 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20931
20932 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20933 if (ERes.isInvalid())
20934 return ExprError();
20935 E = ERes.get();
20936
20937 QualType T = E->getType();
20938 if (!T->isScalarType()) { // C99 6.8.4.1p1
20939 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20940 << T << E->getSourceRange();
20941 return ExprError();
20942 }
20943 CheckBoolLikeConversion(E, Loc);
20944 }
20945
20946 return E;
20947}
20948
20949Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20950 Expr *SubExpr, ConditionKind CK,
20951 bool MissingOK) {
20952 // MissingOK indicates whether having no condition expression is valid
20953 // (for loop) or invalid (e.g. while loop).
20954 if (!SubExpr)
20955 return MissingOK ? ConditionResult() : ConditionError();
20956
20957 ExprResult Cond;
20958 switch (CK) {
20959 case ConditionKind::Boolean:
20960 Cond = CheckBooleanCondition(Loc, SubExpr);
20961 break;
20962
20963 case ConditionKind::ConstexprIf:
20964 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20965 break;
20966
20967 case ConditionKind::Switch:
20968 Cond = CheckSwitchCondition(Loc, SubExpr);
20969 break;
20970 }
20971 if (Cond.isInvalid()) {
20972 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20973 {SubExpr}, PreferredConditionType(CK));
20974 if (!Cond.get())
20975 return ConditionError();
20976 }
20977 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20978 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20979 if (!FullExpr.get())
20980 return ConditionError();
20981
20982 return ConditionResult(*this, nullptr, FullExpr,
20983 CK == ConditionKind::ConstexprIf);
20984}
20985
20986namespace {
20987 /// A visitor for rebuilding a call to an __unknown_any expression
20988 /// to have an appropriate type.
20989 struct RebuildUnknownAnyFunction
20990 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20991
20992 Sema &S;
20993
20994 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20995
20996 ExprResult VisitStmt(Stmt *S) {
20997 llvm_unreachable("unexpected statement!");
20998 }
20999
21000 ExprResult VisitExpr(Expr *E) {
21001 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21002 << E->getSourceRange();
21003 return ExprError();
21004 }
21005
21006 /// Rebuild an expression which simply semantically wraps another
21007 /// expression which it shares the type and value kind of.
21008 template <class T> ExprResult rebuildSugarExpr(T *E) {
21009 ExprResult SubResult = Visit(E->getSubExpr());
21010 if (SubResult.isInvalid()) return ExprError();
21011
21012 Expr *SubExpr = SubResult.get();
21013 E->setSubExpr(SubExpr);
21014 E->setType(SubExpr->getType());
21015 E->setValueKind(SubExpr->getValueKind());
21016 assert(E->getObjectKind() == OK_Ordinary);
21017 return E;
21018 }
21019
21020 ExprResult VisitParenExpr(ParenExpr *E) {
21021 return rebuildSugarExpr(E);
21022 }
21023
21024 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21025 return rebuildSugarExpr(E);
21026 }
21027
21028 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21029 ExprResult SubResult = Visit(E->getSubExpr());
21030 if (SubResult.isInvalid()) return ExprError();
21031
21032 Expr *SubExpr = SubResult.get();
21033 E->setSubExpr(SubExpr);
21034 E->setType(S.Context.getPointerType(SubExpr->getType()));
21035 assert(E->isPRValue());
21036 assert(E->getObjectKind() == OK_Ordinary);
21037 return E;
21038 }
21039
21040 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21041 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21042
21043 E->setType(VD->getType());
21044
21045 assert(E->isPRValue());
21046 if (S.getLangOpts().CPlusPlus &&
21047 !(isa<CXXMethodDecl>(VD) &&
21048 cast<CXXMethodDecl>(VD)->isInstance()))
21049 E->setValueKind(VK_LValue);
21050
21051 return E;
21052 }
21053
21054 ExprResult VisitMemberExpr(MemberExpr *E) {
21055 return resolveDecl(E, E->getMemberDecl());
21056 }
21057
21058 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21059 return resolveDecl(E, E->getDecl());
21060 }
21061 };
21062}
21063
21064/// Given a function expression of unknown-any type, try to rebuild it
21065/// to have a function type.
21066static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21067 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21068 if (Result.isInvalid()) return ExprError();
21069 return S.DefaultFunctionArrayConversion(Result.get());
21070}
21071
21072namespace {
21073 /// A visitor for rebuilding an expression of type __unknown_anytype
21074 /// into one which resolves the type directly on the referring
21075 /// expression. Strict preservation of the original source
21076 /// structure is not a goal.
21077 struct RebuildUnknownAnyExpr
21078 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21079
21080 Sema &S;
21081
21082 /// The current destination type.
21083 QualType DestType;
21084
21085 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21086 : S(S), DestType(CastType) {}
21087
21088 ExprResult VisitStmt(Stmt *S) {
21089 llvm_unreachable("unexpected statement!");
21090 }
21091
21092 ExprResult VisitExpr(Expr *E) {
21093 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21094 << E->getSourceRange();
21095 return ExprError();
21096 }
21097
21098 ExprResult VisitCallExpr(CallExpr *E);
21099 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21100
21101 /// Rebuild an expression which simply semantically wraps another
21102 /// expression which it shares the type and value kind of.
21103 template <class T> ExprResult rebuildSugarExpr(T *E) {
21104 ExprResult SubResult = Visit(E->getSubExpr());
21105 if (SubResult.isInvalid()) return ExprError();
21106 Expr *SubExpr = SubResult.get();
21107 E->setSubExpr(SubExpr);
21108 E->setType(SubExpr->getType());
21109 E->setValueKind(SubExpr->getValueKind());
21110 assert(E->getObjectKind() == OK_Ordinary);
21111 return E;
21112 }
21113
21114 ExprResult VisitParenExpr(ParenExpr *E) {
21115 return rebuildSugarExpr(E);
21116 }
21117
21118 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21119 return rebuildSugarExpr(E);
21120 }
21121
21122 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21123 const PointerType *Ptr = DestType->getAs<PointerType>();
21124 if (!Ptr) {
21125 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21126 << E->getSourceRange();
21127 return ExprError();
21128 }
21129
21130 if (isa<CallExpr>(E->getSubExpr())) {
21131 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21132 << E->getSourceRange();
21133 return ExprError();
21134 }
21135
21136 assert(E->isPRValue());
21137 assert(E->getObjectKind() == OK_Ordinary);
21138 E->setType(DestType);
21139
21140 // Build the sub-expression as if it were an object of the pointee type.
21141 DestType = Ptr->getPointeeType();
21142 ExprResult SubResult = Visit(E->getSubExpr());
21143 if (SubResult.isInvalid()) return ExprError();
21144 E->setSubExpr(SubResult.get());
21145 return E;
21146 }
21147
21148 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21149
21150 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21151
21152 ExprResult VisitMemberExpr(MemberExpr *E) {
21153 return resolveDecl(E, E->getMemberDecl());
21154 }
21155
21156 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21157 return resolveDecl(E, E->getDecl());
21158 }
21159 };
21160}
21161
21162/// Rebuilds a call expression which yielded __unknown_anytype.
21163ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21164 Expr *CalleeExpr = E->getCallee();
21165
21166 enum FnKind {
21167 FK_MemberFunction,
21168 FK_FunctionPointer,
21169 FK_BlockPointer
21170 };
21171
21172 FnKind Kind;
21173 QualType CalleeType = CalleeExpr->getType();
21174 if (CalleeType == S.Context.BoundMemberTy) {
21175 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21176 Kind = FK_MemberFunction;
21177 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21178 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21179 CalleeType = Ptr->getPointeeType();
21180 Kind = FK_FunctionPointer;
21181 } else {
21182 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21183 Kind = FK_BlockPointer;
21184 }
21185 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21186
21187 // Verify that this is a legal result type of a function.
21188 if (DestType->isArrayType() || DestType->isFunctionType()) {
21189 unsigned diagID = diag::err_func_returning_array_function;
21190 if (Kind == FK_BlockPointer)
21191 diagID = diag::err_block_returning_array_function;
21192
21193 S.Diag(E->getExprLoc(), diagID)
21194 << DestType->isFunctionType() << DestType;
21195 return ExprError();
21196 }
21197
21198 // Otherwise, go ahead and set DestType as the call's result.
21199 E->setType(DestType.getNonLValueExprType(S.Context));
21200 E->setValueKind(Expr::getValueKindForType(DestType));
21201 assert(E->getObjectKind() == OK_Ordinary);
21202
21203 // Rebuild the function type, replacing the result type with DestType.
21204 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21205 if (Proto) {
21206 // __unknown_anytype(...) is a special case used by the debugger when
21207 // it has no idea what a function's signature is.
21208 //
21209 // We want to build this call essentially under the K&R
21210 // unprototyped rules, but making a FunctionNoProtoType in C++
21211 // would foul up all sorts of assumptions. However, we cannot
21212 // simply pass all arguments as variadic arguments, nor can we
21213 // portably just call the function under a non-variadic type; see
21214 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21215 // However, it turns out that in practice it is generally safe to
21216 // call a function declared as "A foo(B,C,D);" under the prototype
21217 // "A foo(B,C,D,...);". The only known exception is with the
21218 // Windows ABI, where any variadic function is implicitly cdecl
21219 // regardless of its normal CC. Therefore we change the parameter
21220 // types to match the types of the arguments.
21221 //
21222 // This is a hack, but it is far superior to moving the
21223 // corresponding target-specific code from IR-gen to Sema/AST.
21224
21225 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21226 SmallVector<QualType, 8> ArgTypes;
21227 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21228 ArgTypes.reserve(E->getNumArgs());
21229 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21230 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21231 }
21232 ParamTypes = ArgTypes;
21233 }
21234 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21235 Proto->getExtProtoInfo());
21236 } else {
21237 DestType = S.Context.getFunctionNoProtoType(DestType,
21238 FnType->getExtInfo());
21239 }
21240
21241 // Rebuild the appropriate pointer-to-function type.
21242 switch (Kind) {
21243 case FK_MemberFunction:
21244 // Nothing to do.
21245 break;
21246
21247 case FK_FunctionPointer:
21248 DestType = S.Context.getPointerType(DestType);
21249 break;
21250
21251 case FK_BlockPointer:
21252 DestType = S.Context.getBlockPointerType(DestType);
21253 break;
21254 }
21255
21256 // Finally, we can recurse.
21257 ExprResult CalleeResult = Visit(CalleeExpr);
21258 if (!CalleeResult.isUsable()) return ExprError();
21259 E->setCallee(CalleeResult.get());
21260
21261 // Bind a temporary if necessary.
21262 return S.MaybeBindToTemporary(E);
21263}
21264
21265ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21266 // Verify that this is a legal result type of a call.
21267 if (DestType->isArrayType() || DestType->isFunctionType()) {
21268 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21269 << DestType->isFunctionType() << DestType;
21270 return ExprError();
21271 }
21272
21273 // Rewrite the method result type if available.
21274 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21275 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21276 Method->setReturnType(DestType);
21277 }
21278
21279 // Change the type of the message.
21280 E->setType(DestType.getNonReferenceType());
21281 E->setValueKind(Expr::getValueKindForType(DestType));
21282
21283 return S.MaybeBindToTemporary(E);
21284}
21285
21286ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21287 // The only case we should ever see here is a function-to-pointer decay.
21288 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21289 assert(E->isPRValue());
21290 assert(E->getObjectKind() == OK_Ordinary);
21291
21292 E->setType(DestType);
21293
21294 // Rebuild the sub-expression as the pointee (function) type.
21295 DestType = DestType->castAs<PointerType>()->getPointeeType();
21296
21297 ExprResult Result = Visit(E->getSubExpr());
21298 if (!Result.isUsable()) return ExprError();
21299
21300 E->setSubExpr(Result.get());
21301 return E;
21302 } else if (E->getCastKind() == CK_LValueToRValue) {
21303 assert(E->isPRValue());
21304 assert(E->getObjectKind() == OK_Ordinary);
21305
21306 assert(isa<BlockPointerType>(E->getType()));
21307
21308 E->setType(DestType);
21309
21310 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21311 DestType = S.Context.getLValueReferenceType(DestType);
21312
21313 ExprResult Result = Visit(E->getSubExpr());
21314 if (!Result.isUsable()) return ExprError();
21315
21316 E->setSubExpr(Result.get());
21317 return E;
21318 } else {
21319 llvm_unreachable("Unhandled cast type!");
21320 }
21321}
21322
21323ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21324 ExprValueKind ValueKind = VK_LValue;
21325 QualType Type = DestType;
21326
21327 // We know how to make this work for certain kinds of decls:
21328
21329 // - functions
21330 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21331 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21332 DestType = Ptr->getPointeeType();
21333 ExprResult Result = resolveDecl(E, VD);
21334 if (Result.isInvalid()) return ExprError();
21335 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21336 VK_PRValue);
21337 }
21338
21339 if (!Type->isFunctionType()) {
21340 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21341 << VD << E->getSourceRange();
21342 return ExprError();
21343 }
21344 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21345 // We must match the FunctionDecl's type to the hack introduced in
21346 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21347 // type. See the lengthy commentary in that routine.
21348 QualType FDT = FD->getType();
21349 const FunctionType *FnType = FDT->castAs<FunctionType>();
21350 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21351 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21352 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21353 SourceLocation Loc = FD->getLocation();
21354 FunctionDecl *NewFD = FunctionDecl::Create(
21355 S.Context, FD->getDeclContext(), Loc, Loc,
21356 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21357 SC_None, S.getCurFPFeatures().isFPConstrained(),
21358 false /*isInlineSpecified*/, FD->hasPrototype(),
21359 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21360
21361 if (FD->getQualifier())
21362 NewFD->setQualifierInfo(FD->getQualifierLoc());
21363
21364 SmallVector<ParmVarDecl*, 16> Params;
21365 for (const auto &AI : FT->param_types()) {
21366 ParmVarDecl *Param =
21367 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21368 Param->setScopeInfo(0, Params.size());
21369 Params.push_back(Param);
21370 }
21371 NewFD->setParams(Params);
21372 DRE->setDecl(NewFD);
21373 VD = DRE->getDecl();
21374 }
21375 }
21376
21377 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21378 if (MD->isInstance()) {
21379 ValueKind = VK_PRValue;
21380 Type = S.Context.BoundMemberTy;
21381 }
21382
21383 // Function references aren't l-values in C.
21384 if (!S.getLangOpts().CPlusPlus)
21385 ValueKind = VK_PRValue;
21386
21387 // - variables
21388 } else if (isa<VarDecl>(VD)) {
21389 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21390 Type = RefTy->getPointeeType();
21391 } else if (Type->isFunctionType()) {
21392 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21393 << VD << E->getSourceRange();
21394 return ExprError();
21395 }
21396
21397 // - nothing else
21398 } else {
21399 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21400 << VD << E->getSourceRange();
21401 return ExprError();
21402 }
21403
21404 // Modifying the declaration like this is friendly to IR-gen but
21405 // also really dangerous.
21406 VD->setType(DestType);
21407 E->setType(Type);
21408 E->setValueKind(ValueKind);
21409 return E;
21410}
21411
21412/// Check a cast of an unknown-any type. We intentionally only
21413/// trigger this for C-style casts.
21414ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21415 Expr *CastExpr, CastKind &CastKind,
21416 ExprValueKind &VK, CXXCastPath &Path) {
21417 // The type we're casting to must be either void or complete.
21418 if (!CastType->isVoidType() &&
21419 RequireCompleteType(TypeRange.getBegin(), CastType,
21420 diag::err_typecheck_cast_to_incomplete))
21421 return ExprError();
21422
21423 // Rewrite the casted expression from scratch.
21424 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21425 if (!result.isUsable()) return ExprError();
21426
21427 CastExpr = result.get();
21428 VK = CastExpr->getValueKind();
21429 CastKind = CK_NoOp;
21430
21431 return CastExpr;
21432}
21433
21434ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21435 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21436}
21437
21438ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21439 Expr *arg, QualType &paramType) {
21440 // If the syntactic form of the argument is not an explicit cast of
21441 // any sort, just do default argument promotion.
21442 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21443 if (!castArg) {
21444 ExprResult result = DefaultArgumentPromotion(arg);
21445 if (result.isInvalid()) return ExprError();
21446 paramType = result.get()->getType();
21447 return result;
21448 }
21449
21450 // Otherwise, use the type that was written in the explicit cast.
21451 assert(!arg->hasPlaceholderType());
21452 paramType = castArg->getTypeAsWritten();
21453
21454 // Copy-initialize a parameter of that type.
21455 InitializedEntity entity =
21456 InitializedEntity::InitializeParameter(Context, paramType,
21457 /*consumed*/ false);
21458 return PerformCopyInitialization(entity, callLoc, arg);
21459}
21460
21461static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21462 Expr *orig = E;
21463 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21464 while (true) {
21465 E = E->IgnoreParenImpCasts();
21466 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21467 E = call->getCallee();
21468 diagID = diag::err_uncasted_call_of_unknown_any;
21469 } else {
21470 break;
21471 }
21472 }
21473
21474 SourceLocation loc;
21475 NamedDecl *d;
21476 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21477 loc = ref->getLocation();
21478 d = ref->getDecl();
21479 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21480 loc = mem->getMemberLoc();
21481 d = mem->getMemberDecl();
21482 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21483 diagID = diag::err_uncasted_call_of_unknown_any;
21484 loc = msg->getSelectorStartLoc();
21485 d = msg->getMethodDecl();
21486 if (!d) {
21487 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21488 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21489 << orig->getSourceRange();
21490 return ExprError();
21491 }
21492 } else {
21493 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21494 << E->getSourceRange();
21495 return ExprError();
21496 }
21497
21498 S.Diag(loc, diagID) << d << orig->getSourceRange();
21499
21500 // Never recoverable.
21501 return ExprError();
21502}
21503
21504/// Check for operands with placeholder types and complain if found.
21505/// Returns ExprError() if there was an error and no recovery was possible.
21506ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21507 if (!Context.isDependenceAllowed()) {
21508 // C cannot handle TypoExpr nodes on either side of a binop because it
21509 // doesn't handle dependent types properly, so make sure any TypoExprs have
21510 // been dealt with before checking the operands.
21511 ExprResult Result = CorrectDelayedTyposInExpr(E);
21512 if (!Result.isUsable()) return ExprError();
21513 E = Result.get();
21514 }
21515
21516 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21517 if (!placeholderType) return E;
21518
21519 switch (placeholderType->getKind()) {
21520
21521 // Overloaded expressions.
21522 case BuiltinType::Overload: {
21523 // Try to resolve a single function template specialization.
21524 // This is obligatory.
21525 ExprResult Result = E;
21526 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21527 return Result;
21528
21529 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21530 // leaves Result unchanged on failure.
21531 Result = E;
21532 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21533 return Result;
21534
21535 // If that failed, try to recover with a call.
21536 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21537 /*complain*/ true);
21538 return Result;
21539 }
21540
21541 // Bound member functions.
21542 case BuiltinType::BoundMember: {
21543 ExprResult result = E;
21544 const Expr *BME = E->IgnoreParens();
21545 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21546 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21547 if (isa<CXXPseudoDestructorExpr>(BME)) {
21548 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21549 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21550 if (ME->getMemberNameInfo().getName().getNameKind() ==
21551 DeclarationName::CXXDestructorName)
21552 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21553 }
21554 tryToRecoverWithCall(result, PD,
21555 /*complain*/ true);
21556 return result;
21557 }
21558
21559 // ARC unbridged casts.
21560 case BuiltinType::ARCUnbridgedCast: {
21561 Expr *realCast = stripARCUnbridgedCast(E);
21562 diagnoseARCUnbridgedCast(realCast);
21563 return realCast;
21564 }
21565
21566 // Expressions of unknown type.
21567 case BuiltinType::UnknownAny:
21568 return diagnoseUnknownAnyExpr(*this, E);
21569
21570 // Pseudo-objects.
21571 case BuiltinType::PseudoObject:
21572 return checkPseudoObjectRValue(E);
21573
21574 case BuiltinType::BuiltinFn: {
21575 // Accept __noop without parens by implicitly converting it to a call expr.
21576 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21577 if (DRE) {
21578 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21579 unsigned BuiltinID = FD->getBuiltinID();
21580 if (BuiltinID == Builtin::BI__noop) {
21581 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21582 CK_BuiltinFnToFnPtr)
21583 .get();
21584 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21585 VK_PRValue, SourceLocation(),
21586 FPOptionsOverride());
21587 }
21588
21589 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21590 // Any use of these other than a direct call is ill-formed as of C++20,
21591 // because they are not addressable functions. In earlier language
21592 // modes, warn and force an instantiation of the real body.
21593 Diag(E->getBeginLoc(),
21594 getLangOpts().CPlusPlus20
21595 ? diag::err_use_of_unaddressable_function
21596 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21597 if (FD->isImplicitlyInstantiable()) {
21598 // Require a definition here because a normal attempt at
21599 // instantiation for a builtin will be ignored, and we won't try
21600 // again later. We assume that the definition of the template
21601 // precedes this use.
21602 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21603 /*Recursive=*/false,
21604 /*DefinitionRequired=*/true,
21605 /*AtEndOfTU=*/false);
21606 }
21607 // Produce a properly-typed reference to the function.
21608 CXXScopeSpec SS;
21609 SS.Adopt(DRE->getQualifierLoc());
21610 TemplateArgumentListInfo TemplateArgs;
21611 DRE->copyTemplateArgumentsInto(TemplateArgs);
21612 return BuildDeclRefExpr(
21613 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21614 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21615 DRE->getTemplateKeywordLoc(),
21616 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21617 }
21618 }
21619
21620 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21621 return ExprError();
21622 }
21623
21624 case BuiltinType::IncompleteMatrixIdx:
21625 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21626 ->getRowIdx()
21627 ->getBeginLoc(),
21628 diag::err_matrix_incomplete_index);
21629 return ExprError();
21630
21631 // Expressions of unknown type.
21632 case BuiltinType::OMPArraySection:
21633 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21634 return ExprError();
21635
21636 // Expressions of unknown type.
21637 case BuiltinType::OMPArrayShaping:
21638 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21639
21640 case BuiltinType::OMPIterator:
21641 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21642
21643 // Everything else should be impossible.
21644#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21645 case BuiltinType::Id:
21646#include "clang/Basic/OpenCLImageTypes.def"
21647#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21648 case BuiltinType::Id:
21649#include "clang/Basic/OpenCLExtensionTypes.def"
21650#define SVE_TYPE(Name, Id, SingletonId) \
21651 case BuiltinType::Id:
21652#include "clang/Basic/AArch64SVEACLETypes.def"
21653#define PPC_VECTOR_TYPE(Name, Id, Size) \
21654 case BuiltinType::Id:
21655#include "clang/Basic/PPCTypes.def"
21656#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21657#include "clang/Basic/RISCVVTypes.def"
21658#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21659#include "clang/Basic/WebAssemblyReferenceTypes.def"
21660#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21661#define PLACEHOLDER_TYPE(Id, SingletonId)
21662#include "clang/AST/BuiltinTypes.def"
21663 break;
21664 }
21665
21666 llvm_unreachable("invalid placeholder type!");
21667}
21668
21669bool Sema::CheckCaseExpression(Expr *E) {
21670 if (E->isTypeDependent())
21671 return true;
21672 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21673 return E->getType()->isIntegralOrEnumerationType();
21674 return false;
21675}
21676
21677/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21678ExprResult
21679Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21680 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21681 "Unknown Objective-C Boolean value!");
21682 QualType BoolT = Context.ObjCBuiltinBoolTy;
21683 if (!Context.getBOOLDecl()) {
21684 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21685 Sema::LookupOrdinaryName);
21686 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21687 NamedDecl *ND = Result.getFoundDecl();
21688 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21689 Context.setBOOLDecl(TD);
21690 }
21691 }
21692 if (Context.getBOOLDecl())
21693 BoolT = Context.getBOOLType();
21694 return new (Context)
21695 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21696}
21697
21698ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21699 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21700 SourceLocation RParen) {
21701 auto FindSpecVersion =
21702 [&](StringRef Platform) -> std::optional<VersionTuple> {
21703 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21704 return Spec.getPlatform() == Platform;
21705 });
21706 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21707 // for "maccatalyst" if "maccatalyst" is not specified.
21708 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21709 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21710 return Spec.getPlatform() == "ios";
21711 });
21712 }
21713 if (Spec == AvailSpecs.end())
21714 return std::nullopt;
21715 return Spec->getVersion();
21716 };
21717
21718 VersionTuple Version;
21719 if (auto MaybeVersion =
21720 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21721 Version = *MaybeVersion;
21722
21723 // The use of `@available` in the enclosing context should be analyzed to
21724 // warn when it's used inappropriately (i.e. not if(@available)).
21725 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21726 Context->HasPotentialAvailabilityViolations = true;
21727
21728 return new (Context)
21729 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21730}
21731
21732ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21733 ArrayRef<Expr *> SubExprs, QualType T) {
21734 if (!Context.getLangOpts().RecoveryAST)
21735 return ExprError();
21736
21737 if (isSFINAEContext())
21738 return ExprError();
21739
21740 if (T.isNull() || T->isUndeducedType() ||
21741 !Context.getLangOpts().RecoveryASTType)
21742 // We don't know the concrete type, fallback to dependent type.
21743 T = Context.DependentTy;
21744
21745 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21746}
21747