clang  19.0.0git
SemaExpr.cpp
Go to the documentation of this file.
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"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.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"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/TypeTraits.h"
40 #include "clang/Lex/Preprocessor.h"
42 #include "clang/Sema/DeclSpec.h"
44 #include "clang/Sema/Designator.h"
47 #include "clang/Sema/Lookup.h"
48 #include "clang/Sema/Overload.h"
50 #include "clang/Sema/Scope.h"
51 #include "clang/Sema/ScopeInfo.h"
52 #include "clang/Sema/SemaCUDA.h"
55 #include "clang/Sema/SemaObjC.h"
56 #include "clang/Sema/SemaOpenMP.h"
58 #include "clang/Sema/Template.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include "llvm/ADT/STLForwardCompat.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ConvertUTF.h"
64 #include "llvm/Support/SaveAndRestore.h"
65 #include "llvm/Support/TypeSize.h"
66 #include <optional>
67 
68 using namespace clang;
69 using namespace sema;
70 
71 /// Determine whether the use of this declaration is valid, without
72 /// emitting diagnostics.
73 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
74  // See if this is an auto-typed variable whose initializer we are parsing.
75  if (ParsingInitForAutoVars.count(D))
76  return false;
77 
78  // See if this is a deleted function.
79  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
80  if (FD->isDeleted())
81  return false;
82 
83  // If the function has a deduced return type, and we can't deduce it,
84  // then we can't use it either.
85  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
86  DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
87  return false;
88 
89  // See if this is an aligned allocation/deallocation function that is
90  // unavailable.
91  if (TreatUnavailableAsInvalid &&
92  isUnavailableAlignedAllocationFunction(*FD))
93  return false;
94  }
95 
96  // See if this function is unavailable.
97  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
98  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
99  return false;
100 
101  if (isa<UnresolvedUsingIfExistsDecl>(D))
102  return false;
103 
104  return true;
105 }
106 
108  // Warn if this is used but marked unused.
109  if (const auto *A = D->getAttr<UnusedAttr>()) {
110  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
111  // should diagnose them.
112  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
113  A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
114  const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
115  if (DC && !DC->hasAttr<UnusedAttr>())
116  S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
117  }
118  }
119 }
120 
121 /// Emit a note explaining that this function is deleted.
123  assert(Decl && Decl->isDeleted());
124 
125  if (Decl->isDefaulted()) {
126  // If the method was explicitly defaulted, point at that declaration.
127  if (!Decl->isImplicit())
128  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
129 
130  // Try to diagnose why this special member function was implicitly
131  // deleted. This might fail, if that reason no longer applies.
132  DiagnoseDeletedDefaultedFunction(Decl);
133  return;
134  }
135 
136  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
137  if (Ctor && Ctor->isInheritingConstructor())
138  return NoteDeletedInheritingConstructor(Ctor);
139 
140  Diag(Decl->getLocation(), diag::note_availability_specified_here)
141  << Decl << 1;
142 }
143 
144 /// Determine whether a FunctionDecl was ever declared with an
145 /// explicit storage class.
147  for (auto *I : D->redecls()) {
148  if (I->getStorageClass() != SC_None)
149  return true;
150  }
151  return false;
152 }
153 
154 /// Check whether we're in an extern inline function and referring to a
155 /// variable or function with internal linkage (C11 6.7.4p3).
156 ///
157 /// This is only a warning because we used to silently accept this code, but
158 /// in many cases it will not behave correctly. This is not enabled in C++ mode
159 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
160 /// and so while there may still be user mistakes, most of the time we can't
161 /// prove that there are errors.
163  const NamedDecl *D,
165  // This is disabled under C++; there are too many ways for this to fire in
166  // contexts where the warning is a false positive, or where it is technically
167  // correct but benign.
168  if (S.getLangOpts().CPlusPlus)
169  return;
170 
171  // Check if this is an inlined function or method.
172  FunctionDecl *Current = S.getCurFunctionDecl();
173  if (!Current)
174  return;
175  if (!Current->isInlined())
176  return;
177  if (!Current->isExternallyVisible())
178  return;
179 
180  // Check if the decl has internal linkage.
182  return;
183 
184  // Downgrade from ExtWarn to Extension if
185  // (1) the supposedly external inline function is in the main file,
186  // and probably won't be included anywhere else.
187  // (2) the thing we're referencing is a pure function.
188  // (3) the thing we're referencing is another inline function.
189  // This last can give us false negatives, but it's better than warning on
190  // wrappers for simple C library functions.
191  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
192  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
193  if (!DowngradeWarning && UsedFn)
194  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
195 
196  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
197  : diag::ext_internal_in_extern_inline)
198  << /*IsVar=*/!UsedFn << D;
199 
201 
202  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
203  << D;
204 }
205 
207  const FunctionDecl *First = Cur->getFirstDecl();
208 
209  // Suggest "static" on the function, if possible.
211  SourceLocation DeclBegin = First->getSourceRange().getBegin();
212  Diag(DeclBegin, diag::note_convert_inline_to_static)
213  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
214  }
215 }
216 
217 /// Determine whether the use of this declaration is valid, and
218 /// emit any corresponding diagnostics.
219 ///
220 /// This routine diagnoses various problems with referencing
221 /// declarations that can occur when using a declaration. For example,
222 /// it might warn if a deprecated or unavailable declaration is being
223 /// used, or produce an error (and return true) if a C++0x deleted
224 /// function is being used.
225 ///
226 /// \returns true if there was an error (this declaration cannot be
227 /// referenced), false otherwise.
228 ///
230  const ObjCInterfaceDecl *UnknownObjCClass,
231  bool ObjCPropertyAccess,
232  bool AvoidPartialAvailabilityChecks,
233  ObjCInterfaceDecl *ClassReceiver,
234  bool SkipTrailingRequiresClause) {
235  if (getLangOpts().SYCLIsDevice) {
236  if (auto VD = dyn_cast<VarDecl>(D)) {
237  bool IsConst = VD->getType().isConstant(Context);
238  bool IsRuntimeEvaluated =
239  ExprEvalContexts.empty() ||
240  (!isUnevaluatedContext() && !isConstantEvaluatedContext());
241  bool IsEsimdPrivateGlobal = SYCL().isSYCLEsimdPrivateGlobal(VD);
242  // Non-const statics are not allowed in SYCL except for ESIMD or with the
243  // SYCLGlobalVar or SYCLGlobalVariableAllowed attribute.
244  if (IsRuntimeEvaluated && !IsEsimdPrivateGlobal && !IsConst &&
245  VD->getStorageClass() == SC_Static &&
246  !VD->hasAttr<SYCLGlobalVarAttr>() &&
248  SYCLGlobalVariableAllowedAttr>(VD->getType()))
249  SYCL().DiagIfDeviceCode(*Locs.begin(), diag::err_sycl_restrict)
251  // Non-const globals are not allowed in SYCL except for ESIMD or with the
252  // SYCLGlobalVar or SYCLGlobalVariableAllowed attribute.
253  else if (IsRuntimeEvaluated && !IsEsimdPrivateGlobal && !IsConst &&
254  VD->hasGlobalStorage() && !VD->hasAttr<SYCLGlobalVarAttr>() &&
256  SYCLGlobalVariableAllowedAttr>(VD->getType()))
257  SYCL().DiagIfDeviceCode(*Locs.begin(), diag::err_sycl_restrict)
259  // ESIMD globals cannot be used in a SYCL context.
260  else if (IsRuntimeEvaluated && IsEsimdPrivateGlobal &&
261  VD->hasGlobalStorage())
262  SYCL().DiagIfDeviceCode(*Locs.begin(),
263  diag::err_esimd_global_in_sycl_context,
265  } else if (auto *FDecl = dyn_cast<FunctionDecl>(D)) {
266  // SYCL device function cannot be called from ESIMD context. However,
267  // there are some exceptions from this rule - functions that start
268  // with '__spirv_', '__sycl_', '__assert_fail', etc.
269  const IdentifierInfo *Id = FDecl->getIdentifier();
270  auto isMsvcMathFn = [=](StringRef Name) {
271  auto *AuxInfo = Context.getAuxTargetInfo();
272  if (!AuxInfo)
273  return false;
274  if (!AuxInfo->getTriple().isWindowsMSVCEnvironment())
275  return false;
276  return llvm::StringSwitch<bool>(Name)
277  .Case("_FDtest", true)
278  .Case("_hypotf", true)
279  .Case("_fdpcomp", true)
280  .Case("_fdsign", true)
281  .Case("_fdtest", true)
282  .Case("_FDnorm", true)
283  .Case("_FDscale", true)
284  .Case("_FExp", true)
285  .Case("_FCosh", true)
286  .Case("_FSinh", true)
287  .Default(false);
288  };
289  if ((getEmissionReason(FDecl) == Sema::DeviceDiagnosticReason::Sycl) &&
290  Id && !Id->getName().starts_with("__spirv_") &&
291  !Id->getName().starts_with("__sycl_") &&
292  !Id->getName().starts_with("__devicelib_ConvertBF16ToFINTEL") &&
293  !Id->getName().starts_with("__devicelib_ConvertFToBF16INTEL") &&
294  !Id->getName().starts_with("__assert_fail") &&
295  !isMsvcMathFn(Id->getName())) {
296  SYCL().DiagIfDeviceCode(
297  *Locs.begin(), diag::err_sycl_device_function_is_called_from_esimd,
299  }
300  }
301  }
302 
303  SourceLocation Loc = Locs.front();
304  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
305  // If there were any diagnostics suppressed by template argument deduction,
306  // emit them now.
307  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
308  if (Pos != SuppressedDiagnostics.end()) {
309  for (const PartialDiagnosticAt &Suppressed : Pos->second)
310  Diag(Suppressed.first, Suppressed.second);
311 
312  // Clear out the list of suppressed diagnostics, so that we don't emit
313  // them again for this specialization. However, we don't obsolete this
314  // entry from the table, because we want to avoid ever emitting these
315  // diagnostics again.
316  Pos->second.clear();
317  }
318 
319  // C++ [basic.start.main]p3:
320  // The function 'main' shall not be used within a program.
321  if (cast<FunctionDecl>(D)->isMain())
322  Diag(Loc, diag::ext_main_used);
323 
324  diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
325  }
326 
327  // See if this is an auto-typed variable whose initializer we are parsing.
328  if (ParsingInitForAutoVars.count(D)) {
329  if (isa<BindingDecl>(D)) {
330  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
331  << D->getDeclName();
332  } else {
333  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
334  << D->getDeclName() << cast<VarDecl>(D)->getType();
335  }
336  return true;
337  }
338 
339  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
340  // See if this is a deleted function.
341  if (FD->isDeleted()) {
342  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
343  if (Ctor && Ctor->isInheritingConstructor())
344  Diag(Loc, diag::err_deleted_inherited_ctor_use)
345  << Ctor->getParent()
346  << Ctor->getInheritedConstructor().getConstructor()->getParent();
347  else {
348  StringLiteral *Msg = FD->getDeletedMessage();
349  Diag(Loc, diag::err_deleted_function_use)
350  << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
351  }
352  NoteDeletedFunction(FD);
353  return true;
354  }
355 
356  // [expr.prim.id]p4
357  // A program that refers explicitly or implicitly to a function with a
358  // trailing requires-clause whose constraint-expression is not satisfied,
359  // other than to declare it, is ill-formed. [...]
360  //
361  // See if this is a function with constraints that need to be satisfied.
362  // Check this before deducing the return type, as it might instantiate the
363  // definition.
364  if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
365  ConstraintSatisfaction Satisfaction;
366  if (CheckFunctionConstraints(FD, Satisfaction, Loc,
367  /*ForOverloadResolution*/ true))
368  // A diagnostic will have already been generated (non-constant
369  // constraint expression, for example)
370  return true;
371  if (!Satisfaction.IsSatisfied) {
372  Diag(Loc,
373  diag::err_reference_to_function_with_unsatisfied_constraints)
374  << D;
375  DiagnoseUnsatisfiedConstraint(Satisfaction);
376  return true;
377  }
378  }
379 
380  // If the function has a deduced return type, and we can't deduce it,
381  // then we can't use it either.
382  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
383  DeduceReturnType(FD, Loc))
384  return true;
385 
386  if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
387  return true;
388 
389  }
390 
391  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
392  // Lambdas are only default-constructible or assignable in C++2a onwards.
393  if (MD->getParent()->isLambda() &&
394  ((isa<CXXConstructorDecl>(MD) &&
395  cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
396  MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
397  Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
398  << !isa<CXXConstructorDecl>(MD);
399  }
400  }
401 
402  auto getReferencedObjCProp = [](const NamedDecl *D) ->
403  const ObjCPropertyDecl * {
404  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
405  return MD->findPropertyDecl();
406  return nullptr;
407  };
408  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
409  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
410  return true;
411  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
412  return true;
413  }
414 
415  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
416  // Only the variables omp_in and omp_out are allowed in the combiner.
417  // Only the variables omp_priv and omp_orig are allowed in the
418  // initializer-clause.
419  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
420  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
421  isa<VarDecl>(D)) {
422  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
423  << getCurFunction()->HasOMPDeclareReductionCombiner;
424  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
425  return true;
426  }
427 
428  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
429  // List-items in map clauses on this construct may only refer to the declared
430  // variable var and entities that could be referenced by a procedure defined
431  // at the same location.
432  // [OpenMP 5.2] Also allow iterator declared variables.
433  if (LangOpts.OpenMP && isa<VarDecl>(D) &&
434  !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
435  Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
436  << OpenMP().getOpenMPDeclareMapperVarName();
437  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
438  return true;
439  }
440 
441  if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
442  Diag(Loc, diag::err_use_of_empty_using_if_exists);
443  Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
444  return true;
445  }
446 
447  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
448  AvoidPartialAvailabilityChecks, ClassReceiver);
449 
450  DiagnoseUnusedOfDecl(*this, D, Loc);
451 
453 
454  if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
455  if (getLangOpts().getFPEvalMethod() !=
456  LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
457  PP.getLastFPEvalPragmaLocation().isValid() &&
458  PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
459  Diag(D->getLocation(),
460  diag::err_type_available_only_in_default_eval_method)
461  << D->getName();
462  }
463 
464  if (auto *VD = dyn_cast<ValueDecl>(D))
465  checkTypeSupport(VD->getType(), Loc, VD);
466 
467  if (LangOpts.SYCLIsDevice ||
468  (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
469  if (!Context.getTargetInfo().isTLSSupported())
470  if (const auto *VD = dyn_cast<VarDecl>(D))
471  if (VD->getTLSKind() != VarDecl::TLS_None)
472  targetDiag(*Locs.begin(), diag::err_thread_unsupported);
473  }
474 
475  if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
476  !isUnevaluatedContext()) {
477  // C++ [expr.prim.req.nested] p3
478  // A local parameter shall only appear as an unevaluated operand
479  // (Clause 8) within the constraint-expression.
480  Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
481  << D;
482  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
483  return true;
484  }
485 
486  return false;
487 }
488 
489 /// DiagnoseSentinelCalls - This routine checks whether a call or
490 /// message-send is to a declaration with the sentinel attribute, and
491 /// if so, it checks that the requirements of the sentinel are
492 /// satisfied.
494  ArrayRef<Expr *> Args) {
495  const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
496  if (!Attr)
497  return;
498 
499  // The number of formal parameters of the declaration.
500  unsigned NumFormalParams;
501 
502  // The kind of declaration. This is also an index into a %select in
503  // the diagnostic.
504  enum { CK_Function, CK_Method, CK_Block } CalleeKind;
505 
506  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
507  NumFormalParams = MD->param_size();
508  CalleeKind = CK_Method;
509  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
510  NumFormalParams = FD->param_size();
511  CalleeKind = CK_Function;
512  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
513  QualType Ty = VD->getType();
514  const FunctionType *Fn = nullptr;
515  if (const auto *PtrTy = Ty->getAs<PointerType>()) {
516  Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
517  if (!Fn)
518  return;
519  CalleeKind = CK_Function;
520  } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
521  Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
522  CalleeKind = CK_Block;
523  } else {
524  return;
525  }
526 
527  if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
528  NumFormalParams = proto->getNumParams();
529  else
530  NumFormalParams = 0;
531  } else {
532  return;
533  }
534 
535  // "NullPos" is the number of formal parameters at the end which
536  // effectively count as part of the variadic arguments. This is
537  // useful if you would prefer to not have *any* formal parameters,
538  // but the language forces you to have at least one.
539  unsigned NullPos = Attr->getNullPos();
540  assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
541  NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
542 
543  // The number of arguments which should follow the sentinel.
544  unsigned NumArgsAfterSentinel = Attr->getSentinel();
545 
546  // If there aren't enough arguments for all the formal parameters,
547  // the sentinel, and the args after the sentinel, complain.
548  if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
549  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
550  Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
551  return;
552  }
553 
554  // Otherwise, find the sentinel expression.
555  const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
556  if (!SentinelExpr)
557  return;
558  if (SentinelExpr->isValueDependent())
559  return;
560  if (Context.isSentinelNullExpr(SentinelExpr))
561  return;
562 
563  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
564  // or 'NULL' if those are actually defined in the context. Only use
565  // 'nil' for ObjC methods, where it's much more likely that the
566  // variadic arguments form a list of object pointers.
567  SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
568  std::string NullValue;
569  if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
570  NullValue = "nil";
571  else if (getLangOpts().CPlusPlus11)
572  NullValue = "nullptr";
573  else if (PP.isMacroDefined("NULL"))
574  NullValue = "NULL";
575  else
576  NullValue = "(void*) 0";
577 
578  if (MissingNilLoc.isInvalid())
579  Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
580  else
581  Diag(MissingNilLoc, diag::warn_missing_sentinel)
582  << int(CalleeKind)
583  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
584  Diag(D->getLocation(), diag::note_sentinel_here)
585  << int(CalleeKind) << Attr->getRange();
586 }
587 
589  return E ? E->getSourceRange() : SourceRange();
590 }
591 
592 //===----------------------------------------------------------------------===//
593 // Standard Promotions and Conversions
594 //===----------------------------------------------------------------------===//
595 
596 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
598  // Handle any placeholder expressions which made it here.
599  if (E->hasPlaceholderType()) {
600  ExprResult result = CheckPlaceholderExpr(E);
601  if (result.isInvalid()) return ExprError();
602  E = result.get();
603  }
604 
605  QualType Ty = E->getType();
606  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
607 
608  if (Ty->isFunctionType()) {
609  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
610  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
611  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
612  return ExprError();
613 
614  E = ImpCastExprToType(E, Context.getPointerType(Ty),
615  CK_FunctionToPointerDecay).get();
616  } else if (Ty->isArrayType()) {
617  // In C90 mode, arrays only promote to pointers if the array expression is
618  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
619  // type 'array of type' is converted to an expression that has type 'pointer
620  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
621  // that has type 'array of type' ...". The relevant change is "an lvalue"
622  // (C90) to "an expression" (C99).
623  //
624  // C++ 4.2p1:
625  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
626  // T" can be converted to an rvalue of type "pointer to T".
627  //
628  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
629  ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
630  CK_ArrayToPointerDecay);
631  if (Res.isInvalid())
632  return ExprError();
633  E = Res.get();
634  }
635  }
636  return E;
637 }
638 
640  // Check to see if we are dereferencing a null pointer. If so,
641  // and if not volatile-qualified, this is undefined behavior that the
642  // optimizer will delete, so warn about it. People sometimes try to use this
643  // to get a deterministic trap and are surprised by clang's behavior. This
644  // only handles the pattern "*null", which is a very syntactic check.
645  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
646  if (UO && UO->getOpcode() == UO_Deref &&
647  UO->getSubExpr()->getType()->isPointerType()) {
648  const LangAS AS =
649  UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
650  if ((!isTargetAddressSpace(AS) ||
651  (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
652  UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
654  !UO->getType().isVolatileQualified()) {
655  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
656  S.PDiag(diag::warn_indirection_through_null)
657  << UO->getSubExpr()->getSourceRange());
658  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
659  S.PDiag(diag::note_indirection_through_null));
660  }
661  }
662 }
663 
664 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
665  SourceLocation AssignLoc,
666  const Expr* RHS) {
667  const ObjCIvarDecl *IV = OIRE->getDecl();
668  if (!IV)
669  return;
670 
671  DeclarationName MemberName = IV->getDeclName();
672  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
673  if (!Member || !Member->isStr("isa"))
674  return;
675 
676  const Expr *Base = OIRE->getBase();
677  QualType BaseType = Base->getType();
678  if (OIRE->isArrow())
679  BaseType = BaseType->getPointeeType();
680  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
681  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
682  ObjCInterfaceDecl *ClassDeclared = nullptr;
683  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
684  if (!ClassDeclared->getSuperClass()
685  && (*ClassDeclared->ivar_begin()) == IV) {
686  if (RHS) {
687  NamedDecl *ObjectSetClass =
689  &S.Context.Idents.get("object_setClass"),
691  if (ObjectSetClass) {
692  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
693  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
695  "object_setClass(")
697  SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
698  << FixItHint::CreateInsertion(RHSLocEnd, ")");
699  }
700  else
701  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
702  } else {
703  NamedDecl *ObjectGetClass =
705  &S.Context.Idents.get("object_getClass"),
707  if (ObjectGetClass)
708  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
710  "object_getClass(")
712  SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
713  else
714  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
715  }
716  S.Diag(IV->getLocation(), diag::note_ivar_decl);
717  }
718  }
719 }
720 
722  // Handle any placeholder expressions which made it here.
723  if (E->hasPlaceholderType()) {
724  ExprResult result = CheckPlaceholderExpr(E);
725  if (result.isInvalid()) return ExprError();
726  E = result.get();
727  }
728 
729  // C++ [conv.lval]p1:
730  // A glvalue of a non-function, non-array type T can be
731  // converted to a prvalue.
732  if (!E->isGLValue()) return E;
733 
734  QualType T = E->getType();
735  assert(!T.isNull() && "r-value conversion on typeless expression?");
736 
737  // lvalue-to-rvalue conversion cannot be applied to types that decay to
738  // pointers (i.e. function or array types).
739  if (T->canDecayToPointerType())
740  return E;
741 
742  // We don't want to throw lvalue-to-rvalue casts on top of
743  // expressions of certain types in C++.
744  if (getLangOpts().CPlusPlus) {
745  if (T == Context.OverloadTy || T->isRecordType() ||
746  (T->isDependentType() && !T->isAnyPointerType() &&
747  !T->isMemberPointerType()))
748  return E;
749  }
750 
751  // The C standard is actually really unclear on this point, and
752  // DR106 tells us what the result should be but not why. It's
753  // generally best to say that void types just doesn't undergo
754  // lvalue-to-rvalue at all. Note that expressions of unqualified
755  // 'void' type are never l-values, but qualified void can be.
756  if (T->isVoidType())
757  return E;
758 
759  // OpenCL usually rejects direct accesses to values of 'half' type.
760  if (getLangOpts().OpenCL &&
761  !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
762  T->isHalfType()) {
763  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
764  << 0 << T;
765  return ExprError();
766  }
767 
769  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
770  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
771  &Context.Idents.get("object_getClass"),
772  SourceLocation(), LookupOrdinaryName);
773  if (ObjectGetClass)
774  Diag(E->getExprLoc(), diag::warn_objc_isa_use)
775  << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
777  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
778  else
779  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
780  }
781  else if (const ObjCIvarRefExpr *OIRE =
782  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
783  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
784 
785  // C++ [conv.lval]p1:
786  // [...] If T is a non-class type, the type of the prvalue is the
787  // cv-unqualified version of T. Otherwise, the type of the
788  // rvalue is T.
789  //
790  // C99 6.3.2.1p2:
791  // If the lvalue has qualified type, the value has the unqualified
792  // version of the type of the lvalue; otherwise, the value has the
793  // type of the lvalue.
794  if (T.hasQualifiers())
795  T = T.getUnqualifiedType();
796 
797  // Under the MS ABI, lock down the inheritance model now.
798  if (T->isMemberPointerType() &&
799  Context.getTargetInfo().getCXXABI().isMicrosoft())
800  (void)isCompleteType(E->getExprLoc(), T);
801 
802  ExprResult Res = CheckLValueToRValueConversionOperand(E);
803  if (Res.isInvalid())
804  return Res;
805  E = Res.get();
806 
807  // Loading a __weak object implicitly retains the value, so we need a cleanup to
808  // balance that.
810  Cleanup.setExprNeedsCleanups(true);
811 
813  Cleanup.setExprNeedsCleanups(true);
814 
815  // C++ [conv.lval]p3:
816  // If T is cv std::nullptr_t, the result is a null pointer constant.
817  CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
818  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
819  CurFPFeatureOverrides());
820 
821  // C11 6.3.2.1p2:
822  // ... if the lvalue has atomic type, the value has the non-atomic version
823  // of the type of the lvalue ...
824  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
825  T = Atomic->getValueType().getUnqualifiedType();
826  Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
827  nullptr, VK_PRValue, FPOptionsOverride());
828  }
829 
830  return Res;
831 }
832 
834  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
835  if (Res.isInvalid())
836  return ExprError();
837  Res = DefaultLvalueConversion(Res.get());
838  if (Res.isInvalid())
839  return ExprError();
840  return Res;
841 }
842 
843 /// CallExprUnaryConversions - a special case of an unary conversion
844 /// performed on a function designator of a call expression.
846  QualType Ty = E->getType();
847  ExprResult Res = E;
848  // Only do implicit cast for a function type, but not for a pointer
849  // to function type.
850  if (Ty->isFunctionType()) {
851  Res = ImpCastExprToType(E, Context.getPointerType(Ty),
852  CK_FunctionToPointerDecay);
853  if (Res.isInvalid())
854  return ExprError();
855  }
856  Res = DefaultLvalueConversion(Res.get());
857  if (Res.isInvalid())
858  return ExprError();
859  return Res.get();
860 }
861 
862 /// UsualUnaryConversions - Performs various conversions that are common to most
863 /// operators (C99 6.3). The conversions of array and function types are
864 /// sometimes suppressed. For example, the array->pointer conversion doesn't
865 /// apply if the array is an argument to the sizeof or address (&) operators.
866 /// In these instances, this routine should *not* be called.
868  // First, convert to an r-value.
869  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
870  if (Res.isInvalid())
871  return ExprError();
872  E = Res.get();
873 
874  QualType Ty = E->getType();
875  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
876 
877  LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
878  if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
879  (getLangOpts().getFPEvalMethod() !=
880  LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
881  PP.getLastFPEvalPragmaLocation().isValid())) {
882  switch (EvalMethod) {
883  default:
884  llvm_unreachable("Unrecognized float evaluation method");
885  break;
887  llvm_unreachable("Float evaluation method should be set by now");
888  break;
890  if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
891  // Widen the expression to double.
892  return Ty->isComplexType()
893  ? ImpCastExprToType(E,
894  Context.getComplexType(Context.DoubleTy),
895  CK_FloatingComplexCast)
896  : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
897  break;
899  if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
900  // Widen the expression to long double.
901  return Ty->isComplexType()
902  ? ImpCastExprToType(
903  E, Context.getComplexType(Context.LongDoubleTy),
904  CK_FloatingComplexCast)
905  : ImpCastExprToType(E, Context.LongDoubleTy,
906  CK_FloatingCast);
907  break;
908  }
909  }
910 
911  // Half FP have to be promoted to float unless it is natively supported
912  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
913  return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
914 
915  // Try to perform integral promotions if the object has a theoretically
916  // promotable type.
918  // C99 6.3.1.1p2:
919  //
920  // The following may be used in an expression wherever an int or
921  // unsigned int may be used:
922  // - an object or expression with an integer type whose integer
923  // conversion rank is less than or equal to the rank of int
924  // and unsigned int.
925  // - A bit-field of type _Bool, int, signed int, or unsigned int.
926  //
927  // If an int can represent all values of the original type, the
928  // value is converted to an int; otherwise, it is converted to an
929  // unsigned int. These are called the integer promotions. All
930  // other types are unchanged by the integer promotions.
931 
932  QualType PTy = Context.isPromotableBitField(E);
933  if (!PTy.isNull()) {
934  E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
935  return E;
936  }
937  if (Context.isPromotableIntegerType(Ty)) {
938  QualType PT = Context.getPromotedIntegerType(Ty);
939  E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
940  return E;
941  }
942  }
943  return E;
944 }
945 
946 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
947 /// do not have a prototype. Arguments that have type float or __fp16
948 /// are promoted to double. All other argument types are converted by
949 /// UsualUnaryConversions().
951  QualType Ty = E->getType();
952  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
953 
954  ExprResult Res = UsualUnaryConversions(E);
955  if (Res.isInvalid())
956  return ExprError();
957  E = Res.get();
958 
959  // If this is a 'float' or '__fp16' (CVR qualified or typedef)
960  // promote to double.
961  // Note that default argument promotion applies only to float (and
962  // half/fp16); it does not apply to _Float16.
963  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
964  if (BTy && (BTy->getKind() == BuiltinType::Half ||
965  BTy->getKind() == BuiltinType::Float)) {
966  if (getLangOpts().OpenCL &&
967  !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
968  if (BTy->getKind() == BuiltinType::Half) {
969  E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
970  }
971  } else {
972  E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
973  }
974  }
975  if (BTy &&
976  getLangOpts().getExtendIntArgs() ==
978  Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
979  Context.getTypeSizeInChars(BTy) <
980  Context.getTypeSizeInChars(Context.LongLongTy)) {
981  E = (Ty->isUnsignedIntegerType())
982  ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
983  .get()
984  : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
985  assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
986  "Unexpected typesize for LongLongTy");
987  }
988 
989  // C++ performs lvalue-to-rvalue conversion as a default argument
990  // promotion, even on class types, but note:
991  // C++11 [conv.lval]p2:
992  // When an lvalue-to-rvalue conversion occurs in an unevaluated
993  // operand or a subexpression thereof the value contained in the
994  // referenced object is not accessed. Otherwise, if the glvalue
995  // has a class type, the conversion copy-initializes a temporary
996  // of type T from the glvalue and the result of the conversion
997  // is a prvalue for the temporary.
998  // FIXME: add some way to gate this entire thing for correctness in
999  // potentially potentially evaluated contexts.
1000  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
1001  ExprResult Temp = PerformCopyInitialization(
1003  E->getExprLoc(), E);
1004  if (Temp.isInvalid())
1005  return ExprError();
1006  E = Temp.get();
1007  }
1008 
1009  return E;
1010 }
1011 
1012 /// Determine the degree of POD-ness for an expression.
1013 /// Incomplete types are considered POD, since this check can be performed
1014 /// when we're in an unevaluated context.
1016  if (Ty->isIncompleteType()) {
1017  // C++11 [expr.call]p7:
1018  // After these conversions, if the argument does not have arithmetic,
1019  // enumeration, pointer, pointer to member, or class type, the program
1020  // is ill-formed.
1021  //
1022  // Since we've already performed array-to-pointer and function-to-pointer
1023  // decay, the only such type in C++ is cv void. This also handles
1024  // initializer lists as variadic arguments.
1025  if (Ty->isVoidType())
1026  return VAK_Invalid;
1027 
1028  if (Ty->isObjCObjectType())
1029  return VAK_Invalid;
1030  return VAK_Valid;
1031  }
1032 
1034  return VAK_Invalid;
1035 
1036  if (Context.getTargetInfo().getTriple().isWasm() &&
1038  return VAK_Invalid;
1039  }
1040 
1041  if (Ty.isCXX98PODType(Context))
1042  return VAK_Valid;
1043 
1044  // C++11 [expr.call]p7:
1045  // Passing a potentially-evaluated argument of class type (Clause 9)
1046  // having a non-trivial copy constructor, a non-trivial move constructor,
1047  // or a non-trivial destructor, with no corresponding parameter,
1048  // is conditionally-supported with implementation-defined semantics.
1049  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
1051  if (!Record->hasNonTrivialCopyConstructor() &&
1052  !Record->hasNonTrivialMoveConstructor() &&
1053  !Record->hasNonTrivialDestructor())
1054  return VAK_ValidInCXX11;
1055 
1056  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1057  return VAK_Valid;
1058 
1059  if (Ty->isObjCObjectType())
1060  return VAK_Invalid;
1061 
1062  if (getLangOpts().MSVCCompat)
1063  return VAK_MSVCUndefined;
1064 
1065  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1066  // permitted to reject them. We should consider doing so.
1067  return VAK_Undefined;
1068 }
1069 
1071  // Don't allow one to pass an Objective-C interface to a vararg.
1072  const QualType &Ty = E->getType();
1073  VarArgKind VAK = isValidVarArgType(Ty);
1074 
1075  // Complain about passing non-POD types through varargs.
1076  switch (VAK) {
1077  case VAK_ValidInCXX11:
1078  DiagRuntimeBehavior(
1079  E->getBeginLoc(), nullptr,
1080  PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1081  [[fallthrough]];
1082  case VAK_Valid:
1083  if (Ty->isRecordType()) {
1084  // This is unlikely to be what the user intended. If the class has a
1085  // 'c_str' member function, the user probably meant to call that.
1086  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1087  PDiag(diag::warn_pass_class_arg_to_vararg)
1088  << Ty << CT << hasCStrMethod(E) << ".c_str()");
1089  }
1090  break;
1091 
1092  case VAK_Undefined:
1093  case VAK_MSVCUndefined:
1094  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1095  PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1096  << getLangOpts().CPlusPlus11 << Ty << CT);
1097  break;
1098 
1099  case VAK_Invalid:
1101  Diag(E->getBeginLoc(),
1102  diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1103  << Ty << CT;
1104  else if (Ty->isObjCObjectType())
1105  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1106  PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1107  << Ty << CT);
1108  else
1109  Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1110  << isa<InitListExpr>(E) << Ty << CT;
1111  break;
1112  }
1113 }
1114 
1115 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1116 /// will create a trap if the resulting type is not a POD type.
1118  FunctionDecl *FDecl) {
1119  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1120  // Strip the unbridged-cast placeholder expression off, if applicable.
1121  if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1122  (CT == VariadicMethod ||
1123  (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1124  E = ObjC().stripARCUnbridgedCast(E);
1125 
1126  // Otherwise, do normal placeholder checking.
1127  } else {
1128  ExprResult ExprRes = CheckPlaceholderExpr(E);
1129  if (ExprRes.isInvalid())
1130  return ExprError();
1131  E = ExprRes.get();
1132  }
1133  }
1134 
1135  ExprResult ExprRes = DefaultArgumentPromotion(E);
1136  if (ExprRes.isInvalid())
1137  return ExprError();
1138 
1139  // Copy blocks to the heap.
1140  if (ExprRes.get()->getType()->isBlockPointerType())
1141  maybeExtendBlockObject(ExprRes);
1142 
1143  E = ExprRes.get();
1144 
1145  // Diagnostics regarding non-POD argument types are
1146  // emitted along with format string checking in Sema::CheckFunctionCall().
1147  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1148  // Turn this into a trap.
1149  CXXScopeSpec SS;
1150  SourceLocation TemplateKWLoc;
1151  UnqualifiedId Name;
1152  Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1153  E->getBeginLoc());
1154  ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1155  /*HasTrailingLParen=*/true,
1156  /*IsAddressOfOperand=*/false);
1157  if (TrapFn.isInvalid())
1158  return ExprError();
1159 
1160  ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1161  std::nullopt, E->getEndLoc());
1162  if (Call.isInvalid())
1163  return ExprError();
1164 
1165  ExprResult Comma =
1166  ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1167  if (Comma.isInvalid())
1168  return ExprError();
1169  return Comma.get();
1170  }
1171 
1172  if (!getLangOpts().CPlusPlus &&
1173  RequireCompleteType(E->getExprLoc(), E->getType(),
1174  diag::err_call_incomplete_argument))
1175  return ExprError();
1176 
1177  return E;
1178 }
1179 
1180 /// Convert complex integers to complex floats and real integers to
1181 /// real floats as required for complex arithmetic. Helper function of
1182 /// UsualArithmeticConversions()
1183 ///
1184 /// \return false if the integer expression is an integer type and is
1185 /// successfully converted to the (complex) float type.
1187  ExprResult &ComplexExpr,
1188  QualType IntTy,
1189  QualType ComplexTy,
1190  bool SkipCast) {
1191  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1192  if (SkipCast) return false;
1193  if (IntTy->isIntegerType()) {
1194  QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1195  IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1196  } else {
1197  assert(IntTy->isComplexIntegerType());
1198  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1199  CK_IntegralComplexToFloatingComplex);
1200  }
1201  return false;
1202 }
1203 
1204 // This handles complex/complex, complex/float, or float/complex.
1205 // When both operands are complex, the shorter operand is converted to the
1206 // type of the longer, and that is the type of the result. This corresponds
1207 // to what is done when combining two real floating-point operands.
1208 // The fun begins when size promotion occur across type domains.
1209 // From H&S 6.3.4: When one operand is complex and the other is a real
1210 // floating-point type, the less precise type is converted, within it's
1211 // real or complex domain, to the precision of the other type. For example,
1212 // when combining a "long double" with a "double _Complex", the
1213 // "double _Complex" is promoted to "long double _Complex".
1215  QualType ShorterType,
1216  QualType LongerType,
1217  bool PromotePrecision) {
1218  bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1219  QualType Result =
1220  LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1221 
1222  if (PromotePrecision) {
1223  if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1224  Shorter =
1225  S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1226  } else {
1227  if (LongerIsComplex)
1228  LongerType = LongerType->castAs<ComplexType>()->getElementType();
1229  Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1230  }
1231  }
1232  return Result;
1233 }
1234 
1235 /// Handle arithmetic conversion with complex types. Helper function of
1236 /// UsualArithmeticConversions()
1238  ExprResult &RHS, QualType LHSType,
1239  QualType RHSType, bool IsCompAssign) {
1240  // Handle (complex) integer types.
1241  if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1242  /*SkipCast=*/false))
1243  return LHSType;
1244  if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1245  /*SkipCast=*/IsCompAssign))
1246  return RHSType;
1247 
1248  // Compute the rank of the two types, regardless of whether they are complex.
1249  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1250  if (Order < 0)
1251  // Promote the precision of the LHS if not an assignment.
1252  return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1253  /*PromotePrecision=*/!IsCompAssign);
1254  // Promote the precision of the RHS unless it is already the same as the LHS.
1255  return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1256  /*PromotePrecision=*/Order > 0);
1257 }
1258 
1259 /// Handle arithmetic conversion from integer to float. Helper function
1260 /// of UsualArithmeticConversions()
1262  ExprResult &IntExpr,
1263  QualType FloatTy, QualType IntTy,
1264  bool ConvertFloat, bool ConvertInt) {
1265  if (IntTy->isIntegerType()) {
1266  if (ConvertInt)
1267  // Convert intExpr to the lhs floating point type.
1268  IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1269  CK_IntegralToFloating);
1270  return FloatTy;
1271  }
1272 
1273  // Convert both sides to the appropriate complex float.
1274  assert(IntTy->isComplexIntegerType());
1275  QualType result = S.Context.getComplexType(FloatTy);
1276 
1277  // _Complex int -> _Complex float
1278  if (ConvertInt)
1279  IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1280  CK_IntegralComplexToFloatingComplex);
1281 
1282  // float -> _Complex float
1283  if (ConvertFloat)
1284  FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1285  CK_FloatingRealToComplex);
1286 
1287  return result;
1288 }
1289 
1290 /// Handle arithmethic conversion with floating point types. Helper
1291 /// function of UsualArithmeticConversions()
1293  ExprResult &RHS, QualType LHSType,
1294  QualType RHSType, bool IsCompAssign) {
1295  bool LHSFloat = LHSType->isRealFloatingType();
1296  bool RHSFloat = RHSType->isRealFloatingType();
1297 
1298  // N1169 4.1.4: If one of the operands has a floating type and the other
1299  // operand has a fixed-point type, the fixed-point operand
1300  // is converted to the floating type [...]
1301  if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1302  if (LHSFloat)
1303  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1304  else if (!IsCompAssign)
1305  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1306  return LHSFloat ? LHSType : RHSType;
1307  }
1308 
1309  // If we have two real floating types, convert the smaller operand
1310  // to the bigger result.
1311  if (LHSFloat && RHSFloat) {
1312  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1313  if (order > 0) {
1314  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1315  return LHSType;
1316  }
1317 
1318  assert(order < 0 && "illegal float comparison");
1319  if (!IsCompAssign)
1320  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1321  return RHSType;
1322  }
1323 
1324  if (LHSFloat) {
1325  // Half FP has to be promoted to float unless it is natively supported
1326  if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1327  LHSType = S.Context.FloatTy;
1328 
1329  return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1330  /*ConvertFloat=*/!IsCompAssign,
1331  /*ConvertInt=*/ true);
1332  }
1333  assert(RHSFloat);
1334  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1335  /*ConvertFloat=*/ true,
1336  /*ConvertInt=*/!IsCompAssign);
1337 }
1338 
1339 /// Diagnose attempts to convert between __float128, __ibm128 and
1340 /// long double if there is no support for such conversion.
1341 /// Helper function of UsualArithmeticConversions().
1342 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1343  QualType RHSType) {
1344  // No issue if either is not a floating point type.
1345  if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1346  return false;
1347 
1348  // No issue if both have the same 128-bit float semantics.
1349  auto *LHSComplex = LHSType->getAs<ComplexType>();
1350  auto *RHSComplex = RHSType->getAs<ComplexType>();
1351 
1352  QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1353  QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1354 
1355  const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1356  const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1357 
1358  if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1359  &RHSSem != &llvm::APFloat::IEEEquad()) &&
1360  (&LHSSem != &llvm::APFloat::IEEEquad() ||
1361  &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1362  return false;
1363 
1364  return true;
1365 }
1366 
1367 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1368 
1369 namespace {
1370 /// These helper callbacks are placed in an anonymous namespace to
1371 /// permit their use as function template parameters.
1372 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1373  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1374 }
1375 
1376 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1377  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1378  CK_IntegralComplexCast);
1379 }
1380 }
1381 
1382 /// Handle integer arithmetic conversions. Helper function of
1383 /// UsualArithmeticConversions()
1384 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1386  ExprResult &RHS, QualType LHSType,
1387  QualType RHSType, bool IsCompAssign) {
1388  // The rules for this case are in C99 6.3.1.8
1389  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1390  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1391  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1392  if (LHSSigned == RHSSigned) {
1393  // Same signedness; use the higher-ranked type
1394  if (order >= 0) {
1395  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1396  return LHSType;
1397  } else if (!IsCompAssign)
1398  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1399  return RHSType;
1400  } else if (order != (LHSSigned ? 1 : -1)) {
1401  // The unsigned type has greater than or equal rank to the
1402  // signed type, so use the unsigned type
1403  if (RHSSigned) {
1404  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1405  return LHSType;
1406  } else if (!IsCompAssign)
1407  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1408  return RHSType;
1409  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1410  // The two types are different widths; if we are here, that
1411  // means the signed type is larger than the unsigned type, so
1412  // use the signed type.
1413  if (LHSSigned) {
1414  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1415  return LHSType;
1416  } else if (!IsCompAssign)
1417  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1418  return RHSType;
1419  } else {
1420  // The signed type is higher-ranked than the unsigned type,
1421  // but isn't actually any bigger (like unsigned int and long
1422  // on most 32-bit systems). Use the unsigned type corresponding
1423  // to the signed type.
1424  QualType result =
1425  S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1426  RHS = (*doRHSCast)(S, RHS.get(), result);
1427  if (!IsCompAssign)
1428  LHS = (*doLHSCast)(S, LHS.get(), result);
1429  return result;
1430  }
1431 }
1432 
1433 /// Handle conversions with GCC complex int extension. Helper function
1434 /// of UsualArithmeticConversions()
1436  ExprResult &RHS, QualType LHSType,
1437  QualType RHSType,
1438  bool IsCompAssign) {
1439  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1440  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1441 
1442  if (LHSComplexInt && RHSComplexInt) {
1443  QualType LHSEltType = LHSComplexInt->getElementType();
1444  QualType RHSEltType = RHSComplexInt->getElementType();
1445  QualType ScalarType =
1446  handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1447  (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1448 
1449  return S.Context.getComplexType(ScalarType);
1450  }
1451 
1452  if (LHSComplexInt) {
1453  QualType LHSEltType = LHSComplexInt->getElementType();
1454  QualType ScalarType =
1455  handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1456  (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1457  QualType ComplexType = S.Context.getComplexType(ScalarType);
1458  RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1459  CK_IntegralRealToComplex);
1460 
1461  return ComplexType;
1462  }
1463 
1464  assert(RHSComplexInt);
1465 
1466  QualType RHSEltType = RHSComplexInt->getElementType();
1467  QualType ScalarType =
1468  handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1469  (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1470  QualType ComplexType = S.Context.getComplexType(ScalarType);
1471 
1472  if (!IsCompAssign)
1473  LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1474  CK_IntegralRealToComplex);
1475  return ComplexType;
1476 }
1477 
1478 /// Return the rank of a given fixed point or integer type. The value itself
1479 /// doesn't matter, but the values must be increasing with proper increasing
1480 /// rank as described in N1169 4.1.1.
1481 static unsigned GetFixedPointRank(QualType Ty) {
1482  const auto *BTy = Ty->getAs<BuiltinType>();
1483  assert(BTy && "Expected a builtin type.");
1484 
1485  switch (BTy->getKind()) {
1486  case BuiltinType::ShortFract:
1487  case BuiltinType::UShortFract:
1488  case BuiltinType::SatShortFract:
1489  case BuiltinType::SatUShortFract:
1490  return 1;
1491  case BuiltinType::Fract:
1492  case BuiltinType::UFract:
1493  case BuiltinType::SatFract:
1494  case BuiltinType::SatUFract:
1495  return 2;
1496  case BuiltinType::LongFract:
1497  case BuiltinType::ULongFract:
1498  case BuiltinType::SatLongFract:
1499  case BuiltinType::SatULongFract:
1500  return 3;
1501  case BuiltinType::ShortAccum:
1502  case BuiltinType::UShortAccum:
1503  case BuiltinType::SatShortAccum:
1504  case BuiltinType::SatUShortAccum:
1505  return 4;
1506  case BuiltinType::Accum:
1507  case BuiltinType::UAccum:
1508  case BuiltinType::SatAccum:
1509  case BuiltinType::SatUAccum:
1510  return 5;
1511  case BuiltinType::LongAccum:
1512  case BuiltinType::ULongAccum:
1513  case BuiltinType::SatLongAccum:
1514  case BuiltinType::SatULongAccum:
1515  return 6;
1516  default:
1517  if (BTy->isInteger())
1518  return 0;
1519  llvm_unreachable("Unexpected fixed point or integer type");
1520  }
1521 }
1522 
1523 /// handleFixedPointConversion - Fixed point operations between fixed
1524 /// point types and integers or other fixed point types do not fall under
1525 /// usual arithmetic conversion since these conversions could result in loss
1526 /// of precsision (N1169 4.1.4). These operations should be calculated with
1527 /// the full precision of their result type (N1169 4.1.6.2.1).
1529  QualType RHSTy) {
1530  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1531  "Expected at least one of the operands to be a fixed point type");
1532  assert((LHSTy->isFixedPointOrIntegerType() ||
1533  RHSTy->isFixedPointOrIntegerType()) &&
1534  "Special fixed point arithmetic operation conversions are only "
1535  "applied to ints or other fixed point types");
1536 
1537  // If one operand has signed fixed-point type and the other operand has
1538  // unsigned fixed-point type, then the unsigned fixed-point operand is
1539  // converted to its corresponding signed fixed-point type and the resulting
1540  // type is the type of the converted operand.
1541  if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1543  else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1545 
1546  // The result type is the type with the highest rank, whereby a fixed-point
1547  // conversion rank is always greater than an integer conversion rank; if the
1548  // type of either of the operands is a saturating fixedpoint type, the result
1549  // type shall be the saturating fixed-point type corresponding to the type
1550  // with the highest rank; the resulting value is converted (taking into
1551  // account rounding and overflow) to the precision of the resulting type.
1552  // Same ranks between signed and unsigned types are resolved earlier, so both
1553  // types are either signed or both unsigned at this point.
1554  unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1555  unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1556 
1557  QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1558 
1559  if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1560  ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1561 
1562  return ResultTy;
1563 }
1564 
1565 /// Check that the usual arithmetic conversions can be performed on this pair of
1566 /// expressions that might be of enumeration type.
1567 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1569  Sema::ArithConvKind ACK) {
1570  // C++2a [expr.arith.conv]p1:
1571  // If one operand is of enumeration type and the other operand is of a
1572  // different enumeration type or a floating-point type, this behavior is
1573  // deprecated ([depr.arith.conv.enum]).
1574  //
1575  // Warn on this in all language modes. Produce a deprecation warning in C++20.
1576  // Eventually we will presumably reject these cases (in C++23 onwards?).
1577  QualType L = LHS->getEnumCoercedType(S.Context),
1578  R = RHS->getEnumCoercedType(S.Context);
1579  bool LEnum = L->isUnscopedEnumerationType(),
1580  REnum = R->isUnscopedEnumerationType();
1581  bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1582  if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1583  (REnum && L->isFloatingType())) {
1584  S.Diag(Loc, S.getLangOpts().CPlusPlus26
1585  ? diag::err_arith_conv_enum_float_cxx26
1586  : S.getLangOpts().CPlusPlus20
1587  ? diag::warn_arith_conv_enum_float_cxx20
1588  : diag::warn_arith_conv_enum_float)
1589  << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1590  << L << R;
1591  } else if (!IsCompAssign && LEnum && REnum &&
1592  !S.Context.hasSameUnqualifiedType(L, R)) {
1593  unsigned DiagID;
1594  // In C++ 26, usual arithmetic conversions between 2 different enum types
1595  // are ill-formed.
1596  if (S.getLangOpts().CPlusPlus26)
1597  DiagID = diag::err_conv_mixed_enum_types_cxx26;
1598  else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1599  !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1600  // If either enumeration type is unnamed, it's less likely that the
1601  // user cares about this, but this situation is still deprecated in
1602  // C++2a. Use a different warning group.
1603  DiagID = S.getLangOpts().CPlusPlus20
1604  ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1605  : diag::warn_arith_conv_mixed_anon_enum_types;
1606  } else if (ACK == Sema::ACK_Conditional) {
1607  // Conditional expressions are separated out because they have
1608  // historically had a different warning flag.
1609  DiagID = S.getLangOpts().CPlusPlus20
1610  ? diag::warn_conditional_mixed_enum_types_cxx20
1611  : diag::warn_conditional_mixed_enum_types;
1612  } else if (ACK == Sema::ACK_Comparison) {
1613  // Comparison expressions are separated out because they have
1614  // historically had a different warning flag.
1615  DiagID = S.getLangOpts().CPlusPlus20
1616  ? diag::warn_comparison_mixed_enum_types_cxx20
1617  : diag::warn_comparison_mixed_enum_types;
1618  } else {
1619  DiagID = S.getLangOpts().CPlusPlus20
1620  ? diag::warn_arith_conv_mixed_enum_types_cxx20
1621  : diag::warn_arith_conv_mixed_enum_types;
1622  }
1623  S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1624  << (int)ACK << L << R;
1625  }
1626 }
1627 
1628 /// UsualArithmeticConversions - Performs various conversions that are common to
1629 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1630 /// routine returns the first non-arithmetic type found. The client is
1631 /// responsible for emitting appropriate error diagnostics.
1634  ArithConvKind ACK) {
1635  checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1636 
1637  if (ACK != ACK_CompAssign) {
1638  LHS = UsualUnaryConversions(LHS.get());
1639  if (LHS.isInvalid())
1640  return QualType();
1641  }
1642 
1643  RHS = UsualUnaryConversions(RHS.get());
1644  if (RHS.isInvalid())
1645  return QualType();
1646 
1647  // For conversion purposes, we ignore any qualifiers.
1648  // For example, "const float" and "float" are equivalent.
1649  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1650  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1651 
1652  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1653  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1654  LHSType = AtomicLHS->getValueType();
1655 
1656  // If both types are identical, no conversion is needed.
1657  if (Context.hasSameType(LHSType, RHSType))
1658  return Context.getCommonSugaredType(LHSType, RHSType);
1659 
1660  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1661  // The caller can deal with this (e.g. pointer + int).
1662  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1663  return QualType();
1664 
1665  // Apply unary and bitfield promotions to the LHS's type.
1666  QualType LHSUnpromotedType = LHSType;
1667  if (Context.isPromotableIntegerType(LHSType))
1668  LHSType = Context.getPromotedIntegerType(LHSType);
1669  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1670  if (!LHSBitfieldPromoteTy.isNull())
1671  LHSType = LHSBitfieldPromoteTy;
1672  if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1673  LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1674 
1675  // If both types are identical, no conversion is needed.
1676  if (Context.hasSameType(LHSType, RHSType))
1677  return Context.getCommonSugaredType(LHSType, RHSType);
1678 
1679  // At this point, we have two different arithmetic types.
1680 
1681  // Diagnose attempts to convert between __ibm128, __float128 and long double
1682  // where such conversions currently can't be handled.
1683  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1684  return QualType();
1685 
1686  // Handle complex types first (C99 6.3.1.8p1).
1687  if (LHSType->isComplexType() || RHSType->isComplexType())
1688  return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1689  ACK == ACK_CompAssign);
1690 
1691  // Now handle "real" floating types (i.e. float, double, long double).
1692  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1693  return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1694  ACK == ACK_CompAssign);
1695 
1696  // Handle GCC complex int extension.
1697  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1698  return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1699  ACK == ACK_CompAssign);
1700 
1701  if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1702  return handleFixedPointConversion(*this, LHSType, RHSType);
1703 
1704  // Finally, we have two differing integer types.
1705  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1706  (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1707 }
1708 
1709 //===----------------------------------------------------------------------===//
1710 // Semantic Analysis for various Expression Types
1711 //===----------------------------------------------------------------------===//
1712 
1713 
1715  SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1716  bool PredicateIsExpr, void *ControllingExprOrType,
1717  ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1718  unsigned NumAssocs = ArgTypes.size();
1719  assert(NumAssocs == ArgExprs.size());
1720 
1721  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1722  for (unsigned i = 0; i < NumAssocs; ++i) {
1723  if (ArgTypes[i])
1724  (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1725  else
1726  Types[i] = nullptr;
1727  }
1728 
1729  // If we have a controlling type, we need to convert it from a parsed type
1730  // into a semantic type and then pass that along.
1731  if (!PredicateIsExpr) {
1732  TypeSourceInfo *ControllingType;
1733  (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1734  &ControllingType);
1735  assert(ControllingType && "couldn't get the type out of the parser");
1736  ControllingExprOrType = ControllingType;
1737  }
1738 
1739  ExprResult ER = CreateGenericSelectionExpr(
1740  KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1741  llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1742  delete [] Types;
1743  return ER;
1744 }
1745 
1747  SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1748  bool PredicateIsExpr, void *ControllingExprOrType,
1750  unsigned NumAssocs = Types.size();
1751  assert(NumAssocs == Exprs.size());
1752  assert(ControllingExprOrType &&
1753  "Must have either a controlling expression or a controlling type");
1754 
1755  Expr *ControllingExpr = nullptr;
1756  TypeSourceInfo *ControllingType = nullptr;
1757  if (PredicateIsExpr) {
1758  // Decay and strip qualifiers for the controlling expression type, and
1759  // handle placeholder type replacement. See committee discussion from WG14
1760  // DR423.
1763  ExprResult R = DefaultFunctionArrayLvalueConversion(
1764  reinterpret_cast<Expr *>(ControllingExprOrType));
1765  if (R.isInvalid())
1766  return ExprError();
1767  ControllingExpr = R.get();
1768  } else {
1769  // The extension form uses the type directly rather than converting it.
1770  ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1771  if (!ControllingType)
1772  return ExprError();
1773  }
1774 
1775  bool TypeErrorFound = false,
1776  IsResultDependent = ControllingExpr
1777  ? ControllingExpr->isTypeDependent()
1778  : ControllingType->getType()->isDependentType(),
1779  ContainsUnexpandedParameterPack =
1780  ControllingExpr
1781  ? ControllingExpr->containsUnexpandedParameterPack()
1782  : ControllingType->getType()->containsUnexpandedParameterPack();
1783 
1784  // The controlling expression is an unevaluated operand, so side effects are
1785  // likely unintended.
1786  if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1787  ControllingExpr->HasSideEffects(Context, false))
1788  Diag(ControllingExpr->getExprLoc(),
1789  diag::warn_side_effects_unevaluated_context);
1790 
1791  for (unsigned i = 0; i < NumAssocs; ++i) {
1792  if (Exprs[i]->containsUnexpandedParameterPack())
1793  ContainsUnexpandedParameterPack = true;
1794 
1795  if (Types[i]) {
1796  if (Types[i]->getType()->containsUnexpandedParameterPack())
1797  ContainsUnexpandedParameterPack = true;
1798 
1799  if (Types[i]->getType()->isDependentType()) {
1800  IsResultDependent = true;
1801  } else {
1802  // We relax the restriction on use of incomplete types and non-object
1803  // types with the type-based extension of _Generic. Allowing incomplete
1804  // objects means those can be used as "tags" for a type-safe way to map
1805  // to a value. Similarly, matching on function types rather than
1806  // function pointer types can be useful. However, the restriction on VM
1807  // types makes sense to retain as there are open questions about how
1808  // the selection can be made at compile time.
1809  //
1810  // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1811  // complete object type other than a variably modified type."
1812  unsigned D = 0;
1813  if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1814  D = diag::err_assoc_type_incomplete;
1815  else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1816  D = diag::err_assoc_type_nonobject;
1817  else if (Types[i]->getType()->isVariablyModifiedType())
1818  D = diag::err_assoc_type_variably_modified;
1819  else if (ControllingExpr) {
1820  // Because the controlling expression undergoes lvalue conversion,
1821  // array conversion, and function conversion, an association which is
1822  // of array type, function type, or is qualified can never be
1823  // reached. We will warn about this so users are less surprised by
1824  // the unreachable association. However, we don't have to handle
1825  // function types; that's not an object type, so it's handled above.
1826  //
1827  // The logic is somewhat different for C++ because C++ has different
1828  // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1829  // If T is a non-class type, the type of the prvalue is the cv-
1830  // unqualified version of T. Otherwise, the type of the prvalue is T.
1831  // The result of these rules is that all qualified types in an
1832  // association in C are unreachable, and in C++, only qualified non-
1833  // class types are unreachable.
1834  //
1835  // NB: this does not apply when the first operand is a type rather
1836  // than an expression, because the type form does not undergo
1837  // conversion.
1838  unsigned Reason = 0;
1839  QualType QT = Types[i]->getType();
1840  if (QT->isArrayType())
1841  Reason = 1;
1842  else if (QT.hasQualifiers() &&
1843  (!LangOpts.CPlusPlus || !QT->isRecordType()))
1844  Reason = 2;
1845 
1846  if (Reason)
1847  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1848  diag::warn_unreachable_association)
1849  << QT << (Reason - 1);
1850  }
1851 
1852  if (D != 0) {
1853  Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1854  << Types[i]->getTypeLoc().getSourceRange()
1855  << Types[i]->getType();
1856  TypeErrorFound = true;
1857  }
1858 
1859  // C11 6.5.1.1p2 "No two generic associations in the same generic
1860  // selection shall specify compatible types."
1861  for (unsigned j = i+1; j < NumAssocs; ++j)
1862  if (Types[j] && !Types[j]->getType()->isDependentType() &&
1863  Context.typesAreCompatible(Types[i]->getType(),
1864  Types[j]->getType())) {
1865  Diag(Types[j]->getTypeLoc().getBeginLoc(),
1866  diag::err_assoc_compatible_types)
1867  << Types[j]->getTypeLoc().getSourceRange()
1868  << Types[j]->getType()
1869  << Types[i]->getType();
1870  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1871  diag::note_compat_assoc)
1872  << Types[i]->getTypeLoc().getSourceRange()
1873  << Types[i]->getType();
1874  TypeErrorFound = true;
1875  }
1876  }
1877  }
1878  }
1879  if (TypeErrorFound)
1880  return ExprError();
1881 
1882  // If we determined that the generic selection is result-dependent, don't
1883  // try to compute the result expression.
1884  if (IsResultDependent) {
1885  if (ControllingExpr)
1886  return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1887  Types, Exprs, DefaultLoc, RParenLoc,
1888  ContainsUnexpandedParameterPack);
1889  return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1890  Exprs, DefaultLoc, RParenLoc,
1891  ContainsUnexpandedParameterPack);
1892  }
1893 
1894  SmallVector<unsigned, 1> CompatIndices;
1895  unsigned DefaultIndex = -1U;
1896  // Look at the canonical type of the controlling expression in case it was a
1897  // deduced type like __auto_type. However, when issuing diagnostics, use the
1898  // type the user wrote in source rather than the canonical one.
1899  for (unsigned i = 0; i < NumAssocs; ++i) {
1900  if (!Types[i])
1901  DefaultIndex = i;
1902  else if (ControllingExpr &&
1903  Context.typesAreCompatible(
1904  ControllingExpr->getType().getCanonicalType(),
1905  Types[i]->getType()))
1906  CompatIndices.push_back(i);
1907  else if (ControllingType &&
1908  Context.typesAreCompatible(
1909  ControllingType->getType().getCanonicalType(),
1910  Types[i]->getType()))
1911  CompatIndices.push_back(i);
1912  }
1913 
1914  auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1915  TypeSourceInfo *ControllingType) {
1916  // We strip parens here because the controlling expression is typically
1917  // parenthesized in macro definitions.
1918  if (ControllingExpr)
1919  ControllingExpr = ControllingExpr->IgnoreParens();
1920 
1921  SourceRange SR = ControllingExpr
1922  ? ControllingExpr->getSourceRange()
1923  : ControllingType->getTypeLoc().getSourceRange();
1924  QualType QT = ControllingExpr ? ControllingExpr->getType()
1925  : ControllingType->getType();
1926 
1927  return std::make_pair(SR, QT);
1928  };
1929 
1930  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1931  // type compatible with at most one of the types named in its generic
1932  // association list."
1933  if (CompatIndices.size() > 1) {
1934  auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1935  SourceRange SR = P.first;
1936  Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1937  << SR << P.second << (unsigned)CompatIndices.size();
1938  for (unsigned I : CompatIndices) {
1939  Diag(Types[I]->getTypeLoc().getBeginLoc(),
1940  diag::note_compat_assoc)
1941  << Types[I]->getTypeLoc().getSourceRange()
1942  << Types[I]->getType();
1943  }
1944  return ExprError();
1945  }
1946 
1947  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1948  // its controlling expression shall have type compatible with exactly one of
1949  // the types named in its generic association list."
1950  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1951  auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1952  SourceRange SR = P.first;
1953  Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1954  return ExprError();
1955  }
1956 
1957  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1958  // type name that is compatible with the type of the controlling expression,
1959  // then the result expression of the generic selection is the expression
1960  // in that generic association. Otherwise, the result expression of the
1961  // generic selection is the expression in the default generic association."
1962  unsigned ResultIndex =
1963  CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1964 
1965  if (ControllingExpr) {
1967  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1968  ContainsUnexpandedParameterPack, ResultIndex);
1969  }
1971  Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1972  ContainsUnexpandedParameterPack, ResultIndex);
1973 }
1974 
1976  switch (Kind) {
1977  default:
1978  llvm_unreachable("unexpected TokenKind");
1979  case tok::kw___func__:
1980  return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1981  case tok::kw___FUNCTION__:
1983  case tok::kw___FUNCDNAME__:
1984  return PredefinedIdentKind::FuncDName; // [MS]
1985  case tok::kw___FUNCSIG__:
1986  return PredefinedIdentKind::FuncSig; // [MS]
1987  case tok::kw_L__FUNCTION__:
1988  return PredefinedIdentKind::LFunction; // [MS]
1989  case tok::kw_L__FUNCSIG__:
1990  return PredefinedIdentKind::LFuncSig; // [MS]
1991  case tok::kw___PRETTY_FUNCTION__:
1992  return PredefinedIdentKind::PrettyFunction; // [GNU]
1993  }
1994 }
1995 
1996 /// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1997 /// to determine the value of a PredefinedExpr. This can be either a
1998 /// block, lambda, captured statement, function, otherwise a nullptr.
2000  while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
2001  DC = DC->getParent();
2002  return cast_or_null<Decl>(DC);
2003 }
2004 
2005 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2006 /// location of the token and the offset of the ud-suffix within it.
2008  unsigned Offset) {
2010  S.getLangOpts());
2011 }
2012 
2013 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2014 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
2016  IdentifierInfo *UDSuffix,
2017  SourceLocation UDSuffixLoc,
2018  ArrayRef<Expr*> Args,
2019  SourceLocation LitEndLoc) {
2020  assert(Args.size() <= 2 && "too many arguments for literal operator");
2021 
2022  QualType ArgTy[2];
2023  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2024  ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2025  if (ArgTy[ArgIdx]->isArrayType())
2026  ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2027  }
2028 
2029  DeclarationName OpName =
2031  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2032  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2033 
2034  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2035  if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2036  /*AllowRaw*/ false, /*AllowTemplate*/ false,
2037  /*AllowStringTemplatePack*/ false,
2038  /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2039  return ExprError();
2040 
2041  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2042 }
2043 
2045  // StringToks needs backing storage as it doesn't hold array elements itself
2046  std::vector<Token> ExpandedToks;
2047  if (getLangOpts().MicrosoftExt)
2048  StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2049 
2050  StringLiteralParser Literal(StringToks, PP,
2052  if (Literal.hadError)
2053  return ExprError();
2054 
2055  SmallVector<SourceLocation, 4> StringTokLocs;
2056  for (const Token &Tok : StringToks)
2057  StringTokLocs.push_back(Tok.getLocation());
2058 
2060  Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
2061  &StringTokLocs[0], StringTokLocs.size());
2062 
2063  if (!Literal.getUDSuffix().empty()) {
2064  SourceLocation UDSuffixLoc =
2065  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2066  Literal.getUDSuffixOffset());
2067  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2068  }
2069 
2070  return Lit;
2071 }
2072 
2073 std::vector<Token>
2075  // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2076  // local macros that expand to string literals that may be concatenated.
2077  // These macros are expanded here (in Sema), because StringLiteralParser
2078  // (in Lex) doesn't know the enclosing function (because it hasn't been
2079  // parsed yet).
2080  assert(getLangOpts().MicrosoftExt);
2081 
2082  // Note: Although function local macros are defined only inside functions,
2083  // we ensure a valid `CurrentDecl` even outside of a function. This allows
2084  // expansion of macros into empty string literals without additional checks.
2085  Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2086  if (!CurrentDecl)
2087  CurrentDecl = Context.getTranslationUnitDecl();
2088 
2089  std::vector<Token> ExpandedToks;
2090  ExpandedToks.reserve(Toks.size());
2091  for (const Token &Tok : Toks) {
2092  if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2093  assert(tok::isStringLiteral(Tok.getKind()));
2094  ExpandedToks.emplace_back(Tok);
2095  continue;
2096  }
2097  if (isa<TranslationUnitDecl>(CurrentDecl))
2098  Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2099  // Stringify predefined expression
2100  Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2101  << Tok.getKind();
2102  SmallString<64> Str;
2103  llvm::raw_svector_ostream OS(Str);
2104  Token &Exp = ExpandedToks.emplace_back();
2105  Exp.startToken();
2106  if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2107  Tok.getKind() == tok::kw_L__FUNCSIG__) {
2108  OS << 'L';
2109  Exp.setKind(tok::wide_string_literal);
2110  } else {
2111  Exp.setKind(tok::string_literal);
2112  }
2113  OS << '"'
2115  getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2116  << '"';
2117  PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2118  }
2119  return ExpandedToks;
2120 }
2121 
2122 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2123 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2124 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2125 /// multiple tokens. However, the common case is that StringToks points to one
2126 /// string.
2127 ///
2128 ExprResult
2130  assert(!StringToks.empty() && "Must have at least one string!");
2131 
2132  // StringToks needs backing storage as it doesn't hold array elements itself
2133  std::vector<Token> ExpandedToks;
2134  if (getLangOpts().MicrosoftExt)
2135  StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2136 
2137  StringLiteralParser Literal(StringToks, PP);
2138  if (Literal.hadError)
2139  return ExprError();
2140 
2141  SmallVector<SourceLocation, 4> StringTokLocs;
2142  for (const Token &Tok : StringToks)
2143  StringTokLocs.push_back(Tok.getLocation());
2144 
2145  QualType CharTy = Context.CharTy;
2147  if (Literal.isWide()) {
2148  CharTy = Context.getWideCharType();
2150  } else if (Literal.isUTF8()) {
2151  if (getLangOpts().Char8)
2152  CharTy = Context.Char8Ty;
2154  } else if (Literal.isUTF16()) {
2155  CharTy = Context.Char16Ty;
2157  } else if (Literal.isUTF32()) {
2158  CharTy = Context.Char32Ty;
2160  } else if (Literal.isPascal()) {
2161  CharTy = Context.UnsignedCharTy;
2162  }
2163 
2164  // Warn on initializing an array of char from a u8 string literal; this
2165  // becomes ill-formed in C++2a.
2166  if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
2167  !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2168  Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2169 
2170  // Create removals for all 'u8' prefixes in the string literal(s). This
2171  // ensures C++2a compatibility (but may change the program behavior when
2172  // built by non-Clang compilers for which the execution character set is
2173  // not always UTF-8).
2174  auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2175  SourceLocation RemovalDiagLoc;
2176  for (const Token &Tok : StringToks) {
2177  if (Tok.getKind() == tok::utf8_string_literal) {
2178  if (RemovalDiagLoc.isInvalid())
2179  RemovalDiagLoc = Tok.getLocation();
2181  Tok.getLocation(),
2182  Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2183  getSourceManager(), getLangOpts())));
2184  }
2185  }
2186  Diag(RemovalDiagLoc, RemovalDiag);
2187  }
2188 
2189  QualType StrTy =
2190  Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2191 
2192  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2193  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2194  Kind, Literal.Pascal, StrTy,
2195  &StringTokLocs[0],
2196  StringTokLocs.size());
2197  if (Literal.getUDSuffix().empty())
2198  return Lit;
2199 
2200  // We're building a user-defined literal.
2201  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2202  SourceLocation UDSuffixLoc =
2203  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2204  Literal.getUDSuffixOffset());
2205 
2206  // Make sure we're allowed user-defined literals here.
2207  if (!UDLScope)
2208  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2209 
2210  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2211  // operator "" X (str, len)
2212  QualType SizeType = Context.getSizeType();
2213 
2214  DeclarationName OpName =
2215  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2216  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2217  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2218 
2219  QualType ArgTy[] = {
2220  Context.getArrayDecayedType(StrTy), SizeType
2221  };
2222 
2223  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2224  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2225  /*AllowRaw*/ false, /*AllowTemplate*/ true,
2226  /*AllowStringTemplatePack*/ true,
2227  /*DiagnoseMissing*/ true, Lit)) {
2228 
2229  case LOLR_Cooked: {
2230  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2231  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2232  StringTokLocs[0]);
2233  Expr *Args[] = { Lit, LenArg };
2234 
2235  return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2236  }
2237 
2238  case LOLR_Template: {
2239  TemplateArgumentListInfo ExplicitArgs;
2240  TemplateArgument Arg(Lit);
2241  TemplateArgumentLocInfo ArgInfo(Lit);
2242  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2243  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2244  StringTokLocs.back(), &ExplicitArgs);
2245  }
2246 
2247  case LOLR_StringTemplatePack: {
2248  TemplateArgumentListInfo ExplicitArgs;
2249 
2250  unsigned CharBits = Context.getIntWidth(CharTy);
2251  bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2252  llvm::APSInt Value(CharBits, CharIsUnsigned);
2253 
2254  TemplateArgument TypeArg(CharTy);
2255  TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2256  ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2257 
2258  for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2259  Value = Lit->getCodeUnit(I);
2260  TemplateArgument Arg(Context, Value, CharTy);
2261  TemplateArgumentLocInfo ArgInfo;
2262  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2263  }
2264  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2265  StringTokLocs.back(), &ExplicitArgs);
2266  }
2267  case LOLR_Raw:
2268  case LOLR_ErrorNoDiagnostic:
2269  llvm_unreachable("unexpected literal operator lookup result");
2270  case LOLR_Error:
2271  return ExprError();
2272  }
2273  llvm_unreachable("unexpected literal operator lookup result");
2274 }
2275 
2276 DeclRefExpr *
2279  const CXXScopeSpec *SS) {
2280  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2281  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2282 }
2283 
2284 DeclRefExpr *
2286  const DeclarationNameInfo &NameInfo,
2287  const CXXScopeSpec *SS, NamedDecl *FoundD,
2288  SourceLocation TemplateKWLoc,
2289  const TemplateArgumentListInfo *TemplateArgs) {
2291  SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2292  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2293  TemplateArgs);
2294 }
2295 
2296 // CUDA/HIP: Check whether a captured reference variable is referencing a
2297 // host variable in a device or host device lambda.
2299  VarDecl *VD) {
2300  if (!S.getLangOpts().CUDA || !VD->hasInit())
2301  return false;
2302  assert(VD->getType()->isReferenceType());
2303 
2304  // Check whether the reference variable is referencing a host variable.
2305  auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2306  if (!DRE)
2307  return false;
2308  auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2309  if (!Referee || !Referee->hasGlobalStorage() ||
2310  Referee->hasAttr<CUDADeviceAttr>())
2311  return false;
2312 
2313  // Check whether the current function is a device or host device lambda.
2314  // Check whether the reference variable is a capture by getDeclContext()
2315  // since refersToEnclosingVariableOrCapture() is not ready at this point.
2316  auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2317  if (MD && MD->getParent()->isLambda() &&
2318  MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2319  VD->getDeclContext() != MD)
2320  return true;
2321 
2322  return false;
2323 }
2324 
2326  // A declaration named in an unevaluated operand never constitutes an odr-use.
2327  if (isUnevaluatedContext())
2328  return NOUR_Unevaluated;
2329 
2330  // C++2a [basic.def.odr]p4:
2331  // A variable x whose name appears as a potentially-evaluated expression e
2332  // is odr-used by e unless [...] x is a reference that is usable in
2333  // constant expressions.
2334  // CUDA/HIP:
2335  // If a reference variable referencing a host variable is captured in a
2336  // device or host device lambda, the value of the referee must be copied
2337  // to the capture and the reference variable must be treated as odr-use
2338  // since the value of the referee is not known at compile time and must
2339  // be loaded from the captured.
2340  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2341  if (VD->getType()->isReferenceType() &&
2342  !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2344  VD->isUsableInConstantExpressions(Context))
2345  return NOUR_Constant;
2346  }
2347 
2348  // All remaining non-variable cases constitute an odr-use. For variables, we
2349  // need to wait and see how the expression is used.
2350  return NOUR_None;
2351 }
2352 
2353 /// BuildDeclRefExpr - Build an expression that references a
2354 /// declaration that does not require a closure capture.
2355 DeclRefExpr *
2357  const DeclarationNameInfo &NameInfo,
2358  NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2359  SourceLocation TemplateKWLoc,
2360  const TemplateArgumentListInfo *TemplateArgs) {
2361  bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2362  NeedToCaptureVariable(D, NameInfo.getLoc());
2363 
2365  Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2366  VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2367  MarkDeclRefReferenced(E);
2368 
2369  // C++ [except.spec]p17:
2370  // An exception-specification is considered to be needed when:
2371  // - in an expression, the function is the unique lookup result or
2372  // the selected member of a set of overloaded functions.
2373  //
2374  // We delay doing this until after we've built the function reference and
2375  // marked it as used so that:
2376  // a) if the function is defaulted, we get errors from defining it before /
2377  // instead of errors from computing its exception specification, and
2378  // b) if the function is a defaulted comparison, we can use the body we
2379  // build when defining it as input to the exception specification
2380  // computation rather than computing a new body.
2381  if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2382  if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2383  if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2384  E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2385  }
2386  }
2387 
2388  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2389  Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2390  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2391  getCurFunction()->recordUseOfWeak(E);
2392 
2393  const auto *FD = dyn_cast<FieldDecl>(D);
2394  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2395  FD = IFD->getAnonField();
2396  if (FD) {
2397  UnusedPrivateFields.remove(FD);
2398  // Just in case we're building an illegal pointer-to-member.
2399  if (FD->isBitField())
2401  }
2402 
2403  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2404  // designates a bit-field.
2405  if (const auto *BD = dyn_cast<BindingDecl>(D))
2406  if (const auto *BE = BD->getBinding())
2407  E->setObjectKind(BE->getObjectKind());
2408 
2409  return E;
2410 }
2411 
2412 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2413 /// possibly a list of template arguments.
2414 ///
2415 /// If this produces template arguments, it is permitted to call
2416 /// DecomposeTemplateName.
2417 ///
2418 /// This actually loses a lot of source location information for
2419 /// non-standard name kinds; we should consider preserving that in
2420 /// some way.
2421 void
2423  TemplateArgumentListInfo &Buffer,
2424  DeclarationNameInfo &NameInfo,
2425  const TemplateArgumentListInfo *&TemplateArgs) {
2426  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2427  Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2428  Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2429 
2430  ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2431  Id.TemplateId->NumArgs);
2432  translateTemplateArguments(TemplateArgsPtr, Buffer);
2433 
2434  TemplateName TName = Id.TemplateId->Template.get();
2435  SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2436  NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2437  TemplateArgs = &Buffer;
2438  } else {
2439  NameInfo = GetNameFromUnqualifiedId(Id);
2440  TemplateArgs = nullptr;
2441  }
2442 }
2443 
2445  const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2446  DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2447  unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2448  DeclContext *Ctx =
2449  SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2450  if (!TC) {
2451  // Emit a special diagnostic for failed member lookups.
2452  // FIXME: computing the declaration context might fail here (?)
2453  if (Ctx)
2454  SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2455  << SS.getRange();
2456  else
2457  SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2458  return;
2459  }
2460 
2461  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2462  bool DroppedSpecifier =
2463  TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2464  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2465  ? diag::note_implicit_param_decl
2466  : diag::note_previous_decl;
2467  if (!Ctx)
2468  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2469  SemaRef.PDiag(NoteID));
2470  else
2471  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2472  << Typo << Ctx << DroppedSpecifier
2473  << SS.getRange(),
2474  SemaRef.PDiag(NoteID));
2475 }
2476 
2477 /// Diagnose a lookup that found results in an enclosing class during error
2478 /// recovery. This usually indicates that the results were found in a dependent
2479 /// base class that could not be searched as part of a template definition.
2480 /// Always issues a diagnostic (though this may be only a warning in MS
2481 /// compatibility mode).
2482 ///
2483 /// Return \c true if the error is unrecoverable, or \c false if the caller
2484 /// should attempt to recover using these lookup results.
2486  // During a default argument instantiation the CurContext points
2487  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2488  // function parameter list, hence add an explicit check.
2489  bool isDefaultArgument =
2490  !CodeSynthesisContexts.empty() &&
2491  CodeSynthesisContexts.back().Kind ==
2492  CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2493  const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2494  bool isInstance = CurMethod && CurMethod->isInstance() &&
2495  R.getNamingClass() == CurMethod->getParent() &&
2496  !isDefaultArgument;
2497 
2498  // There are two ways we can find a class-scope declaration during template
2499  // instantiation that we did not find in the template definition: if it is a
2500  // member of a dependent base class, or if it is declared after the point of
2501  // use in the same class. Distinguish these by comparing the class in which
2502  // the member was found to the naming class of the lookup.
2503  unsigned DiagID = diag::err_found_in_dependent_base;
2504  unsigned NoteID = diag::note_member_declared_at;
2506  DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2507  : diag::err_found_later_in_class;
2508  } else if (getLangOpts().MSVCCompat) {
2509  DiagID = diag::ext_found_in_dependent_base;
2510  NoteID = diag::note_dependent_member_use;
2511  }
2512 
2513  if (isInstance) {
2514  // Give a code modification hint to insert 'this->'.
2515  Diag(R.getNameLoc(), DiagID)
2516  << R.getLookupName()
2517  << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2518  CheckCXXThisCapture(R.getNameLoc());
2519  } else {
2520  // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2521  // they're not shadowed).
2522  Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2523  }
2524 
2525  for (const NamedDecl *D : R)
2526  Diag(D->getLocation(), NoteID);
2527 
2528  // Return true if we are inside a default argument instantiation
2529  // and the found name refers to an instance member function, otherwise
2530  // the caller will try to create an implicit member call and this is wrong
2531  // for default arguments.
2532  //
2533  // FIXME: Is this special case necessary? We could allow the caller to
2534  // diagnose this.
2535  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2536  Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2537  return true;
2538  }
2539 
2540  // Tell the callee to try to recover.
2541  return false;
2542 }
2543 
2544 /// Diagnose an empty lookup.
2545 ///
2546 /// \return false if new lookup candidates were found
2549  TemplateArgumentListInfo *ExplicitTemplateArgs,
2550  ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2551  TypoExpr **Out) {
2552  DeclarationName Name = R.getLookupName();
2553 
2554  unsigned diagnostic = diag::err_undeclared_var_use;
2555  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2556  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2557  Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2558  Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2559  diagnostic = diag::err_undeclared_use;
2560  diagnostic_suggest = diag::err_undeclared_use_suggest;
2561  }
2562 
2563  // If the original lookup was an unqualified lookup, fake an
2564  // unqualified lookup. This is useful when (for example) the
2565  // original lookup would not have found something because it was a
2566  // dependent name.
2567  DeclContext *DC =
2568  LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2569  while (DC) {
2570  if (isa<CXXRecordDecl>(DC)) {
2571  LookupQualifiedName(R, DC);
2572 
2573  if (!R.empty()) {
2574  // Don't give errors about ambiguities in this lookup.
2575  R.suppressDiagnostics();
2576 
2577  // If there's a best viable function among the results, only mention
2578  // that one in the notes.
2579  OverloadCandidateSet Candidates(R.getNameLoc(),
2581  AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2583  if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2584  OR_Success) {
2585  R.clear();
2586  R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2587  R.resolveKind();
2588  }
2589 
2590  return DiagnoseDependentMemberLookup(R);
2591  }
2592 
2593  R.clear();
2594  }
2595 
2596  DC = DC->getLookupParent();
2597  }
2598 
2599  // We didn't find anything, so try to correct for a typo.
2600  TypoCorrection Corrected;
2601  if (S && Out) {
2602  SourceLocation TypoLoc = R.getNameLoc();
2603  assert(!ExplicitTemplateArgs &&
2604  "Diagnosing an empty lookup with explicit template args!");
2605  *Out = CorrectTypoDelayed(
2606  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2607  [=](const TypoCorrection &TC) {
2608  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2609  diagnostic, diagnostic_suggest);
2610  },
2611  nullptr, CTK_ErrorRecovery, LookupCtx);
2612  if (*Out)
2613  return true;
2614  } else if (S && (Corrected =
2615  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
2616  &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2617  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2618  bool DroppedSpecifier =
2619  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2620  R.setLookupName(Corrected.getCorrection());
2621 
2622  bool AcceptableWithRecovery = false;
2623  bool AcceptableWithoutRecovery = false;
2624  NamedDecl *ND = Corrected.getFoundDecl();
2625  if (ND) {
2626  if (Corrected.isOverloaded()) {
2630  for (NamedDecl *CD : Corrected) {
2631  if (FunctionTemplateDecl *FTD =
2632  dyn_cast<FunctionTemplateDecl>(CD))
2633  AddTemplateOverloadCandidate(
2634  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2635  Args, OCS);
2636  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2637  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2638  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2639  Args, OCS);
2640  }
2641  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2642  case OR_Success:
2643  ND = Best->FoundDecl;
2644  Corrected.setCorrectionDecl(ND);
2645  break;
2646  default:
2647  // FIXME: Arbitrarily pick the first declaration for the note.
2648  Corrected.setCorrectionDecl(ND);
2649  break;
2650  }
2651  }
2652  R.addDecl(ND);
2653  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2654  CXXRecordDecl *Record = nullptr;
2655  if (Corrected.getCorrectionSpecifier()) {
2656  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2657  Record = Ty->getAsCXXRecordDecl();
2658  }
2659  if (!Record)
2660  Record = cast<CXXRecordDecl>(
2661  ND->getDeclContext()->getRedeclContext());
2663  }
2664 
2665  auto *UnderlyingND = ND->getUnderlyingDecl();
2666  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2667  isa<FunctionTemplateDecl>(UnderlyingND);
2668  // FIXME: If we ended up with a typo for a type name or
2669  // Objective-C class name, we're in trouble because the parser
2670  // is in the wrong place to recover. Suggest the typo
2671  // correction, but don't make it a fix-it since we're not going
2672  // to recover well anyway.
2673  AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2674  getAsTypeTemplateDecl(UnderlyingND) ||
2675  isa<ObjCInterfaceDecl>(UnderlyingND);
2676  } else {
2677  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2678  // because we aren't able to recover.
2679  AcceptableWithoutRecovery = true;
2680  }
2681 
2682  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2683  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2684  ? diag::note_implicit_param_decl
2685  : diag::note_previous_decl;
2686  if (SS.isEmpty())
2687  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2688  PDiag(NoteID), AcceptableWithRecovery);
2689  else
2690  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2691  << Name << computeDeclContext(SS, false)
2692  << DroppedSpecifier << SS.getRange(),
2693  PDiag(NoteID), AcceptableWithRecovery);
2694 
2695  // Tell the callee whether to try to recover.
2696  return !AcceptableWithRecovery;
2697  }
2698  }
2699  R.clear();
2700 
2701  // Emit a special diagnostic for failed member lookups.
2702  // FIXME: computing the declaration context might fail here (?)
2703  if (!SS.isEmpty()) {
2704  Diag(R.getNameLoc(), diag::err_no_member)
2705  << Name << computeDeclContext(SS, false)
2706  << SS.getRange();
2707  return true;
2708  }
2709 
2710  // Give up, we can't recover.
2711  Diag(R.getNameLoc(), diagnostic) << Name;
2712  return true;
2713 }
2714 
2715 /// In Microsoft mode, if we are inside a template class whose parent class has
2716 /// dependent base classes, and we can't resolve an unqualified identifier, then
2717 /// assume the identifier is a member of a dependent base class. We can only
2718 /// recover successfully in static methods, instance methods, and other contexts
2719 /// where 'this' is available. This doesn't precisely match MSVC's
2720 /// instantiation model, but it's close enough.
2721 static Expr *
2723  DeclarationNameInfo &NameInfo,
2724  SourceLocation TemplateKWLoc,
2725  const TemplateArgumentListInfo *TemplateArgs) {
2726  // Only try to recover from lookup into dependent bases in static methods or
2727  // contexts where 'this' is available.
2728  QualType ThisType = S.getCurrentThisType();
2729  const CXXRecordDecl *RD = nullptr;
2730  if (!ThisType.isNull())
2731  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2732  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2733  RD = MD->getParent();
2734  if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2735  return nullptr;
2736 
2737  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2738  // is available, suggest inserting 'this->' as a fixit.
2739  SourceLocation Loc = NameInfo.getLoc();
2740  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2741  DB << NameInfo.getName() << RD;
2742 
2743  if (!ThisType.isNull()) {
2744  DB << FixItHint::CreateInsertion(Loc, "this->");
2746  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2747  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2748  /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2749  }
2750 
2751  // Synthesize a fake NNS that points to the derived class. This will
2752  // perform name lookup during template instantiation.
2753  CXXScopeSpec SS;
2754  auto *NNS =
2755  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2756  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2758  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2759  TemplateArgs);
2760 }
2761 
2762 ExprResult
2764  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2765  bool HasTrailingLParen, bool IsAddressOfOperand,
2767  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2768  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2769  "cannot be direct & operand and have a trailing lparen");
2770  if (SS.isInvalid())
2771  return ExprError();
2772 
2773  TemplateArgumentListInfo TemplateArgsBuffer;
2774 
2775  // Decompose the UnqualifiedId into the following data.
2776  DeclarationNameInfo NameInfo;
2777  const TemplateArgumentListInfo *TemplateArgs;
2778  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2779 
2780  DeclarationName Name = NameInfo.getName();
2781  IdentifierInfo *II = Name.getAsIdentifierInfo();
2782  SourceLocation NameLoc = NameInfo.getLoc();
2783 
2784  if (II && II->isEditorPlaceholder()) {
2785  // FIXME: When typed placeholders are supported we can create a typed
2786  // placeholder expression node.
2787  return ExprError();
2788  }
2789 
2790  // BoundsSafety: This specially handles arguments of bounds attributes
2791  // appertains to a type of C struct field such that the name lookup
2792  // within a struct finds the member name, which is not the case for other
2793  // contexts in C.
2794  if (isBoundsAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2795  // See if this is reference to a field of struct.
2796  LookupResult R(*this, NameInfo, LookupMemberName);
2797  // LookupName handles a name lookup from within anonymous struct.
2798  if (LookupName(R, S)) {
2799  if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2800  QualType type = VD->getType().getNonReferenceType();
2801  // This will eventually be translated into MemberExpr upon
2802  // the use of instantiated struct fields.
2803  return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2804  }
2805  }
2806  }
2807 
2808  // Perform the required lookup.
2809  LookupResult R(*this, NameInfo,
2811  ? LookupObjCImplicitSelfParam
2812  : LookupOrdinaryName);
2813  if (TemplateKWLoc.isValid() || TemplateArgs) {
2814  // Lookup the template name again to correctly establish the context in
2815  // which it was found. This is really unfortunate as we already did the
2816  // lookup to determine that it was a template name in the first place. If
2817  // this becomes a performance hit, we can work harder to preserve those
2818  // results until we get here but it's likely not worth it.
2819  AssumedTemplateKind AssumedTemplate;
2820  if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2821  /*EnteringContext=*/false, TemplateKWLoc,
2822  &AssumedTemplate))
2823  return ExprError();
2824 
2826  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2827  IsAddressOfOperand, TemplateArgs);
2828  } else {
2829  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2830  LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2831  /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2832 
2833  // If the result might be in a dependent base class, this is a dependent
2834  // id-expression.
2836  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2837  IsAddressOfOperand, TemplateArgs);
2838 
2839  // If this reference is in an Objective-C method, then we need to do
2840  // some special Objective-C lookup, too.
2841  if (IvarLookupFollowUp) {
2842  ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2843  if (E.isInvalid())
2844  return ExprError();
2845 
2846  if (Expr *Ex = E.getAs<Expr>())
2847  return Ex;
2848  }
2849  }
2850 
2851  if (R.isAmbiguous())
2852  return ExprError();
2853 
2854  // This could be an implicitly declared function reference if the language
2855  // mode allows it as a feature.
2856  if (R.empty() && HasTrailingLParen && II &&
2857  getLangOpts().implicitFunctionsAllowed()) {
2858  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2859  if (D) R.addDecl(D);
2860  }
2861 
2862  // Determine whether this name might be a candidate for
2863  // argument-dependent lookup.
2864  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2865 
2866  if (R.empty() && !ADL) {
2867  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2868  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2869  TemplateKWLoc, TemplateArgs))
2870  return E;
2871  }
2872 
2873  // Don't diagnose an empty lookup for inline assembly.
2874  if (IsInlineAsmIdentifier)
2875  return ExprError();
2876 
2877  // If this name wasn't predeclared and if this is not a function
2878  // call, diagnose the problem.
2879  TypoExpr *TE = nullptr;
2880  DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2881  : nullptr);
2882  DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2883  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2884  "Typo correction callback misconfigured");
2885  if (CCC) {
2886  // Make sure the callback knows what the typo being diagnosed is.
2887  CCC->setTypoName(II);
2888  if (SS.isValid())
2889  CCC->setTypoNNS(SS.getScopeRep());
2890  }
2891  // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2892  // a template name, but we happen to have always already looked up the name
2893  // before we get here if it must be a template name.
2894  if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2895  std::nullopt, nullptr, &TE)) {
2896  if (TE && KeywordReplacement) {
2897  auto &State = getTypoExprState(TE);
2898  auto BestTC = State.Consumer->getNextCorrection();
2899  if (BestTC.isKeyword()) {
2900  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2901  if (State.DiagHandler)
2902  State.DiagHandler(BestTC);
2903  KeywordReplacement->startToken();
2904  KeywordReplacement->setKind(II->getTokenID());
2905  KeywordReplacement->setIdentifierInfo(II);
2906  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2907  // Clean up the state associated with the TypoExpr, since it has
2908  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2909  clearDelayedTypo(TE);
2910  // Signal that a correction to a keyword was performed by returning a
2911  // valid-but-null ExprResult.
2912  return (Expr*)nullptr;
2913  }
2914  State.Consumer->resetCorrectionStream();
2915  }
2916  return TE ? TE : ExprError();
2917  }
2918 
2919  assert(!R.empty() &&
2920  "DiagnoseEmptyLookup returned false but added no results");
2921 
2922  // If we found an Objective-C instance variable, let
2923  // LookupInObjCMethod build the appropriate expression to
2924  // reference the ivar.
2925  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2926  R.clear();
2927  ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2928  // In a hopelessly buggy code, Objective-C instance variable
2929  // lookup fails and no expression will be built to reference it.
2930  if (!E.isInvalid() && !E.get())
2931  return ExprError();
2932  return E;
2933  }
2934  }
2935 
2936  // This is guaranteed from this point on.
2937  assert(!R.empty() || ADL);
2938 
2939  // Check whether this might be a C++ implicit instance member access.
2940  // C++ [class.mfct.non-static]p3:
2941  // When an id-expression that is not part of a class member access
2942  // syntax and not used to form a pointer to member is used in the
2943  // body of a non-static member function of class X, if name lookup
2944  // resolves the name in the id-expression to a non-static non-type
2945  // member of some class C, the id-expression is transformed into a
2946  // class member access expression using (*this) as the
2947  // postfix-expression to the left of the . operator.
2948  //
2949  // But we don't actually need to do this for '&' operands if R
2950  // resolved to a function or overloaded function set, because the
2951  // expression is ill-formed if it actually works out to be a
2952  // non-static member function:
2953  //
2954  // C++ [expr.ref]p4:
2955  // Otherwise, if E1.E2 refers to a non-static member function. . .
2956  // [t]he expression can be used only as the left-hand operand of a
2957  // member function call.
2958  //
2959  // There are other safeguards against such uses, but it's important
2960  // to get this right here so that we don't end up making a
2961  // spuriously dependent expression if we're inside a dependent
2962  // instance method.
2963  if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2964  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2965  S);
2966 
2967  if (TemplateArgs || TemplateKWLoc.isValid()) {
2968 
2969  // In C++1y, if this is a variable template id, then check it
2970  // in BuildTemplateIdExpr().
2971  // The single lookup result must be a variable template declaration.
2972  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2973  Id.TemplateId->Kind == TNK_Var_template) {
2974  assert(R.getAsSingle<VarTemplateDecl>() &&
2975  "There should only be one declaration found.");
2976  }
2977 
2978  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2979  }
2980 
2981  return BuildDeclarationNameExpr(SS, R, ADL);
2982 }
2983 
2984 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2985 /// declaration name, generally during template instantiation.
2986 /// There's a large number of things which don't need to be done along
2987 /// this path.
2989  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2990  bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2991  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2992  LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2993 
2994  if (R.isAmbiguous())
2995  return ExprError();
2996 
2998  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2999  NameInfo, /*TemplateArgs=*/nullptr);
3000 
3001  if (R.empty()) {
3002  // Don't diagnose problems with invalid record decl, the secondary no_member
3003  // diagnostic during template instantiation is likely bogus, e.g. if a class
3004  // is invalid because it's derived from an invalid base class, then missing
3005  // members were likely supposed to be inherited.
3006  DeclContext *DC = computeDeclContext(SS);
3007  if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3008  if (CD->isInvalidDecl())
3009  return ExprError();
3010  Diag(NameInfo.getLoc(), diag::err_no_member)
3011  << NameInfo.getName() << DC << SS.getRange();
3012  return ExprError();
3013  }
3014 
3015  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3016  // Diagnose a missing typename if this resolved unambiguously to a type in
3017  // a dependent context. If we can recover with a type, downgrade this to
3018  // a warning in Microsoft compatibility mode.
3019  unsigned DiagID = diag::err_typename_missing;
3020  if (RecoveryTSI && getLangOpts().MSVCCompat)
3021  DiagID = diag::ext_typename_missing;
3023  auto D = Diag(Loc, DiagID);
3024  D << SS.getScopeRep() << NameInfo.getName().getAsString()
3025  << SourceRange(Loc, NameInfo.getEndLoc());
3026 
3027  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3028  // context.
3029  if (!RecoveryTSI)
3030  return ExprError();
3031 
3032  // Only issue the fixit if we're prepared to recover.
3033  D << FixItHint::CreateInsertion(Loc, "typename ");
3034 
3035  // Recover by pretending this was an elaborated type.
3036  QualType Ty = Context.getTypeDeclType(TD);
3037  TypeLocBuilder TLB;
3038  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
3039 
3040  QualType ET = getElaboratedType(ElaboratedTypeKeyword::None, SS, Ty);
3041  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
3043  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
3044 
3045  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3046 
3047  return ExprEmpty();
3048  }
3049 
3050  // If necessary, build an implicit class member access.
3051  if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3052  return BuildPossibleImplicitMemberExpr(SS,
3053  /*TemplateKWLoc=*/SourceLocation(),
3054  R, /*TemplateArgs=*/nullptr,
3055  /*S=*/nullptr);
3056 
3057  return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3058 }
3059 
3060 /// Cast a base object to a member's actual type.
3061 ///
3062 /// There are two relevant checks:
3063 ///
3064 /// C++ [class.access.base]p7:
3065 ///
3066 /// If a class member access operator [...] is used to access a non-static
3067 /// data member or non-static member function, the reference is ill-formed if
3068 /// the left operand [...] cannot be implicitly converted to a pointer to the
3069 /// naming class of the right operand.
3070 ///
3071 /// C++ [expr.ref]p7:
3072 ///
3073 /// If E2 is a non-static data member or a non-static member function, the
3074 /// program is ill-formed if the class of which E2 is directly a member is an
3075 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3076 ///
3077 /// Note that the latter check does not consider access; the access of the
3078 /// "real" base class is checked as appropriate when checking the access of the
3079 /// member name.
3080 ExprResult
3082  NestedNameSpecifier *Qualifier,
3083  NamedDecl *FoundDecl,
3084  NamedDecl *Member) {
3085  const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3086  if (!RD)
3087  return From;
3088 
3089  QualType DestRecordType;
3090  QualType DestType;
3091  QualType FromRecordType;
3092  QualType FromType = From->getType();
3093  bool PointerConversions = false;
3094  if (isa<FieldDecl>(Member)) {
3095  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3096  auto FromPtrType = FromType->getAs<PointerType>();
3097  DestRecordType = Context.getAddrSpaceQualType(
3098  DestRecordType, FromPtrType
3099  ? FromType->getPointeeType().getAddressSpace()
3100  : FromType.getAddressSpace());
3101 
3102  if (FromPtrType) {
3103  DestType = Context.getPointerType(DestRecordType);
3104  FromRecordType = FromPtrType->getPointeeType();
3105  PointerConversions = true;
3106  } else {
3107  DestType = DestRecordType;
3108  FromRecordType = FromType;
3109  }
3110  } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3111  if (!Method->isImplicitObjectMemberFunction())
3112  return From;
3113 
3114  DestType = Method->getThisType().getNonReferenceType();
3115  DestRecordType = Method->getFunctionObjectParameterType();
3116 
3117  if (FromType->getAs<PointerType>()) {
3118  FromRecordType = FromType->getPointeeType();
3119  PointerConversions = true;
3120  } else {
3121  FromRecordType = FromType;
3122  DestType = DestRecordType;
3123  }
3124 
3125  LangAS FromAS = FromRecordType.getAddressSpace();
3126  LangAS DestAS = DestRecordType.getAddressSpace();
3127  if (FromAS != DestAS) {
3128  QualType FromRecordTypeWithoutAS =
3129  Context.removeAddrSpaceQualType(FromRecordType);
3130  QualType FromTypeWithDestAS =
3131  Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3132  if (PointerConversions)
3133  FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3134  From = ImpCastExprToType(From, FromTypeWithDestAS,
3135  CK_AddressSpaceConversion, From->getValueKind())
3136  .get();
3137  }
3138  } else {
3139  // No conversion necessary.
3140  return From;
3141  }
3142 
3143  if (DestType->isDependentType() || FromType->isDependentType())
3144  return From;
3145 
3146  // If the unqualified types are the same, no conversion is necessary.
3147  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3148  return From;
3149 
3150  SourceRange FromRange = From->getSourceRange();
3151  SourceLocation FromLoc = FromRange.getBegin();
3152 
3153  ExprValueKind VK = From->getValueKind();
3154 
3155  // C++ [class.member.lookup]p8:
3156  // [...] Ambiguities can often be resolved by qualifying a name with its
3157  // class name.
3158  //
3159  // If the member was a qualified name and the qualified referred to a
3160  // specific base subobject type, we'll cast to that intermediate type
3161  // first and then to the object in which the member is declared. That allows
3162  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3163  //
3164  // class Base { public: int x; };
3165  // class Derived1 : public Base { };
3166  // class Derived2 : public Base { };
3167  // class VeryDerived : public Derived1, public Derived2 { void f(); };
3168  //
3169  // void VeryDerived::f() {
3170  // x = 17; // error: ambiguous base subobjects
3171  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3172  // }
3173  if (Qualifier && Qualifier->getAsType()) {
3174  QualType QType = QualType(Qualifier->getAsType(), 0);
3175  assert(QType->isRecordType() && "lookup done with non-record type");
3176 
3177  QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3178 
3179  // In C++98, the qualifier type doesn't actually have to be a base
3180  // type of the object type, in which case we just ignore it.
3181  // Otherwise build the appropriate casts.
3182  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3183  CXXCastPath BasePath;
3184  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3185  FromLoc, FromRange, &BasePath))
3186  return ExprError();
3187 
3188  if (PointerConversions)
3189  QType = Context.getPointerType(QType);
3190  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3191  VK, &BasePath).get();
3192 
3193  FromType = QType;
3194  FromRecordType = QRecordType;
3195 
3196  // If the qualifier type was the same as the destination type,
3197  // we're done.
3198  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3199  return From;
3200  }
3201  }
3202 
3203  CXXCastPath BasePath;
3204  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3205  FromLoc, FromRange, &BasePath,
3206  /*IgnoreAccess=*/true))
3207  return ExprError();
3208 
3209  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3210  VK, &BasePath);
3211 }
3212 
3214  const LookupResult &R,
3215  bool HasTrailingLParen) {
3216  // Only when used directly as the postfix-expression of a call.
3217  if (!HasTrailingLParen)
3218  return false;
3219 
3220  // Never if a scope specifier was provided.
3221  if (SS.isNotEmpty())
3222  return false;
3223 
3224  // Only in C++ or ObjC++.
3225  if (!getLangOpts().CPlusPlus)
3226  return false;
3227 
3228  // Turn off ADL when we find certain kinds of declarations during
3229  // normal lookup:
3230  for (const NamedDecl *D : R) {
3231  // C++0x [basic.lookup.argdep]p3:
3232  // -- a declaration of a class member
3233  // Since using decls preserve this property, we check this on the
3234  // original decl.
3235  if (D->isCXXClassMember())
3236  return false;
3237 
3238  // C++0x [basic.lookup.argdep]p3:
3239  // -- a block-scope function declaration that is not a
3240  // using-declaration
3241  // NOTE: we also trigger this for function templates (in fact, we
3242  // don't check the decl type at all, since all other decl types
3243  // turn off ADL anyway).
3244  if (isa<UsingShadowDecl>(D))
3245  D = cast<UsingShadowDecl>(D)->getTargetDecl();
3246  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3247  return false;
3248 
3249  // C++0x [basic.lookup.argdep]p3:
3250  // -- a declaration that is neither a function or a function
3251  // template
3252  // And also for builtin functions.
3253  if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3254  // But also builtin functions.
3255  if (FDecl->getBuiltinID() && FDecl->isImplicit())
3256  return false;
3257  } else if (!isa<FunctionTemplateDecl>(D))
3258  return false;
3259  }
3260 
3261  return true;
3262 }
3263 
3264 
3265 /// Diagnoses obvious problems with the use of the given declaration
3266 /// as an expression. This is only actually called for lookups that
3267 /// were not overloaded, and it doesn't promise that the declaration
3268 /// will in fact be used.
3270  bool AcceptInvalid) {
3271  if (D->isInvalidDecl() && !AcceptInvalid)
3272  return true;
3273 
3274  if (isa<TypedefNameDecl>(D)) {
3275  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3276  return true;
3277  }
3278 
3279  if (isa<ObjCInterfaceDecl>(D)) {
3280  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3281  return true;
3282  }
3283 
3284  if (isa<NamespaceDecl>(D)) {
3285  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3286  return true;
3287  }
3288 
3289  return false;
3290 }
3291 
3292 // Certain multiversion types should be treated as overloaded even when there is
3293 // only one result.
3295  assert(R.isSingleResult() && "Expected only a single result");
3296  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3297  return FD &&
3298  (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3299 }
3300 
3302  LookupResult &R, bool NeedsADL,
3303  bool AcceptInvalidDecl) {
3304  // If this is a single, fully-resolved result and we don't need ADL,
3305  // just build an ordinary singleton decl ref.
3306  if (!NeedsADL && R.isSingleResult() &&
3309  return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3310  R.getRepresentativeDecl(), nullptr,
3311  AcceptInvalidDecl);
3312 
3313  // We only need to check the declaration if there's exactly one
3314  // result, because in the overloaded case the results can only be
3315  // functions and function templates.
3317  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3318  AcceptInvalidDecl))
3319  return ExprError();
3320 
3321  // Otherwise, just build an unresolved lookup expression. Suppress
3322  // any lookup-related diagnostics; we'll hash these out later, when
3323  // we've picked a target.
3324  R.suppressDiagnostics();
3325 
3327  Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3328  R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3329  /*KnownDependent=*/false);
3330 
3331  return ULE;
3332 }
3333 
3335  SourceLocation loc,
3336  ValueDecl *var);
3337 
3338 /// Complete semantic analysis for a reference to the given declaration.
3340  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3341  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3342  bool AcceptInvalidDecl) {
3343  assert(D && "Cannot refer to a NULL declaration");
3344  assert(!isa<FunctionTemplateDecl>(D) &&
3345  "Cannot refer unambiguously to a function template");
3346 
3347  SourceLocation Loc = NameInfo.getLoc();
3348  if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3349  // Recovery from invalid cases (e.g. D is an invalid Decl).
3350  // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3351  // diagnostics, as invalid decls use int as a fallback type.
3352  return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3353  }
3354 
3355  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3356  // Specifically diagnose references to class templates that are missing
3357  // a template argument list.
3358  diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3359  return ExprError();
3360  }
3361 
3362  // Make sure that we're referring to a value.
3363  if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3364  Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3365  Diag(D->getLocation(), diag::note_declared_at);
3366  return ExprError();
3367  }
3368 
3369  // Check whether this declaration can be used. Note that we suppress
3370  // this check when we're going to perform argument-dependent lookup
3371  // on this function name, because this might not be the function
3372  // that overload resolution actually selects.
3373  if (DiagnoseUseOfDecl(D, Loc))
3374  return ExprError();
3375 
3376  auto *VD = cast<ValueDecl>(D);
3377 
3378  // Only create DeclRefExpr's for valid Decl's.
3379  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3380  return ExprError();
3381 
3382  // Handle members of anonymous structs and unions. If we got here,
3383  // and the reference is to a class member indirect field, then this
3384  // must be the subject of a pointer-to-member expression.
3385  if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3386  IndirectField && !IndirectField->isCXXClassMember())
3387  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3388  IndirectField);
3389 
3390  QualType type = VD->getType();
3391  if (type.isNull())
3392  return ExprError();
3393  ExprValueKind valueKind = VK_PRValue;
3394 
3395  // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3396  // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3397  // is expanded by some outer '...' in the context of the use.
3398  type = type.getNonPackExpansionType();
3399 
3400  switch (D->getKind()) {
3401  // Ignore all the non-ValueDecl kinds.
3402 #define ABSTRACT_DECL(kind)
3403 #define VALUE(type, base)
3404 #define DECL(type, base) case Decl::type:
3405 #include "clang/AST/DeclNodes.inc"
3406  llvm_unreachable("invalid value decl kind");
3407 
3408  // These shouldn't make it here.
3409  case Decl::ObjCAtDefsField:
3410  llvm_unreachable("forming non-member reference to ivar?");
3411 
3412  // Enum constants are always r-values and never references.
3413  // Unresolved using declarations are dependent.
3414  case Decl::EnumConstant:
3415  case Decl::UnresolvedUsingValue:
3416  case Decl::OMPDeclareReduction:
3417  case Decl::OMPDeclareMapper:
3418  valueKind = VK_PRValue;
3419  break;
3420 
3421  // Fields and indirect fields that got here must be for
3422  // pointer-to-member expressions; we just call them l-values for
3423  // internal consistency, because this subexpression doesn't really
3424  // exist in the high-level semantics.
3425  case Decl::Field:
3426  case Decl::IndirectField:
3427  case Decl::ObjCIvar:
3428  assert((getLangOpts().CPlusPlus || isBoundsAttrContext()) &&
3429  "building reference to field in C?");
3430 
3431  // These can't have reference type in well-formed programs, but
3432  // for internal consistency we do this anyway.
3433  type = type.getNonReferenceType();
3434  valueKind = VK_LValue;
3435  break;
3436 
3437  // Non-type template parameters are either l-values or r-values
3438  // depending on the type.
3439  case Decl::NonTypeTemplateParm: {
3440  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3441  type = reftype->getPointeeType();
3442  valueKind = VK_LValue; // even if the parameter is an r-value reference
3443  break;
3444  }
3445 
3446  // [expr.prim.id.unqual]p2:
3447  // If the entity is a template parameter object for a template
3448  // parameter of type T, the type of the expression is const T.
3449  // [...] The expression is an lvalue if the entity is a [...] template
3450  // parameter object.
3451  if (type->isRecordType()) {
3452  type = type.getUnqualifiedType().withConst();
3453  valueKind = VK_LValue;
3454  break;
3455  }
3456 
3457  // For non-references, we need to strip qualifiers just in case
3458  // the template parameter was declared as 'const int' or whatever.
3459  valueKind = VK_PRValue;
3460  type = type.getUnqualifiedType();
3461  break;
3462  }
3463 
3464  case Decl::Var:
3465  case Decl::VarTemplateSpecialization:
3466  case Decl::VarTemplatePartialSpecialization:
3467  case Decl::Decomposition:
3468  case Decl::OMPCapturedExpr:
3469  // In C, "extern void blah;" is valid and is an r-value.
3470  if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3471  type->isVoidType()) {
3472  valueKind = VK_PRValue;
3473  break;
3474  }
3475  [[fallthrough]];
3476 
3477  case Decl::ImplicitParam:
3478  case Decl::ParmVar: {
3479  // These are always l-values.
3480  valueKind = VK_LValue;
3481  type = type.getNonReferenceType();
3482 
3483  // FIXME: Does the addition of const really only apply in
3484  // potentially-evaluated contexts? Since the variable isn't actually
3485  // captured in an unevaluated context, it seems that the answer is no.
3486  if (!isUnevaluatedContext()) {
3487  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3488  if (!CapturedType.isNull())
3489  type = CapturedType;
3490  }
3491 
3492  break;
3493  }
3494 
3495  case Decl::Binding:
3496  // These are always lvalues.
3497  valueKind = VK_LValue;
3498  type = type.getNonReferenceType();
3499  break;
3500 
3501  case Decl::Function: {
3502  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3503  if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3504  type = Context.BuiltinFnTy;
3505  valueKind = VK_PRValue;
3506  break;
3507  }
3508  }
3509 
3510  const FunctionType *fty = type->castAs<FunctionType>();
3511 
3512  // If we're referring to a function with an __unknown_anytype
3513  // result type, make the entire expression __unknown_anytype.
3514  if (fty->getReturnType() == Context.UnknownAnyTy) {
3515  type = Context.UnknownAnyTy;
3516  valueKind = VK_PRValue;
3517  break;
3518  }
3519 
3520  // Functions are l-values in C++.
3521  if (getLangOpts().CPlusPlus) {
3522  valueKind = VK_LValue;
3523  break;
3524  }
3525 
3526  // C99 DR 316 says that, if a function type comes from a
3527  // function definition (without a prototype), that type is only
3528  // used for checking compatibility. Therefore, when referencing
3529  // the function, we pretend that we don't have the full function
3530  // type.
3531  if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3532  type = Context.getFunctionNoProtoType(fty->getReturnType(),
3533  fty->getExtInfo());
3534 
3535  // Functions are r-values in C.
3536  valueKind = VK_PRValue;
3537  break;
3538  }
3539 
3540  case Decl::CXXDeductionGuide:
3541  llvm_unreachable("building reference to deduction guide");
3542 
3543  case Decl::MSProperty:
3544  case Decl::MSGuid:
3545  case Decl::TemplateParamObject:
3546  // FIXME: Should MSGuidDecl and template parameter objects be subject to
3547  // capture in OpenMP, or duplicated between host and device?
3548  valueKind = VK_LValue;
3549  break;
3550 
3551  case Decl::UnnamedGlobalConstant:
3552  valueKind = VK_LValue;
3553  break;
3554 
3555  case Decl::CXXMethod:
3556  // If we're referring to a method with an __unknown_anytype
3557  // result type, make the entire expression __unknown_anytype.
3558  // This should only be possible with a type written directly.
3559  if (const FunctionProtoType *proto =
3560  dyn_cast<FunctionProtoType>(VD->getType()))
3561  if (proto->getReturnType() == Context.UnknownAnyTy) {
3562  type = Context.UnknownAnyTy;
3563  valueKind = VK_PRValue;
3564  break;
3565  }
3566 
3567  // C++ methods are l-values if static, r-values if non-static.
3568  if (cast<CXXMethodDecl>(VD)->isStatic()) {
3569  valueKind = VK_LValue;
3570  break;
3571  }
3572  [[fallthrough]];
3573 
3574  case Decl::CXXConversion:
3575  case Decl::CXXDestructor:
3576  case Decl::CXXConstructor:
3577  valueKind = VK_PRValue;
3578  break;
3579  }
3580 
3581  auto *E =
3582  BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3583  /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3584  // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3585  // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3586  // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3587  // diagnostics).
3588  if (VD->isInvalidDecl() && E)
3589  return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3590  return E;
3591 }
3592 
3593 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3595  Target.resize(CharByteWidth * (Source.size() + 1));
3596  char *ResultPtr = &Target[0];
3597  const llvm::UTF8 *ErrorPtr;
3598  bool success =
3599  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3600  (void)success;
3601  assert(success);
3602  Target.resize(ResultPtr - &Target[0]);
3603 }
3604 
3606  PredefinedIdentKind IK) {
3607  Decl *currentDecl = getPredefinedExprDecl(CurContext);
3608  if (!currentDecl) {
3609  Diag(Loc, diag::ext_predef_outside_function);
3610  currentDecl = Context.getTranslationUnitDecl();
3611  }
3612 
3613  QualType ResTy;
3614  StringLiteral *SL = nullptr;
3615  if (cast<DeclContext>(currentDecl)->isDependentContext())
3616  ResTy = Context.DependentTy;
3617  else {
3618  // Pre-defined identifiers are of type char[x], where x is the length of
3619  // the string.
3620  bool ForceElaboratedPrinting =
3621  IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3622  auto Str =
3623  PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3624  unsigned Length = Str.length();
3625 
3626  llvm::APInt LengthI(32, Length + 1);
3627  if (IK == PredefinedIdentKind::LFunction ||
3629  ResTy =
3631  SmallString<32> RawChars;
3633  Str, RawChars);
3634  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3636  /*IndexTypeQuals*/ 0);
3637  SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide,
3638  /*Pascal*/ false, ResTy, Loc);
3639  } else {
3640  ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3641  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3643  /*IndexTypeQuals*/ 0);
3645  /*Pascal*/ false, ResTy, Loc);
3646  }
3647  }
3648 
3649  return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3650  SL);
3651 }
3652 
3654  return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3655 }
3656 
3658  SmallString<16> CharBuffer;
3659  bool Invalid = false;
3660  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3661  if (Invalid)
3662  return ExprError();
3663 
3664  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3665  PP, Tok.getKind());
3666  if (Literal.hadError())
3667  return ExprError();
3668 
3669  QualType Ty;
3670  if (Literal.isWide())
3671  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3672  else if (Literal.isUTF8() && getLangOpts().C23)
3673  Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3674  else if (Literal.isUTF8() && getLangOpts().Char8)
3675  Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3676  else if (Literal.isUTF16())
3677  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3678  else if (Literal.isUTF32())
3679  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3680  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3681  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3682  else
3683  Ty = Context.CharTy; // 'x' -> char in C++;
3684  // u8'x' -> char in C11-C17 and in C++ without char8_t.
3685 
3687  if (Literal.isWide())
3689  else if (Literal.isUTF16())
3691  else if (Literal.isUTF32())
3693  else if (Literal.isUTF8())
3695 
3696  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3697  Tok.getLocation());
3698 
3699  if (Literal.getUDSuffix().empty())
3700  return Lit;
3701 
3702  // We're building a user-defined literal.
3703  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3704  SourceLocation UDSuffixLoc =
3705  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3706 
3707  // Make sure we're allowed user-defined literals here.
3708  if (!UDLScope)
3709  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3710 
3711  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3712  // operator "" X (ch)
3713  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3714  Lit, Tok.getLocation());
3715 }
3716 
3718  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3719  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3720  Context.IntTy, Loc);
3721 }
3722 
3724  QualType Ty, SourceLocation Loc) {
3725  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3726 
3727  using llvm::APFloat;
3728  APFloat Val(Format);
3729 
3730  llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3731  if (RM == llvm::RoundingMode::Dynamic)
3732  RM = llvm::RoundingMode::NearestTiesToEven;
3733  APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3734 
3735  // Overflow is always an error, but underflow is only an error if
3736  // we underflowed to zero (APFloat reports denormals as underflow).
3737  if ((result & APFloat::opOverflow) ||
3738  ((result & APFloat::opUnderflow) && Val.isZero())) {
3739  unsigned diagnostic;
3740  SmallString<20> buffer;
3741  if (result & APFloat::opOverflow) {
3742  diagnostic = diag::warn_float_overflow;
3743  APFloat::getLargest(Format).toString(buffer);
3744  } else {
3745  diagnostic = diag::warn_float_underflow;
3746  APFloat::getSmallest(Format).toString(buffer);
3747  }
3748 
3749  S.Diag(Loc, diagnostic) << Ty << buffer.str();
3750  }
3751 
3752  bool isExact = (result == APFloat::opOK);
3753  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3754 }
3755 
3756 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3757  assert(E && "Invalid expression");
3758 
3759  if (E->isValueDependent())
3760  return false;
3761 
3762  QualType QT = E->getType();
3763  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3764  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3765  return true;
3766  }
3767 
3768  llvm::APSInt ValueAPS;
3769  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3770 
3771  if (R.isInvalid())
3772  return true;
3773 
3774  // GCC allows the value of unroll count to be 0.
3775  // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3776  // "The values of 0 and 1 block any unrolling of the loop."
3777  // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3778  // '#pragma unroll' cases.
3779  bool ValueIsPositive =
3780  AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3781  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3782  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3783  << toString(ValueAPS, 10) << ValueIsPositive;
3784  return true;
3785  }
3786 
3787  return false;
3788 }
3789 
3791  // Fast path for a single digit (which is quite common). A single digit
3792  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3793  if (Tok.getLength() == 1) {
3794  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3795  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3796  }
3797 
3798  SmallString<128> SpellingBuffer;
3799  // NumericLiteralParser wants to overread by one character. Add padding to
3800  // the buffer in case the token is copied to the buffer. If getSpelling()
3801  // returns a StringRef to the memory buffer, it should have a null char at
3802  // the EOF, so it is also safe.
3803  SpellingBuffer.resize(Tok.getLength() + 1);
3804 
3805  // Get the spelling of the token, which eliminates trigraphs, etc.
3806  bool Invalid = false;
3807  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3808  if (Invalid)
3809  return ExprError();
3810 
3811  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3812  PP.getSourceManager(), PP.getLangOpts(),
3813  PP.getTargetInfo(), PP.getDiagnostics());
3814  if (Literal.hadError)
3815  return ExprError();
3816 
3817  if (Literal.hasUDSuffix()) {
3818  // We're building a user-defined literal.
3819  const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3820  SourceLocation UDSuffixLoc =
3821  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3822 
3823  // Make sure we're allowed user-defined literals here.
3824  if (!UDLScope)
3825  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3826 
3827  QualType CookedTy;
3828  if (Literal.isFloatingLiteral()) {
3829  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3830  // long double, the literal is treated as a call of the form
3831  // operator "" X (f L)
3832  CookedTy = Context.LongDoubleTy;
3833  } else {
3834  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3835  // unsigned long long, the literal is treated as a call of the form
3836  // operator "" X (n ULL)
3837  CookedTy = Context.UnsignedLongLongTy;
3838  }
3839 
3840  DeclarationName OpName =
3841  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3842  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3843  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3844 
3845  SourceLocation TokLoc = Tok.getLocation();
3846 
3847  // Perform literal operator lookup to determine if we're building a raw
3848  // literal or a cooked one.
3849  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3850  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3851  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3852  /*AllowStringTemplatePack*/ false,
3853  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3854  case LOLR_ErrorNoDiagnostic:
3855  // Lookup failure for imaginary constants isn't fatal, there's still the
3856  // GNU extension producing _Complex types.
3857  break;
3858  case LOLR_Error:
3859  return ExprError();
3860  case LOLR_Cooked: {
3861  Expr *Lit;
3862  if (Literal.isFloatingLiteral()) {
3863  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3864  } else {
3865  llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3866  if (Literal.GetIntegerValue(ResultVal))
3867  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3868  << /* Unsigned */ 1;
3869  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3870  Tok.getLocation());
3871  }
3872  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3873  }
3874 
3875  case LOLR_Raw: {
3876  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3877  // literal is treated as a call of the form
3878  // operator "" X ("n")
3879  unsigned Length = Literal.getUDSuffixOffset();
3880  QualType StrTy = Context.getConstantArrayType(
3881  Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3882  llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3883  Expr *Lit =
3884  StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3886  /*Pascal*/ false, StrTy, &TokLoc, 1);
3887  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3888  }
3889 
3890  case LOLR_Template: {
3891  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3892  // template), L is treated as a call fo the form
3893  // operator "" X <'c1', 'c2', ... 'ck'>()
3894  // where n is the source character sequence c1 c2 ... ck.
3895  TemplateArgumentListInfo ExplicitArgs;
3896  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3897  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3898  llvm::APSInt Value(CharBits, CharIsUnsigned);
3899  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3900  Value = TokSpelling[I];
3901  TemplateArgument Arg(Context, Value, Context.CharTy);
3902  TemplateArgumentLocInfo ArgInfo;
3903  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3904  }
3905  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3906  &ExplicitArgs);
3907  }
3908  case LOLR_StringTemplatePack:
3909  llvm_unreachable("unexpected literal operator lookup result");
3910  }
3911  }
3912 
3913  Expr *Res;
3914 
3915  if (Literal.isFixedPointLiteral()) {
3916  QualType Ty;
3917 
3918  if (Literal.isAccum) {
3919  if (Literal.isHalf) {
3920  Ty = Context.ShortAccumTy;
3921  } else if (Literal.isLong) {
3922  Ty = Context.LongAccumTy;
3923  } else {
3924  Ty = Context.AccumTy;
3925  }
3926  } else if (Literal.isFract) {
3927  if (Literal.isHalf) {
3928  Ty = Context.ShortFractTy;
3929  } else if (Literal.isLong) {
3930  Ty = Context.LongFractTy;
3931  } else {
3932  Ty = Context.FractTy;
3933  }
3934  }
3935 
3936  if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3937 
3938  bool isSigned = !Literal.isUnsigned;
3939  unsigned scale = Context.getFixedPointScale(Ty);
3940  unsigned bit_width = Context.getTypeInfo(Ty).Width;
3941 
3942  llvm::APInt Val(bit_width, 0, isSigned);
3943  bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3944  bool ValIsZero = Val.isZero() && !Overflowed;
3945 
3946  auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3947  if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3948  // Clause 6.4.4 - The value of a constant shall be in the range of
3949  // representable values for its type, with exception for constants of a
3950  // fract type with a value of exactly 1; such a constant shall denote
3951  // the maximal value for the type.
3952  --Val;
3953  else if (Val.ugt(MaxVal) || Overflowed)
3954  Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3955 
3956  Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3957  Tok.getLocation(), scale);
3958  } else if (Literal.isFloatingLiteral()) {
3959  QualType Ty;
3960  if (Literal.isHalf){
3961  if (getLangOpts().HLSL ||
3962  getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3963  Ty = Context.HalfTy;
3964  else {
3965  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3966  return ExprError();
3967  }
3968  } else if (Literal.isFloat)
3969  Ty = Context.FloatTy;
3970  else if (Literal.isLong)
3971  Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3972  else if (Literal.isFloat16)
3973  Ty = Context.Float16Ty;
3974  else if (Literal.isFloat128)
3975  Ty = Context.Float128Ty;
3976  else if (getLangOpts().HLSL)
3977  Ty = Context.FloatTy;
3978  else
3979  Ty = Context.DoubleTy;
3980 
3981  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3982 
3983  if (Ty == Context.DoubleTy) {
3984  if (getLangOpts().SinglePrecisionConstants) {
3985  if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3986  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3987  }
3988  } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3989  "cl_khr_fp64", getLangOpts())) {
3990  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3991  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3992  << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3993  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3994  }
3995  }
3996  } else if (!Literal.isIntegerLiteral()) {
3997  return ExprError();
3998  } else {
3999  QualType Ty;
4000 
4001  // 'z/uz' literals are a C++23 feature.
4002  if (Literal.isSizeT)
4003  Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4004  ? getLangOpts().CPlusPlus23
4005  ? diag::warn_cxx20_compat_size_t_suffix
4006  : diag::ext_cxx23_size_t_suffix
4007  : diag::err_cxx23_size_t_suffix);
4008 
4009  // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4010  // but we do not currently support the suffix in C++ mode because it's not
4011  // entirely clear whether WG21 will prefer this suffix to return a library
4012  // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4013  // literals are a C++ extension.
4014  if (Literal.isBitInt)
4015  PP.Diag(Tok.getLocation(),
4016  getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4017  : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4018  : diag::ext_c23_bitint_suffix);
4019 
4020  // Get the value in the widest-possible width. What is "widest" depends on
4021  // whether the literal is a bit-precise integer or not. For a bit-precise
4022  // integer type, try to scan the source to determine how many bits are
4023  // needed to represent the value. This may seem a bit expensive, but trying
4024  // to get the integer value from an overly-wide APInt is *extremely*
4025  // expensive, so the naive approach of assuming
4026  // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4027  unsigned BitsNeeded =
4028  Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4029  Literal.getLiteralDigits(), Literal.getRadix())
4030  : Context.getTargetInfo().getIntMaxTWidth();
4031  llvm::APInt ResultVal(BitsNeeded, 0);
4032 
4033  if (Literal.GetIntegerValue(ResultVal)) {
4034  // If this value didn't fit into uintmax_t, error and force to ull.
4035  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4036  << /* Unsigned */ 1;
4037  Ty = Context.UnsignedLongLongTy;
4038  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4039  "long long is not intmax_t?");
4040  } else {
4041  // If this value fits into a ULL, try to figure out what else it fits into
4042  // according to the rules of C99 6.4.4.1p5.
4043 
4044  // Octal, Hexadecimal, and integers with a U suffix are allowed to
4045  // be an unsigned int.
4046  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4047 
4048  // HLSL doesn't really have `long` or `long long`. We support the `ll`
4049  // suffix for portability of code with C++, but both `l` and `ll` are
4050  // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4051  // same.
4052  if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4053  Literal.isLong = true;
4054  Literal.isLongLong = false;
4055  }
4056 
4057  // Check from smallest to largest, picking the smallest type we can.
4058  unsigned Width = 0;
4059 
4060  // Microsoft specific integer suffixes are explicitly sized.
4061  if (Literal.MicrosoftInteger) {
4062  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4063  Width = 8;
4064  Ty = Context.CharTy;
4065  } else {
4066  Width = Literal.MicrosoftInteger;
4067  Ty = Context.getIntTypeForBitwidth(Width,
4068  /*Signed=*/!Literal.isUnsigned);
4069  }
4070  }
4071 
4072  // Bit-precise integer literals are automagically-sized based on the
4073  // width required by the literal.
4074  if (Literal.isBitInt) {
4075  // The signed version has one more bit for the sign value. There are no
4076  // zero-width bit-precise integers, even if the literal value is 0.
4077  Width = std::max(ResultVal.getActiveBits(), 1u) +
4078  (Literal.isUnsigned ? 0u : 1u);
4079 
4080  // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4081  // and reset the type to the largest supported width.
4082  unsigned int MaxBitIntWidth =
4083  Context.getTargetInfo().getMaxBitIntWidth();
4084  if (Width > MaxBitIntWidth) {
4085  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4086  << Literal.isUnsigned;
4087  Width = MaxBitIntWidth;
4088  }
4089 
4090  // Reset the result value to the smaller APInt and select the correct
4091  // type to be used. Note, we zext even for signed values because the
4092  // literal itself is always an unsigned value (a preceeding - is a
4093  // unary operator, not part of the literal).
4094  ResultVal = ResultVal.zextOrTrunc(Width);
4095  Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4096  }
4097 
4098  // Check C++23 size_t literals.
4099  if (Literal.isSizeT) {
4100  assert(!Literal.MicrosoftInteger &&
4101  "size_t literals can't be Microsoft literals");
4102  unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4103  Context.getTargetInfo().getSizeType());
4104 
4105  // Does it fit in size_t?
4106  if (ResultVal.isIntN(SizeTSize)) {
4107  // Does it fit in ssize_t?
4108  if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4109  Ty = Context.getSignedSizeType();
4110  else if (AllowUnsigned)
4111  Ty = Context.getSizeType();
4112  Width = SizeTSize;
4113  }
4114  }
4115 
4116  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4117  !Literal.isSizeT) {
4118  // Are int/unsigned possibilities?
4119  unsigned IntSize = Context.getTargetInfo().getIntWidth();
4120 
4121  // Does it fit in a unsigned int?
4122  if (ResultVal.isIntN(IntSize)) {
4123  // Does it fit in a signed int?
4124  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4125  Ty = Context.IntTy;
4126  else if (AllowUnsigned)
4127  Ty = Context.UnsignedIntTy;
4128  Width = IntSize;
4129  }
4130  }
4131 
4132  // Are long/unsigned long possibilities?
4133  if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4134  unsigned LongSize = Context.getTargetInfo().getLongWidth();
4135 
4136  // Does it fit in a unsigned long?
4137  if (ResultVal.isIntN(LongSize)) {
4138  // Does it fit in a signed long?
4139  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4140  Ty = Context.LongTy;
4141  else if (AllowUnsigned)
4142  Ty = Context.UnsignedLongTy;
4143  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4144  // is compatible.
4145  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4146  const unsigned LongLongSize =
4147  Context.getTargetInfo().getLongLongWidth();
4148  Diag(Tok.getLocation(),
4149  getLangOpts().CPlusPlus
4150  ? Literal.isLong
4151  ? diag::warn_old_implicitly_unsigned_long_cxx
4152  : /*C++98 UB*/ diag::
4153  ext_old_implicitly_unsigned_long_cxx
4154  : diag::warn_old_implicitly_unsigned_long)
4155  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4156  : /*will be ill-formed*/ 1);
4157  Ty = Context.UnsignedLongTy;
4158  }
4159  Width = LongSize;
4160  }
4161  }
4162 
4163  // Check long long if needed.
4164  if (Ty.isNull() && !Literal.isSizeT) {
4165  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4166 
4167  // Does it fit in a unsigned long long?
4168  if (ResultVal.isIntN(LongLongSize)) {
4169  // Does it fit in a signed long long?
4170  // To be compatible with MSVC, hex integer literals ending with the
4171  // LL or i64 suffix are always signed in Microsoft mode.
4172  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4173  (getLangOpts().MSVCCompat && Literal.isLongLong)))
4174  Ty = Context.LongLongTy;
4175  else if (AllowUnsigned)
4176  Ty = Context.UnsignedLongLongTy;
4177  Width = LongLongSize;
4178 
4179  // 'long long' is a C99 or C++11 feature, whether the literal
4180  // explicitly specified 'long long' or we needed the extra width.
4181  if (getLangOpts().CPlusPlus)
4182  Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4183  ? diag::warn_cxx98_compat_longlong
4184  : diag::ext_cxx11_longlong);
4185  else if (!getLangOpts().C99)
4186  Diag(Tok.getLocation(), diag::ext_c99_longlong);
4187  }
4188  }
4189 
4190  // If we still couldn't decide a type, we either have 'size_t' literal
4191  // that is out of range, or a decimal literal that does not fit in a
4192  // signed long long and has no U suffix.
4193  if (Ty.isNull()) {
4194  if (Literal.isSizeT)
4195  Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4196  << Literal.isUnsigned;
4197  else
4198  Diag(Tok.getLocation(),
4199  diag::ext_integer_literal_too_large_for_signed);
4200  Ty = Context.UnsignedLongLongTy;
4201  Width = Context.getTargetInfo().getLongLongWidth();
4202  }
4203 
4204  if (ResultVal.getBitWidth() != Width)
4205  ResultVal = ResultVal.trunc(Width);
4206  }
4207  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4208  }
4209 
4210  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4211  if (Literal.isImaginary) {
4212  Res = new (Context) ImaginaryLiteral(Res,
4213  Context.getComplexType(Res->getType()));
4214 
4215  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4216  }
4217  return Res;
4218 }
4219 
4221  assert(E && "ActOnParenExpr() missing expr");
4222  QualType ExprTy = E->getType();
4223  if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4224  !E->isLValue() && ExprTy->hasFloatingRepresentation())
4225  return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4226  return new (Context) ParenExpr(L, R, E);
4227 }
4228 
4231  SourceRange ArgRange) {
4232  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4233  // scalar or vector data type argument..."
4234  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4235  // type (C99 6.2.5p18) or void.
4236  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4237  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4238  << T << ArgRange;
4239  return true;
4240  }
4241 
4242  assert((T->isVoidType() || !T->isIncompleteType()) &&
4243  "Scalar types should always be complete");
4244  return false;
4245 }
4246 
4249  SourceRange ArgRange) {
4250  // builtin_vectorelements supports both fixed-sized and scalable vectors.
4251  if (!T->isVectorType() && !T->isSizelessVectorType())
4252  return S.Diag(Loc, diag::err_builtin_non_vector_type)
4253  << ""
4254  << "__builtin_vectorelements" << T << ArgRange;
4255 
4256  return false;
4257 }
4258 
4261  SourceRange ArgRange,
4262  UnaryExprOrTypeTrait TraitKind) {
4263  // Invalid types must be hard errors for SFINAE in C++.
4264  if (S.LangOpts.CPlusPlus)
4265  return true;
4266 
4267  // C99 6.5.3.4p1:
4268  if (T->isFunctionType() &&
4269  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4270  TraitKind == UETT_PreferredAlignOf)) {
4271  // sizeof(function)/alignof(function) is allowed as an extension.
4272  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4273  << getTraitSpelling(TraitKind) << ArgRange;
4274  return false;
4275  }
4276 
4277  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4278  // this is an error (OpenCL v1.1 s6.3.k)
4279  if (T->isVoidType()) {
4280  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4281  : diag::ext_sizeof_alignof_void_type;
4282  S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4283  return false;
4284  }
4285 
4286  return true;
4287 }
4288 
4291  SourceRange ArgRange,
4292  UnaryExprOrTypeTrait TraitKind) {
4293  // Reject sizeof(interface) and sizeof(interface<proto>) if the
4294  // runtime doesn't allow it.
4296  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4297  << T << (TraitKind == UETT_SizeOf)
4298  << ArgRange;
4299  return true;
4300  }
4301 
4302  return false;
4303 }
4304 
4305 /// Check whether E is a pointer from a decayed array type (the decayed
4306 /// pointer type is equal to T) and emit a warning if it is.
4308  const Expr *E) {
4309  // Don't warn if the operation changed the type.
4310  if (T != E->getType())
4311  return;
4312 
4313  // Now look for array decays.
4314  const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4315  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4316  return;
4317 
4318  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4319  << ICE->getType()
4320  << ICE->getSubExpr()->getType();
4321 }
4322 
4323 /// Check the constraints on expression operands to unary type expression
4324 /// and type traits.
4325 ///
4326 /// Completes any types necessary and validates the constraints on the operand
4327 /// expression. The logic mostly mirrors the type-based overload, but may modify
4328 /// the expression as it completes the type for that expression through template
4329 /// instantiation, etc.
4331  UnaryExprOrTypeTrait ExprKind) {
4332  QualType ExprTy = E->getType();
4333  assert(!ExprTy->isReferenceType());
4334 
4335  bool IsUnevaluatedOperand =
4336  (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4337  ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4338  ExprKind == UETT_VecStep);
4339  if (IsUnevaluatedOperand) {
4340  ExprResult Result = CheckUnevaluatedOperand(E);
4341  if (Result.isInvalid())
4342  return true;
4343  E = Result.get();
4344  }
4345 
4346  // The operand for sizeof and alignof is in an unevaluated expression context,
4347  // so side effects could result in unintended consequences.
4348  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4349  // used to build SFINAE gadgets.
4350  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4351  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4352  !E->isInstantiationDependent() &&
4353  !E->getType()->isVariableArrayType() &&
4354  E->HasSideEffects(Context, false))
4355  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4356 
4357  if (ExprKind == UETT_VecStep)
4358  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4359  E->getSourceRange());
4360 
4361  if (ExprKind == UETT_VectorElements)
4362  return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4363  E->getSourceRange());
4364 
4365  // Explicitly list some types as extensions.
4366  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4367  E->getSourceRange(), ExprKind))
4368  return false;
4369 
4370  // WebAssembly tables are always illegal operands to unary expressions and
4371  // type traits.
4372  if (Context.getTargetInfo().getTriple().isWasm() &&
4373  E->getType()->isWebAssemblyTableType()) {
4374  Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4375  << getTraitSpelling(ExprKind);
4376  return true;
4377  }
4378 
4379  // 'alignof' applied to an expression only requires the base element type of
4380  // the expression to be complete. 'sizeof' requires the expression's type to
4381  // be complete (and will attempt to complete it if it's an array of unknown
4382  // bound).
4383  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4384  if (RequireCompleteSizedType(
4385  E->getExprLoc(), Context.getBaseElementType(E->getType()),
4386  diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4387  getTraitSpelling(ExprKind), E->getSourceRange()))
4388  return true;
4389  } else {
4390  if (RequireCompleteSizedExprType(
4391  E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4392  getTraitSpelling(ExprKind), E->getSourceRange()))
4393  return true;
4394  }
4395 
4396  // Completing the expression's type may have changed it.
4397  ExprTy = E->getType();
4398  assert(!ExprTy->isReferenceType());
4399 
4400  if (ExprTy->isFunctionType()) {
4401  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4402  << getTraitSpelling(ExprKind) << E->getSourceRange();
4403  return true;
4404  }
4405 
4406  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4407  E->getSourceRange(), ExprKind))
4408  return true;
4409 
4410  if (ExprKind == UETT_SizeOf) {
4411  if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4412  if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4413  QualType OType = PVD->getOriginalType();
4414  QualType Type = PVD->getType();
4415  if (Type->isPointerType() && OType->isArrayType()) {
4416  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4417  << Type << OType;
4418  Diag(PVD->getLocation(), diag::note_declared_at);
4419  }
4420  }
4421  }
4422 
4423  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4424  // decays into a pointer and returns an unintended result. This is most
4425  // likely a typo for "sizeof(array) op x".
4426  if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4427  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4428  BO->getLHS());
4429  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4430  BO->getRHS());
4431  }
4432  }
4433 
4434  return false;
4435 }
4436 
4437 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4438  // Cannot know anything else if the expression is dependent.
4439  if (E->isTypeDependent())
4440  return false;
4441 
4442  if (E->getObjectKind() == OK_BitField) {
4443  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4444  << 1 << E->getSourceRange();
4445  return true;
4446  }
4447 
4448  ValueDecl *D = nullptr;
4449  Expr *Inner = E->IgnoreParens();
4450  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4451  D = DRE->getDecl();
4452  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4453  D = ME->getMemberDecl();
4454  }
4455 
4456  // If it's a field, require the containing struct to have a
4457  // complete definition so that we can compute the layout.
4458  //
4459  // This can happen in C++11 onwards, either by naming the member
4460  // in a way that is not transformed into a member access expression
4461  // (in an unevaluated operand, for instance), or by naming the member
4462  // in a trailing-return-type.
4463  //
4464  // For the record, since __alignof__ on expressions is a GCC
4465  // extension, GCC seems to permit this but always gives the
4466  // nonsensical answer 0.
4467  //
4468  // We don't really need the layout here --- we could instead just
4469  // directly check for all the appropriate alignment-lowing
4470  // attributes --- but that would require duplicating a lot of
4471  // logic that just isn't worth duplicating for such a marginal
4472  // use-case.
4473  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4474  // Fast path this check, since we at least know the record has a
4475  // definition if we can find a member of it.
4476  if (!FD->getParent()->isCompleteDefinition()) {
4477  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4478  << E->getSourceRange();
4479  return true;
4480  }
4481 
4482  // Otherwise, if it's a field, and the field doesn't have
4483  // reference type, then it must have a complete type (or be a
4484  // flexible array member, which we explicitly want to
4485  // white-list anyway), which makes the following checks trivial.
4486  if (!FD->getType()->isReferenceType())
4487  return false;
4488  }
4489 
4490  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4491 }
4492 
4494  E = E->IgnoreParens();
4495 
4496  // Cannot know anything else if the expression is dependent.
4497  if (E->isTypeDependent())
4498  return false;
4499 
4500  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4501 }
4502 
4504  CapturingScopeInfo *CSI) {
4505  assert(T->isVariablyModifiedType());
4506  assert(CSI != nullptr);
4507 
4508  // We're going to walk down into the type and look for VLA expressions.
4509  do {
4510  const Type *Ty = T.getTypePtr();
4511  switch (Ty->getTypeClass()) {
4512 #define TYPE(Class, Base)
4513 #define ABSTRACT_TYPE(Class, Base)
4514 #define NON_CANONICAL_TYPE(Class, Base)
4515 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4516 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4517 #include "clang/AST/TypeNodes.inc"
4518  T = QualType();
4519  break;
4520  // These types are never variably-modified.
4521  case Type::Builtin:
4522  case Type::Complex:
4523  case Type::Vector:
4524  case Type::ExtVector:
4525  case Type::ConstantMatrix:
4526  case Type::Record:
4527  case Type::Enum:
4528  case Type::TemplateSpecialization:
4529  case Type::ObjCObject:
4530  case Type::ObjCInterface:
4531  case Type::ObjCObjectPointer:
4532  case Type::ObjCTypeParam:
4533  case Type::Pipe:
4534  case Type::BitInt:
4535  llvm_unreachable("type class is never variably-modified!");
4536  case Type::Elaborated:
4537  T = cast<ElaboratedType>(Ty)->getNamedType();
4538  break;
4539  case Type::Adjusted:
4540  T = cast<AdjustedType>(Ty)->getOriginalType();
4541  break;
4542  case Type::Decayed:
4543  T = cast<DecayedType>(Ty)->getPointeeType();
4544  break;
4545  case Type::ArrayParameter:
4546  T = cast<ArrayParameterType>(Ty)->getElementType();
4547  break;
4548  case Type::Pointer:
4549  T = cast<PointerType>(Ty)->getPointeeType();
4550  break;
4551  case Type::BlockPointer:
4552  T = cast<BlockPointerType>(Ty)->getPointeeType();
4553  break;
4554  case Type::LValueReference:
4555  case Type::RValueReference:
4556  T = cast<ReferenceType>(Ty)->getPointeeType();
4557  break;
4558  case Type::MemberPointer:
4559  T = cast<MemberPointerType>(Ty)->getPointeeType();
4560  break;
4561  case Type::ConstantArray:
4562  case Type::IncompleteArray:
4563  // Losing element qualification here is fine.
4564  T = cast<ArrayType>(Ty)->getElementType();
4565  break;
4566  case Type::VariableArray: {
4567  // Losing element qualification here is fine.
4568  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4569 
4570  // Unknown size indication requires no size computation.
4571  // Otherwise, evaluate and record it.
4572  auto Size = VAT->getSizeExpr();
4573  if (Size && !CSI->isVLATypeCaptured(VAT) &&
4574  (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4575  CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4576 
4577  T = VAT->getElementType();
4578  break;
4579  }
4580  case Type::FunctionProto:
4581  case Type::FunctionNoProto:
4582  T = cast<FunctionType>(Ty)->getReturnType();
4583  break;
4584  case Type::Paren:
4585  case Type::TypeOf:
4586  case Type::UnaryTransform:
4587  case Type::Attributed:
4588  case Type::BTFTagAttributed:
4589  case Type::SubstTemplateTypeParm:
4590  case Type::MacroQualified:
4591  case Type::CountAttributed:
4592  // Keep walking after single level desugaring.
4593  T = T.getSingleStepDesugaredType(Context);
4594  break;
4595  case Type::Typedef:
4596  T = cast<TypedefType>(Ty)->desugar();
4597  break;
4598  case Type::Decltype:
4599  T = cast<DecltypeType>(Ty)->desugar();
4600  break;
4601  case Type::PackIndexing:
4602  T = cast<PackIndexingType>(Ty)->desugar();
4603  break;
4604  case Type::Using:
4605  T = cast<UsingType>(Ty)->desugar();
4606  break;
4607  case Type::Auto:
4608  case Type::DeducedTemplateSpecialization:
4609  T = cast<DeducedType>(Ty)->getDeducedType();
4610  break;
4611  case Type::TypeOfExpr:
4612  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4613  break;
4614  case Type::Atomic:
4615  T = cast<AtomicType>(Ty)->getValueType();
4616  break;
4617  }
4618  } while (!T.isNull() && T->isVariablyModifiedType());
4619 }
4620 
4621 /// Check the constraints on operands to unary expression and type
4622 /// traits.
4623 ///
4624 /// This will complete any types necessary, and validate the various constraints
4625 /// on those operands.
4626 ///
4627 /// The UsualUnaryConversions() function is *not* called by this routine.
4628 /// C99 6.3.2.1p[2-4] all state:
4629 /// Except when it is the operand of the sizeof operator ...
4630 ///
4631 /// C++ [expr.sizeof]p4
4632 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4633 /// standard conversions are not applied to the operand of sizeof.
4634 ///
4635 /// This policy is followed for all of the unary trait expressions.
4637  SourceLocation OpLoc,
4638  SourceRange ExprRange,
4639  UnaryExprOrTypeTrait ExprKind,
4640  StringRef KWName) {
4641  if (ExprType->isDependentType())
4642  return false;
4643 
4644  // C++ [expr.sizeof]p2:
4645  // When applied to a reference or a reference type, the result
4646  // is the size of the referenced type.
4647  // C++11 [expr.alignof]p3:
4648  // When alignof is applied to a reference type, the result
4649  // shall be the alignment of the referenced type.
4650  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4651  ExprType = Ref->getPointeeType();
4652 
4653  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4654  // When alignof or _Alignof is applied to an array type, the result
4655  // is the alignment of the element type.
4656  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4657  ExprKind == UETT_OpenMPRequiredSimdAlign)
4658  ExprType = Context.getBaseElementType(ExprType);
4659 
4660  if (ExprKind == UETT_VecStep)
4661  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4662 
4663  if (ExprKind == UETT_VectorElements)
4664  return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4665  ExprRange);
4666 
4667  // Explicitly list some types as extensions.
4668  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4669  ExprKind))
4670  return false;
4671 
4672  if (RequireCompleteSizedType(
4673  OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4674  KWName, ExprRange))
4675  return true;
4676 
4677  if (ExprType->isFunctionType()) {
4678  Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4679  return true;
4680  }
4681 
4682  // WebAssembly tables are always illegal operands to unary expressions and
4683  // type traits.
4684  if (Context.getTargetInfo().getTriple().isWasm() &&
4685  ExprType->isWebAssemblyTableType()) {
4686  Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4687  << getTraitSpelling(ExprKind);
4688  return true;
4689  }
4690 
4691  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4692  ExprKind))
4693  return true;
4694 
4695  if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4696  if (auto *TT = ExprType->getAs<TypedefType>()) {
4697  for (auto I = FunctionScopes.rbegin(),
4698  E = std::prev(FunctionScopes.rend());
4699  I != E; ++I) {
4700  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4701  if (CSI == nullptr)
4702  break;
4703  DeclContext *DC = nullptr;
4704  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4705  DC = LSI->CallOperator;
4706  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4707  DC = CRSI->TheCapturedDecl;
4708  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4709  DC = BSI->TheDecl;
4710  if (DC) {
4711  if (DC->containsDecl(TT->getDecl()))
4712  break;
4713  captureVariablyModifiedType(Context, ExprType, CSI);
4714  }
4715  }
4716  }
4717  }
4718 
4719  return false;
4720 }
4721 
4722 /// Build a sizeof or alignof expression given a type operand.
4724  SourceLocation OpLoc,
4725  UnaryExprOrTypeTrait ExprKind,
4726  SourceRange R) {
4727  if (!TInfo)
4728  return ExprError();
4729 
4730  QualType T = TInfo->getType();
4731 
4732  if (!T->isDependentType() &&
4733  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4734  getTraitSpelling(ExprKind)))
4735  return ExprError();
4736 
4737  // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4738  // properly deal with VLAs in nested calls of sizeof and typeof.
4739  if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4740  TInfo->getType()->isVariablyModifiedType())
4741  TInfo = TransformToPotentiallyEvaluated(TInfo);
4742 
4743  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4744  return new (Context) UnaryExprOrTypeTraitExpr(
4745  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4746 }
4747 
4748 /// Build a sizeof or alignof expression given an expression
4749 /// operand.
4750 ExprResult
4752  UnaryExprOrTypeTrait ExprKind) {
4753  ExprResult PE = CheckPlaceholderExpr(E);
4754  if (PE.isInvalid())
4755  return ExprError();
4756 
4757  E = PE.get();
4758 
4759  // Verify that the operand is valid.
4760  bool isInvalid = false;
4761  if (E->isTypeDependent()) {
4762  // Delay type-checking for type-dependent expressions.
4763  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4764  isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4765  } else if (ExprKind == UETT_VecStep) {
4766  isInvalid = CheckVecStepExpr(E);
4767  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4768  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4769  isInvalid = true;
4770  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4771  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4772  isInvalid = true;
4773  } else if (ExprKind == UETT_VectorElements) {
4774  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4775  } else {
4776  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4777  }
4778 
4779  if (isInvalid)
4780  return ExprError();
4781 
4782  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4783  PE = TransformToPotentiallyEvaluated(E);
4784  if (PE.isInvalid()) return ExprError();
4785  E = PE.get();
4786  }
4787 
4788  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4789  return new (Context) UnaryExprOrTypeTraitExpr(
4790  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4791 }
4792 
4793 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4794 /// expr and the same for @c alignof and @c __alignof
4795 /// Note that the ArgRange is invalid if isType is false.
4796 ExprResult
4798  UnaryExprOrTypeTrait ExprKind, bool IsType,
4799  void *TyOrEx, SourceRange ArgRange) {
4800  // If error parsing type, ignore.
4801  if (!TyOrEx) return ExprError();
4802 
4803  if (IsType) {
4804  TypeSourceInfo *TInfo;
4805  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4806  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4807  }
4808 
4809  Expr *ArgEx = (Expr *)TyOrEx;
4810  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4811  return Result;
4812 }
4813 
4814 bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4815  SourceLocation OpLoc, SourceRange R) {
4816  if (!TInfo)
4817  return true;
4818  return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4819  UETT_AlignOf, KWName);
4820 }
4821 
4822 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4823 /// _Alignas(type-name) .
4824 /// [dcl.align] An alignment-specifier of the form
4825 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4826 ///
4827 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4828 /// _Alignas(_Alignof(type-name)).
4829 bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4830  SourceLocation OpLoc, SourceRange R) {
4831  TypeSourceInfo *TInfo;
4832  (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),
4833  &TInfo);
4834  return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4835 }
4836 
4838  bool IsReal) {
4839  if (V.get()->isTypeDependent())
4840  return S.Context.DependentTy;
4841 
4842  // _Real and _Imag are only l-values for normal l-values.
4843  if (V.get()->getObjectKind() != OK_Ordinary) {
4844  V = S.DefaultLvalueConversion(V.get());
4845  if (V.isInvalid())
4846  return QualType();
4847  }
4848 
4849  // These operators return the element type of a complex type.
4850  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4851  return CT->getElementType();
4852 
4853  // Otherwise they pass through real integer and floating point types here.
4854  if (V.get()->getType()->isArithmeticType())
4855  return V.get()->getType();
4856 
4857  // Test for placeholders.
4858  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4859  if (PR.isInvalid()) return QualType();
4860  if (PR.get() != V.get()) {
4861  V = PR;
4862  return CheckRealImagOperand(S, V, Loc, IsReal);
4863  }
4864 
4865  // Reject anything else.
4866  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4867  << (IsReal ? "__real" : "__imag");
4868  return QualType();
4869 }
4870 
4871 
4872 
4873 ExprResult
4875  tok::TokenKind Kind, Expr *Input) {
4876  UnaryOperatorKind Opc;
4877  switch (Kind) {
4878  default: llvm_unreachable("Unknown unary op!");
4879  case tok::plusplus: Opc = UO_PostInc; break;
4880  case tok::minusminus: Opc = UO_PostDec; break;
4881  }
4882 
4883  // Since this might is a postfix expression, get rid of ParenListExprs.
4884  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4885  if (Result.isInvalid()) return ExprError();
4886  Input = Result.get();
4887 
4888  return BuildUnaryOp(S, OpLoc, Opc, Input);
4889 }
4890 
4891 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4892 ///
4893 /// \return true on error
4895  SourceLocation opLoc,
4896  Expr *op) {
4897  assert(op->getType()->isObjCObjectPointerType());
4899  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4900  return false;
4901 
4902  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4903  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4904  << op->getSourceRange();
4905  return true;
4906 }
4907 
4909  auto *BaseNoParens = Base->IgnoreParens();
4910  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4911  return MSProp->getPropertyDecl()->getType()->isArrayType();
4912  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4913 }
4914 
4915 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4916 // Typically this is DependentTy, but can sometimes be more precise.
4917 //
4918 // There are cases when we could determine a non-dependent type:
4919 // - LHS and RHS may have non-dependent types despite being type-dependent
4920 // (e.g. unbounded array static members of the current instantiation)
4921 // - one may be a dependent-sized array with known element type
4922 // - one may be a dependent-typed valid index (enum in current instantiation)
4923 //
4924 // We *always* return a dependent type, in such cases it is DependentTy.
4925 // This avoids creating type-dependent expressions with non-dependent types.
4926 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4928  const ASTContext &Ctx) {
4929  assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4930  QualType LTy = LHS->getType(), RTy = RHS->getType();
4931  QualType Result = Ctx.DependentTy;
4932  if (RTy->isIntegralOrUnscopedEnumerationType()) {
4933  if (const PointerType *PT = LTy->getAs<PointerType>())
4934  Result = PT->getPointeeType();
4935  else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4936  Result = AT->getElementType();
4937  } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4938  if (const PointerType *PT = RTy->getAs<PointerType>())
4939  Result = PT->getPointeeType();
4940  else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4941  Result = AT->getElementType();
4942  }
4943  // Ensure we return a dependent type.
4944  return Result->isDependentType() ? Result : Ctx.DependentTy;
4945 }
4946 
4948  SourceLocation lbLoc,
4949  MultiExprArg ArgExprs,
4950  SourceLocation rbLoc) {
4951 
4952  if (base && !base->getType().isNull() &&
4953  base->hasPlaceholderType(BuiltinType::ArraySection)) {
4954  auto *AS = cast<ArraySectionExpr>(base);
4955  if (AS->isOMPArraySection())
4956  return OpenMP().ActOnOMPArraySectionExpr(
4957  base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4958  /*Length*/ nullptr,
4959  /*Stride=*/nullptr, rbLoc);
4960 
4961  return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4962  SourceLocation(), /*Length*/ nullptr,
4963  rbLoc);
4964  }
4965 
4966  // Since this might be a postfix expression, get rid of ParenListExprs.
4967  if (isa<ParenListExpr>(base)) {
4968  ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4969  if (result.isInvalid())
4970  return ExprError();
4971  base = result.get();
4972  }
4973 
4974  // Check if base and idx form a MatrixSubscriptExpr.
4975  //
4976  // Helper to check for comma expressions, which are not allowed as indices for
4977  // matrix subscript expressions.
4978  auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4979  if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4980  Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4981  << SourceRange(base->getBeginLoc(), rbLoc);
4982  return true;
4983  }
4984  return false;
4985  };
4986  // The matrix subscript operator ([][])is considered a single operator.
4987  // Separating the index expressions by parenthesis is not allowed.
4988  if (base && !base->getType().isNull() &&
4989  base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4990  !isa<MatrixSubscriptExpr>(base)) {
4991  Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4992  << SourceRange(base->getBeginLoc(), rbLoc);
4993  return ExprError();
4994  }
4995  // If the base is a MatrixSubscriptExpr, try to create a new
4996  // MatrixSubscriptExpr.
4997  auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4998  if (matSubscriptE) {
4999  assert(ArgExprs.size() == 1);
5000  if (CheckAndReportCommaError(ArgExprs.front()))
5001  return ExprError();
5002 
5003  assert(matSubscriptE->isIncomplete() &&
5004  "base has to be an incomplete matrix subscript");
5005  return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5006  matSubscriptE->getRowIdx(),
5007  ArgExprs.front(), rbLoc);
5008  }
5009  if (base->getType()->isWebAssemblyTableType()) {
5010  Diag(base->getExprLoc(), diag::err_wasm_table_art)
5011  << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5012  return ExprError();
5013  }
5014 
5015  // Handle any non-overload placeholder types in the base and index
5016  // expressions. We can't handle overloads here because the other
5017  // operand might be an overloadable type, in which case the overload
5018  // resolution for the operator overload should get the first crack
5019  // at the overload.
5020  bool IsMSPropertySubscript = false;
5021  if (base->getType()->isNonOverloadPlaceholderType()) {
5022  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5023  if (!IsMSPropertySubscript) {
5024  ExprResult result = CheckPlaceholderExpr(base);
5025  if (result.isInvalid())
5026  return ExprError();
5027  base = result.get();
5028  }
5029  }
5030 
5031  // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5032  if (base->getType()->isMatrixType()) {
5033  assert(ArgExprs.size() == 1);
5034  if (CheckAndReportCommaError(ArgExprs.front()))
5035  return ExprError();
5036 
5037  return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5038  rbLoc);
5039  }
5040 
5041  if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5042  Expr *idx = ArgExprs[0];
5043  if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5044  (isa<CXXOperatorCallExpr>(idx) &&
5045  cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5046  Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5047  << SourceRange(base->getBeginLoc(), rbLoc);
5048  }
5049  }
5050 
5051  if (ArgExprs.size() == 1 &&
5052  ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5053  ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5054  if (result.isInvalid())
5055  return ExprError();
5056  ArgExprs[0] = result.get();
5057  } else {
5058  if (CheckArgsForPlaceholders(ArgExprs))
5059  return ExprError();
5060  }
5061 
5062  // Build an unanalyzed expression if either operand is type-dependent.
5063  if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5064  (base->isTypeDependent() ||
5066  !isa<PackExpansionExpr>(ArgExprs[0])) {
5067  return new (Context) ArraySubscriptExpr(
5068  base, ArgExprs.front(),
5069  getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5070  VK_LValue, OK_Ordinary, rbLoc);
5071  }
5072 
5073  // MSDN, property (C++)
5074  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5075  // This attribute can also be used in the declaration of an empty array in a
5076  // class or structure definition. For example:
5077  // __declspec(property(get=GetX, put=PutX)) int x[];
5078  // The above statement indicates that x[] can be used with one or more array
5079  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5080  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5081  if (IsMSPropertySubscript) {
5082  assert(ArgExprs.size() == 1);
5083  // Build MS property subscript expression if base is MS property reference
5084  // or MS property subscript.
5085  return new (Context)
5086  MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5087  VK_LValue, OK_Ordinary, rbLoc);
5088  }
5089 
5090  // Use C++ overloaded-operator rules if either operand has record
5091  // type. The spec says to do this if either type is *overloadable*,
5092  // but enum types can't declare subscript operators or conversion
5093  // operators, so there's nothing interesting for overload resolution
5094  // to do if there aren't any record types involved.
5095  //
5096  // ObjC pointers have their own subscripting logic that is not tied
5097  // to overload resolution and so should not take this path.
5098  if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5099  ((base->getType()->isRecordType() ||
5100  (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5101  ArgExprs[0]->getType()->isRecordType())))) {
5102  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5103  }
5104 
5105  ExprResult Res =
5106  CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5107 
5108  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5109  CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5110 
5111  return Res;
5112 }
5113 
5118  InitializationSequence InitSeq(*this, Entity, Kind, E);
5119  return InitSeq.Perform(*this, Entity, Kind, E);
5120 }
5121 
5123  Expr *ColumnIdx,
5124  SourceLocation RBLoc) {
5125  ExprResult BaseR = CheckPlaceholderExpr(Base);
5126  if (BaseR.isInvalid())
5127  return BaseR;
5128  Base = BaseR.get();
5129 
5130  ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5131  if (RowR.isInvalid())
5132  return RowR;
5133  RowIdx = RowR.get();
5134 
5135  if (!ColumnIdx)
5136  return new (Context) MatrixSubscriptExpr(
5137  Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5138 
5139  // Build an unanalyzed expression if any of the operands is type-dependent.
5140  if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5141  ColumnIdx->isTypeDependent())
5142  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5143  Context.DependentTy, RBLoc);
5144 
5145  ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5146  if (ColumnR.isInvalid())
5147  return ColumnR;
5148  ColumnIdx = ColumnR.get();
5149 
5150  // Check that IndexExpr is an integer expression. If it is a constant
5151  // expression, check that it is less than Dim (= the number of elements in the
5152  // corresponding dimension).
5153  auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5154  bool IsColumnIdx) -> Expr * {
5155  if (!IndexExpr->getType()->isIntegerType() &&
5156  !IndexExpr->isTypeDependent()) {
5157  Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5158  << IsColumnIdx;
5159  return nullptr;
5160  }
5161 
5162  if (std::optional<llvm::APSInt> Idx =
5163  IndexExpr->getIntegerConstantExpr(Context)) {
5164  if ((*Idx < 0 || *Idx >= Dim)) {
5165  Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5166  << IsColumnIdx << Dim;
5167  return nullptr;
5168  }
5169  }
5170 
5171  ExprResult ConvExpr =
5172  tryConvertExprToType(IndexExpr, Context.getSizeType());
5173  assert(!ConvExpr.isInvalid() &&
5174  "should be able to convert any integer type to size type");
5175  return ConvExpr.get();
5176  };
5177 
5178  auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5179  RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5180  ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5181  if (!RowIdx || !ColumnIdx)
5182  return ExprError();
5183 
5184  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5185  MTy->getElementType(), RBLoc);
5186 }
5187 
5188 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5189  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5190  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5191 
5192  // For expressions like `&(*s).b`, the base is recorded and what should be
5193  // checked.
5194  const MemberExpr *Member = nullptr;
5195  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5196  StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5197 
5198  LastRecord.PossibleDerefs.erase(StrippedExpr);
5199 }
5200 
5201 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5202  if (isUnevaluatedContext())
5203  return;
5204 
5205  QualType ResultTy = E->getType();
5206  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5207 
5208  // Bail if the element is an array since it is not memory access.
5209  if (isa<ArrayType>(ResultTy))
5210  return;
5211 
5212  if (ResultTy->hasAttr(attr::NoDeref)) {
5213  LastRecord.PossibleDerefs.insert(E);
5214  return;
5215  }
5216 
5217  // Check if the base type is a pointer to a member access of a struct
5218  // marked with noderef.
5219  const Expr *Base = E->getBase();
5220  QualType BaseTy = Base->getType();
5221  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5222  // Not a pointer access
5223  return;
5224 
5225  const MemberExpr *Member = nullptr;
5226  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5227  Member->isArrow())
5228  Base = Member->getBase();
5229 
5230  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5231  if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5232  LastRecord.PossibleDerefs.insert(E);
5233  }
5234 }
5235 
5236 ExprResult
5238  Expr *Idx, SourceLocation RLoc) {
5239  Expr *LHSExp = Base;
5240  Expr *RHSExp = Idx;
5241 
5242  ExprValueKind VK = VK_LValue;
5244 
5245  // Per C++ core issue 1213, the result is an xvalue if either operand is
5246  // a non-lvalue array, and an lvalue otherwise.
5247  if (getLangOpts().CPlusPlus11) {
5248  for (auto *Op : {LHSExp, RHSExp}) {
5249  Op = Op->IgnoreImplicit();
5250  if (Op->getType()->isArrayType() && !Op->isLValue())
5251  VK = VK_XValue;
5252  }
5253  }
5254 
5255  // Perform default conversions.
5256  if (!LHSExp->getType()->isSubscriptableVectorType()) {
5257  ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5258  if (Result.isInvalid())
5259  return ExprError();
5260  LHSExp = Result.get();
5261  }
5262  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5263  if (Result.isInvalid())
5264  return ExprError();
5265  RHSExp = Result.get();
5266 
5267  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5268 
5269  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5270  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5271  // in the subscript position. As a result, we need to derive the array base
5272  // and index from the expression types.
5273  Expr *BaseExpr, *IndexExpr;
5274  QualType ResultType;
5275  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5276  BaseExpr = LHSExp;
5277  IndexExpr = RHSExp;
5278  ResultType =
5279  getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5280  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5281  BaseExpr = LHSExp;
5282  IndexExpr = RHSExp;
5283  ResultType = PTy->getPointeeType();
5284  } else if (const ObjCObjectPointerType *PTy =
5285  LHSTy->getAs<ObjCObjectPointerType>()) {
5286  BaseExpr = LHSExp;
5287  IndexExpr = RHSExp;
5288 
5289  // Use custom logic if this should be the pseudo-object subscript
5290  // expression.
5291  if (!LangOpts.isSubscriptPointerArithmetic())
5292  return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5293  nullptr, nullptr);
5294 
5295  ResultType = PTy->getPointeeType();
5296  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5297  // Handle the uncommon case of "123[Ptr]".
5298  BaseExpr = RHSExp;
5299  IndexExpr = LHSExp;
5300  ResultType = PTy->getPointeeType();
5301  } else if (const ObjCObjectPointerType *PTy =
5302  RHSTy->getAs<ObjCObjectPointerType>()) {
5303  // Handle the uncommon case of "123[Ptr]".
5304  BaseExpr = RHSExp;
5305  IndexExpr = LHSExp;
5306  ResultType = PTy->getPointeeType();
5307  if (!LangOpts.isSubscriptPointerArithmetic()) {
5308  Diag(LLoc, diag::err_subscript_nonfragile_interface)
5309  << ResultType << BaseExpr->getSourceRange();
5310  return ExprError();
5311  }
5312  } else if (LHSTy->isSubscriptableVectorType()) {
5313  if (LHSTy->isBuiltinType() &&
5314  LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5315  const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5316  if (BTy->isSVEBool())
5317  return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5318  << LHSExp->getSourceRange()
5319  << RHSExp->getSourceRange());
5320  ResultType = BTy->getSveEltType(Context);
5321  } else {
5322  const VectorType *VTy = LHSTy->getAs<VectorType>();
5323  ResultType = VTy->getElementType();
5324  }
5325  BaseExpr = LHSExp; // vectors: V[123]
5326  IndexExpr = RHSExp;
5327  // We apply C++ DR1213 to vector subscripting too.
5328  if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5329  ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5330  if (Materialized.isInvalid())
5331  return ExprError();
5332  LHSExp = Materialized.get();
5333  }
5334  VK = LHSExp->getValueKind();
5335  if (VK != VK_PRValue)
5336  OK = OK_VectorComponent;
5337 
5338  QualType BaseType = BaseExpr->getType();
5339  Qualifiers BaseQuals = BaseType.getQualifiers();
5340  Qualifiers MemberQuals = ResultType.getQualifiers();
5341  Qualifiers Combined = BaseQuals + MemberQuals;
5342  if (Combined != MemberQuals)
5343  ResultType = Context.getQualifiedType(ResultType, Combined);
5344  } else if (LHSTy->isArrayType()) {
5345  // If we see an array that wasn't promoted by
5346  // DefaultFunctionArrayLvalueConversion, it must be an array that
5347  // wasn't promoted because of the C90 rule that doesn't
5348  // allow promoting non-lvalue arrays. Warn, then
5349  // force the promotion here.
5350  Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5351  << LHSExp->getSourceRange();
5352  LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5353  CK_ArrayToPointerDecay).get();
5354  LHSTy = LHSExp->getType();
5355 
5356  BaseExpr = LHSExp;
5357  IndexExpr = RHSExp;
5358  ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5359  } else if (RHSTy->isArrayType()) {
5360  // Same as previous, except for 123[f().a] case
5361  Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5362  << RHSExp->getSourceRange();
5363  RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5364  CK_ArrayToPointerDecay).get();
5365  RHSTy = RHSExp->getType();
5366 
5367  BaseExpr = RHSExp;
5368  IndexExpr = LHSExp;
5369  ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5370  } else {
5371  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5372  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5373  }
5374  // C99 6.5.2.1p1
5375  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5376  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5377  << IndexExpr->getSourceRange());
5378 
5379  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5380  IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5381  !IndexExpr->isTypeDependent()) {
5382  std::optional<llvm::APSInt> IntegerContantExpr =
5383  IndexExpr->getIntegerConstantExpr(getASTContext());
5384  if (!IntegerContantExpr.has_value() ||
5385  IntegerContantExpr.value().isNegative())
5386  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5387  }
5388 
5389  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5390  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5391  // type. Note that Functions are not objects, and that (in C99 parlance)
5392  // incomplete types are not object types.
5393  if (ResultType->isFunctionType()) {
5394  Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5395  << ResultType << BaseExpr->getSourceRange();
5396  return ExprError();
5397  }
5398 
5399  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5400  // GNU extension: subscripting on pointer to void
5401  Diag(LLoc, diag::ext_gnu_subscript_void_type)
5402  << BaseExpr->getSourceRange();
5403 
5404  // C forbids expressions of unqualified void type from being l-values.
5405  // See IsCForbiddenLValueType.
5406  if (!ResultType.hasQualifiers())
5407  VK = VK_PRValue;
5408  } else if (!ResultType->isDependentType() &&
5409  !ResultType.isWebAssemblyReferenceType() &&
5410  RequireCompleteSizedType(
5411  LLoc, ResultType,
5412  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5413  return ExprError();
5414 
5415  assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5416  !ResultType.isCForbiddenLValueType());
5417 
5418  if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5419  FunctionScopes.size() > 1) {
5420  if (auto *TT =
5421  LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5422  for (auto I = FunctionScopes.rbegin(),
5423  E = std::prev(FunctionScopes.rend());
5424  I != E; ++I) {
5425  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5426  if (CSI == nullptr)
5427  break;
5428  DeclContext *DC = nullptr;
5429  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5430  DC = LSI->CallOperator;
5431  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5432  DC = CRSI->TheCapturedDecl;
5433  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5434  DC = BSI->TheDecl;
5435  if (DC) {
5436  if (DC->containsDecl(TT->getDecl()))
5437  break;
5439  Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5440  }
5441  }
5442  }
5443  }
5444 
5445  return new (Context)
5446  ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5447 }
5448 
5450  ParmVarDecl *Param, Expr *RewrittenInit,
5451  bool SkipImmediateInvocations) {
5452  if (Param->hasUnparsedDefaultArg()) {
5453  assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5454  // If we've already cleared out the location for the default argument,
5455  // that means we're parsing it right now.
5456  if (!UnparsedDefaultArgLocs.count(Param)) {
5457  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5458  Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5459  Param->setInvalidDecl();
5460  return true;
5461  }
5462 
5463  Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5464  << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5465  Diag(UnparsedDefaultArgLocs[Param],
5466  diag::note_default_argument_declared_here);
5467  return true;
5468  }
5469 
5470  if (Param->hasUninstantiatedDefaultArg()) {
5471  assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5472  if (InstantiateDefaultArgument(CallLoc, FD, Param))
5473  return true;
5474  }
5475 
5476  Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5477  assert(Init && "default argument but no initializer?");
5478 
5479  // If the default expression creates temporaries, we need to
5480  // push them to the current stack of expression temporaries so they'll
5481  // be properly destroyed.
5482  // FIXME: We should really be rebuilding the default argument with new
5483  // bound temporaries; see the comment in PR5810.
5484  // We don't need to do that with block decls, though, because
5485  // blocks in default argument expression can never capture anything.
5486  if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5487  // Set the "needs cleanups" bit regardless of whether there are
5488  // any explicit objects.
5489  Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5490  // Append all the objects to the cleanup list. Right now, this
5491  // should always be a no-op, because blocks in default argument
5492  // expressions should never be able to capture anything.
5493  assert(!InitWithCleanup->getNumObjects() &&
5494  "default argument expression has capturing blocks?");
5495  }
5496  // C++ [expr.const]p15.1:
5497  // An expression or conversion is in an immediate function context if it is
5498  // potentially evaluated and [...] its innermost enclosing non-block scope
5499  // is a function parameter scope of an immediate function.
5501  *this,
5502  FD->isImmediateFunction()
5503  ? ExpressionEvaluationContext::ImmediateFunctionContext
5504  : ExpressionEvaluationContext::PotentiallyEvaluated,
5505  Param);
5506  ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5507  SkipImmediateInvocations;
5508  runWithSufficientStackSpace(CallLoc, [&] {
5509  MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5510  });
5511  return false;
5512 }
5513 
5514 struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5516  ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5517 
5518  bool HasImmediateCalls = false;
5519  bool shouldVisitImplicitCode() const { return true; }
5520 
5522  if (const FunctionDecl *FD = E->getDirectCallee())
5523  HasImmediateCalls |= FD->isImmediateFunction();
5525  }
5526 
5528  if (const FunctionDecl *FD = E->getConstructor())
5529  HasImmediateCalls |= FD->isImmediateFunction();
5531  }
5532 
5533  // SourceLocExpr are not immediate invocations
5534  // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5535  // need to be rebuilt so that they refer to the correct SourceLocation and
5536  // DeclContext.
5538  HasImmediateCalls = true;
5540  }
5541 
5542  // A nested lambda might have parameters with immediate invocations
5543  // in their default arguments.
5544  // The compound statement is not visited (as it does not constitute a
5545  // subexpression).
5546  // FIXME: We should consider visiting and transforming captures
5547  // with init expressions.
5549  return VisitCXXMethodDecl(E->getCallOperator());
5550  }
5551 
5553  return TraverseStmt(E->getExpr());
5554  }
5555 
5557  return TraverseStmt(E->getExpr());
5558  }
5559 };
5560 
5562  : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5564  : TreeTransform(SemaRef) {}
5565 
5566  // Lambda can only have immediate invocations in the default
5567  // args of their parameters, which is transformed upon calling the closure.
5568  // The body is not a subexpression, so we have nothing to do.
5569  // FIXME: Immediate calls in capture initializers should be transformed.
5572 
5573  // Make sure we don't rebuild the this pointer as it would
5574  // cause it to incorrectly point it to the outermost class
5575  // in the case of nested struct initialization.
5577 
5578  // Rewrite to source location to refer to the context in which they are used.
5580  if (E->getParentContext() == SemaRef.CurContext)
5581  return E;
5582  return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
5583  E->getBeginLoc(), E->getEndLoc(),
5584  SemaRef.CurContext);
5585  }
5586 };
5587 
5589  FunctionDecl *FD, ParmVarDecl *Param,
5590  Expr *Init) {
5591  assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5592 
5593  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5594  bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5595  std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5596  InitializationContext =
5597  OutermostDeclarationWithDelayedImmediateInvocations();
5598  if (!InitializationContext.has_value())
5599  InitializationContext.emplace(CallLoc, Param, CurContext);
5600 
5601  if (!Init && !Param->hasUnparsedDefaultArg()) {
5602  // Mark that we are replacing a default argument first.
5603  // If we are instantiating a template we won't have to
5604  // retransform immediate calls.
5605  // C++ [expr.const]p15.1:
5606  // An expression or conversion is in an immediate function context if it
5607  // is potentially evaluated and [...] its innermost enclosing non-block
5608  // scope is a function parameter scope of an immediate function.
5610  *this,
5611  FD->isImmediateFunction()
5612  ? ExpressionEvaluationContext::ImmediateFunctionContext
5613  : ExpressionEvaluationContext::PotentiallyEvaluated,
5614  Param);
5615 
5616  if (Param->hasUninstantiatedDefaultArg()) {
5617  if (InstantiateDefaultArgument(CallLoc, FD, Param))
5618  return ExprError();
5619  }
5620  // CWG2631
5621  // An immediate invocation that is not evaluated where it appears is
5622  // evaluated and checked for whether it is a constant expression at the
5623  // point where the enclosing initializer is used in a function call.
5624  ImmediateCallVisitor V(getASTContext());
5625  if (!NestedDefaultChecking)
5626  V.TraverseDecl(Param);
5627 
5628  // Rewrite the call argument that was created from the corresponding
5629  // parameter's default argument.
5630  if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5631  if (V.HasImmediateCalls)
5632  ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5633  CallLoc, Param, CurContext};
5634  // Pass down lifetime extending flag, and collect temporaries in
5635  // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5636  keepInLifetimeExtendingContext();
5637  EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5638  ExprResult Res;
5639  runWithSufficientStackSpace(CallLoc, [&] {
5640  Res = Immediate.TransformInitializer(Param->getInit(),
5641  /*NotCopy=*/false);
5642  });
5643  if (Res.isUsable())
5644  Res = ConvertParamDefaultArgument(Param, Res.get(),
5645  Res.get()->getBeginLoc());
5646  if (Res.isInvalid())
5647  return ExprError();
5648  Init = Res.get();
5649  }
5650  }
5651 
5652  if (CheckCXXDefaultArgExpr(
5653  CallLoc, FD, Param, Init,
5654  /*SkipImmediateInvocations=*/NestedDefaultChecking))
5655  return ExprError();
5656 
5657  return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5658  Init, InitializationContext->Context);
5659 }
5660 
5662  assert(Field->hasInClassInitializer());
5663 
5664  // If we might have already tried and failed to instantiate, don't try again.
5665  if (Field->isInvalidDecl())
5666  return ExprError();
5667 
5668  CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5669 
5670  auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5671 
5672  std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5673  InitializationContext =
5674  OutermostDeclarationWithDelayedImmediateInvocations();
5675  if (!InitializationContext.has_value())
5676  InitializationContext.emplace(Loc, Field, CurContext);
5677 
5678  Expr *Init = nullptr;
5679  bool HasRewrittenInit = false;
5680 
5681  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5682  bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5684  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5685 
5686  if (!Field->getInClassInitializer()) {
5687  // Maybe we haven't instantiated the in-class initializer. Go check the
5688  // pattern FieldDecl to see if it has one.
5689  if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5690  CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5692  ClassPattern->lookup(Field->getDeclName());
5693 
5694  FieldDecl *Pattern = nullptr;
5695  for (auto *L : Lookup) {
5696  if ((Pattern = dyn_cast<FieldDecl>(L)))
5697  break;
5698  }
5699  assert(Pattern && "We must have set the Pattern!");
5700  if (!Pattern->hasInClassInitializer() ||
5701  InstantiateInClassInitializer(Loc, Field, Pattern,
5702  getTemplateInstantiationArgs(Field))) {
5703  Field->setInvalidDecl();
5704  return ExprError();
5705  }
5706  }
5707  }
5708 
5709  // CWG2631
5710  // An immediate invocation that is not evaluated where it appears is
5711  // evaluated and checked for whether it is a constant expression at the
5712  // point where the enclosing initializer is used in a [...] a constructor
5713  // definition, or an aggregate initialization.
5714  ImmediateCallVisitor V(getASTContext());
5715  if (!NestedDefaultChecking)
5716  V.TraverseDecl(Field);
5717 
5718  // CWG1815
5719  // Support lifetime extension of temporary created by aggregate
5720  // initialization using a default member initializer. We should always rebuild
5721  // the initializer if it contains any temporaries (if the initializer
5722  // expression is an ExprWithCleanups). Then make sure the normal lifetime
5723  // extension code recurses into the default initializer and does lifetime
5724  // extension when warranted.
5725  bool ContainsAnyTemporaries =
5726  isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5727  if (V.HasImmediateCalls || InLifetimeExtendingContext ||
5728  ContainsAnyTemporaries) {
5729  HasRewrittenInit = true;
5730  ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5731  CurContext};
5732  ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5733  NestedDefaultChecking;
5734  // Pass down lifetime extending flag, and collect temporaries in
5735  // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5736  keepInLifetimeExtendingContext();
5737  EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5738  ExprResult Res;
5739 
5740  // Rebuild CXXDefaultInitExpr might cause diagnostics.
5741  SFINAETrap Trap(*this);
5743  Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5744  /*CXXDirectInit=*/false);
5745  });
5746  if (Res.isUsable())
5747  Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5748  if (Res.isInvalid()) {
5749  Field->setInvalidDecl();
5750  return ExprError();
5751  }
5752  Init = Res.get();
5753  }
5754 
5755  if (Field->getInClassInitializer()) {
5756  Expr *E = Init ? Init : Field->getInClassInitializer();
5757  if (!NestedDefaultChecking)
5759  MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5760  });
5761  // C++11 [class.base.init]p7:
5762  // The initialization of each base and member constitutes a
5763  // full-expression.
5764  ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5765  if (Res.isInvalid()) {
5766  Field->setInvalidDecl();
5767  return ExprError();
5768  }
5769  Init = Res.get();
5770 
5771  return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5772  Field, InitializationContext->Context,
5773  HasRewrittenInit ? Init : nullptr);
5774  }
5775 
5776  // DR1351:
5777  // If the brace-or-equal-initializer of a non-static data member
5778  // invokes a defaulted default constructor of its class or of an
5779  // enclosing class in a potentially evaluated subexpression, the
5780  // program is ill-formed.
5781  //
5782  // This resolution is unworkable: the exception specification of the
5783  // default constructor can be needed in an unevaluated context, in
5784  // particular, in the operand of a noexcept-expression, and we can be
5785  // unable to compute an exception specification for an enclosed class.
5786  //
5787  // Any attempt to resolve the exception specification of a defaulted default
5788  // constructor before the initializer is lexically complete will ultimately
5789  // come here at which point we can diagnose it.
5790  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5791  Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5792  << OutermostClass << Field;
5793  Diag(Field->getEndLoc(),
5794  diag::note_default_member_initializer_not_yet_parsed);
5795  // Recover by marking the field invalid, unless we're in a SFINAE context.
5796  if (!isSFINAEContext())
5797  Field->setInvalidDecl();
5798  return ExprError();
5799 }
5800 
5803  Expr *Fn) {
5804  if (Proto && Proto->isVariadic()) {
5805  if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5806  return VariadicConstructor;
5807  else if (Fn && Fn->getType()->isBlockPointerType())
5808  return VariadicBlock;
5809  else if (FDecl) {
5810  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5811  if (Method->isInstance())
5812  return VariadicMethod;
5813  } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5814  return VariadicMethod;
5815  return VariadicFunction;
5816  }
5817  return VariadicDoesNotApply;
5818 }
5819 
5820 namespace {
5821 class FunctionCallCCC final : public FunctionCallFilterCCC {
5822 public:
5823  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5824  unsigned NumArgs, MemberExpr *ME)
5825  : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5826  FunctionName(FuncName) {}
5827 
5828  bool ValidateCandidate(const TypoCorrection &candidate) override {
5829  if (!candidate.getCorrectionSpecifier() ||
5830  candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5831  return false;
5832  }
5833 
5834  return FunctionCallFilterCCC::ValidateCandidate(candidate);
5835  }
5836 
5837  std::unique_ptr<CorrectionCandidateCallback> clone() override {
5838  return std::make_unique<FunctionCallCCC>(*this);
5839  }
5840 
5841 private:
5842  const IdentifierInfo *const FunctionName;
5843 };
5844 }
5845 
5847  FunctionDecl *FDecl,
5848  ArrayRef<Expr *> Args) {
5849  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5850  DeclarationName FuncName = FDecl->getDeclName();
5851  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5852 
5853  FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5854  if (TypoCorrection Corrected = S.CorrectTypo(
5855  DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5856  S.getScopeForContext(S.CurContext), nullptr, CCC,
5858  if (NamedDecl *ND = Corrected.getFoundDecl()) {
5859  if (Corrected.isOverloaded()) {
5862  for (NamedDecl *CD : Corrected) {
5863  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5865  OCS);
5866  }
5867  switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5868  case OR_Success:
5869  ND = Best->FoundDecl;
5870  Corrected.setCorrectionDecl(ND);
5871  break;
5872  default:
5873  break;
5874  }
5875  }
5876  ND = ND->getUnderlyingDecl();
5877  if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5878  return Corrected;
5879  }
5880  }
5881  return TypoCorrection();
5882 }
5883 
5884 /// ConvertArgumentsForCall - Converts the arguments specified in
5885 /// Args/NumArgs to the parameter types of the function FDecl with
5886 /// function prototype Proto. Call is the call expression itself, and
5887 /// Fn is the function expression. For a C++ member function, this
5888 /// routine does not attempt to convert the object argument. Returns
5889 /// true if the call is ill-formed.
5890 bool
5892  FunctionDecl *FDecl,
5893  const FunctionProtoType *Proto,
5894  ArrayRef<Expr *> Args,
5895  SourceLocation RParenLoc,
5896  bool IsExecConfig) {
5897  // Bail out early if calling a builtin with custom typechecking.
5898  if (FDecl)
5899  if (unsigned ID = FDecl->getBuiltinID())
5900  if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5901  return false;
5902 
5903  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5904  // assignment, to the types of the corresponding parameter, ...
5905  bool HasExplicitObjectParameter =
5906  FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5907  unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5908  unsigned NumParams = Proto->getNumParams();
5909  bool Invalid = false;
5910  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5911  unsigned FnKind = Fn->getType()->isBlockPointerType()
5912  ? 1 /* block */
5913  : (IsExecConfig ? 3 /* kernel function (exec config) */
5914  : 0 /* function */);
5915 
5916  // If too few arguments are available (and we don't have default
5917  // arguments for the remaining parameters), don't make the call.
5918  if (Args.size() < NumParams) {
5919  if (Args.size() < MinArgs) {
5920  TypoCorrection TC;
5921  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5922  unsigned diag_id =
5923  MinArgs == NumParams && !Proto->isVariadic()
5924  ? diag::err_typecheck_call_too_few_args_suggest
5925  : diag::err_typecheck_call_too_few_args_at_least_suggest;
5926  diagnoseTypo(
5927  TC, PDiag(diag_id)
5928  << FnKind << MinArgs - ExplicitObjectParameterOffset
5929  << static_cast<unsigned>(Args.size()) -
5930  ExplicitObjectParameterOffset
5931  << HasExplicitObjectParameter << TC.getCorrectionRange());
5932  } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5933  FDecl->getParamDecl(ExplicitObjectParameterOffset)
5934  ->getDeclName())
5935  Diag(RParenLoc,
5936  MinArgs == NumParams && !Proto->isVariadic()
5937  ? diag::err_typecheck_call_too_few_args_one
5938  : diag::err_typecheck_call_too_few_args_at_least_one)
5939  << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5940  << HasExplicitObjectParameter << Fn->getSourceRange();
5941  else
5942  Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5943  ? diag::err_typecheck_call_too_few_args
5944  : diag::err_typecheck_call_too_few_args_at_least)
5945  << FnKind << MinArgs - ExplicitObjectParameterOffset
5946  << static_cast<unsigned>(Args.size()) -
5947  ExplicitObjectParameterOffset
5948  << HasExplicitObjectParameter << Fn->getSourceRange();
5949 
5950  // Emit the location of the prototype.
5951  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5952  Diag(FDecl->getLocation(), diag::note_callee_decl)
5953  << FDecl << FDecl->getParametersSourceRange();
5954 
5955  return true;
5956  }
5957  // We reserve space for the default arguments when we create
5958  // the call expression, before calling ConvertArgumentsForCall.
5959  assert((Call->getNumArgs() == NumParams) &&
5960  "We should have reserved space for the default arguments before!");
5961  }
5962 
5963  // If too many are passed and not variadic, error on the extras and drop
5964  // them.
5965  if (Args.size() > NumParams) {
5966  if (!Proto->isVariadic()) {
5967  TypoCorrection TC;
5968  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5969  unsigned diag_id =
5970  MinArgs == NumParams && !Proto->isVariadic()
5971  ? diag::err_typecheck_call_too_many_args_suggest
5972  : diag::err_typecheck_call_too_many_args_at_most_suggest;
5973  diagnoseTypo(
5974  TC, PDiag(diag_id)
5975  << FnKind << NumParams - ExplicitObjectParameterOffset
5976  << static_cast<unsigned>(Args.size()) -
5977  ExplicitObjectParameterOffset
5978  << HasExplicitObjectParameter << TC.getCorrectionRange());
5979  } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5980  FDecl->getParamDecl(ExplicitObjectParameterOffset)
5981  ->getDeclName())
5982  Diag(Args[NumParams]->getBeginLoc(),
5983  MinArgs == NumParams
5984  ? diag::err_typecheck_call_too_many_args_one
5985  : diag::err_typecheck_call_too_many_args_at_most_one)
5986  << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5987  << static_cast<unsigned>(Args.size()) -
5988  ExplicitObjectParameterOffset
5989  << HasExplicitObjectParameter << Fn->getSourceRange()
5990  << SourceRange(Args[NumParams]->getBeginLoc(),
5991  Args.back()->getEndLoc());
5992  else
5993  Diag(Args[NumParams]->getBeginLoc(),
5994  MinArgs == NumParams
5995  ? diag::err_typecheck_call_too_many_args
5996  : diag::err_typecheck_call_too_many_args_at_most)
5997  << FnKind << NumParams - ExplicitObjectParameterOffset
5998  << static_cast<unsigned>(Args.size()) -
5999  ExplicitObjectParameterOffset
6000  << HasExplicitObjectParameter << Fn->getSourceRange()
6001  << SourceRange(Args[NumParams]->getBeginLoc(),
6002  Args.back()->getEndLoc());
6003 
6004  // Emit the location of the prototype.
6005  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6006  Diag(FDecl->getLocation(), diag::note_callee_decl)
6007  << FDecl << FDecl->getParametersSourceRange();
6008 
6009  // This deletes the extra arguments.
6010  Call->shrinkNumArgs(NumParams);
6011  return true;
6012  }
6013  }
6014  SmallVector<Expr *, 8> AllArgs;
6015  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6016 
6017  Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6018  AllArgs, CallType);
6019  if (Invalid)
6020  return true;
6021  unsigned TotalNumArgs = AllArgs.size();
6022  for (unsigned i = 0; i < TotalNumArgs; ++i)
6023  Call->setArg(i, AllArgs[i]);
6024 
6025  Call->computeDependence();
6026  return false;
6027 }
6028 
6030  const FunctionProtoType *Proto,
6031  unsigned FirstParam, ArrayRef<Expr *> Args,
6032  SmallVectorImpl<Expr *> &AllArgs,
6033  VariadicCallType CallType, bool AllowExplicit,
6034  bool IsListInitialization) {
6035  unsigned NumParams = Proto->getNumParams();
6036  bool Invalid = false;
6037  size_t ArgIx = 0;
6038  // Continue to check argument types (even if we have too few/many args).
6039  for (unsigned i = FirstParam; i < NumParams; i++) {
6040  QualType ProtoArgType = Proto->getParamType(i);
6041 
6042  Expr *Arg;
6043  ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6044  if (ArgIx < Args.size()) {
6045  Arg = Args[ArgIx++];
6046 
6047  if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6048  diag::err_call_incomplete_argument, Arg))
6049  return true;
6050 
6051  // Strip the unbridged-cast placeholder expression off, if applicable.
6052  bool CFAudited = false;
6053  if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6054  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6055  (!Param || !Param->hasAttr<CFConsumedAttr>()))
6056  Arg = ObjC().stripARCUnbridgedCast(Arg);
6057  else if (getLangOpts().ObjCAutoRefCount &&
6058  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6059  (!Param || !Param->hasAttr<CFConsumedAttr>()))
6060  CFAudited = true;
6061 
6062  if (Proto->getExtParameterInfo(i).isNoEscape() &&
6063  ProtoArgType->isBlockPointerType())
6064  if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6065  BE->getBlockDecl()->setDoesNotEscape();
6066 
6067  InitializedEntity Entity =
6068  Param ? InitializedEntity::InitializeParameter(Context, Param,
6069  ProtoArgType)
6071  Context, ProtoArgType, Proto->isParamConsumed(i));
6072 
6073  // Remember that parameter belongs to a CF audited API.
6074  if (CFAudited)
6075  Entity.setParameterCFAudited();
6076 
6077  ExprResult ArgE = PerformCopyInitialization(
6078  Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6079  if (ArgE.isInvalid())
6080  return true;
6081 
6082  Arg = ArgE.getAs<Expr>();
6083  } else {
6084  assert(Param && "can't use default arguments without a known callee");
6085 
6086  ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6087  if (ArgExpr.isInvalid())
6088  return true;
6089 
6090  Arg = ArgExpr.getAs<Expr>();
6091  }
6092 
6093  // Check for array bounds violations for each argument to the call. This
6094  // check only triggers warnings when the argument isn't a more complex Expr
6095  // with its own checking, such as a BinaryOperator.
6096  CheckArrayAccess(Arg);
6097 
6098  // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6099  CheckStaticArrayArgument(CallLoc, Param, Arg);
6100 
6101  AllArgs.push_back(Arg);
6102  }
6103 
6104  // If this is a variadic call, handle args passed through "...".
6105  if (CallType != VariadicDoesNotApply) {
6106  // Assume that extern "C" functions with variadic arguments that
6107  // return __unknown_anytype aren't *really* variadic.
6108  if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6109  FDecl->isExternC()) {
6110  for (Expr *A : Args.slice(ArgIx)) {
6111  QualType paramType; // ignored
6112  ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6113  Invalid |= arg.isInvalid();
6114  AllArgs.push_back(arg.get());
6115  }
6116 
6117  // Otherwise do argument promotion, (C99 6.5.2.2p7).
6118  } else {
6119  for (Expr *A : Args.slice(ArgIx)) {
6120  ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6121  Invalid |= Arg.isInvalid();
6122  AllArgs.push_back(Arg.get());
6123  }
6124  }
6125 
6126  // Check for array bounds violations.
6127  for (Expr *A : Args.slice(ArgIx))
6128  CheckArrayAccess(A);
6129  }
6130  return Invalid;
6131 }
6132 
6134  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6135  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6136  TL = DTL.getOriginalLoc();
6137  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6138  S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6139  << ATL.getLocalSourceRange();
6140 }
6141 
6142 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6143 /// array parameter, check that it is non-null, and that if it is formed by
6144 /// array-to-pointer decay, the underlying array is sufficiently large.
6145 ///
6146 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6147 /// array type derivation, then for each call to the function, the value of the
6148 /// corresponding actual argument shall provide access to the first element of
6149 /// an array with at least as many elements as specified by the size expression.
6150 void
6152  ParmVarDecl *Param,
6153  const Expr *ArgExpr) {
6154  // Static array parameters are not supported in C++.
6155  if (!Param || getLangOpts().CPlusPlus)
6156  return;
6157 
6158  QualType OrigTy = Param->getOriginalType();
6159 
6160  const ArrayType *AT = Context.getAsArrayType(OrigTy);
6161  if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6162  return;
6163 
6164  if (ArgExpr->isNullPointerConstant(Context,
6166  Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6167  DiagnoseCalleeStaticArrayParam(*this, Param);
6168  return;
6169  }
6170 
6171  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6172  if (!CAT)
6173  return;
6174 
6175  const ConstantArrayType *ArgCAT =
6176  Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6177  if (!ArgCAT)
6178  return;
6179 
6180  if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6181  ArgCAT->getElementType())) {
6182  if (ArgCAT->getSize().ult(CAT->getSize())) {
6183  Diag(CallLoc, diag::warn_static_array_too_small)
6184  << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6185  << (unsigned)CAT->getZExtSize() << 0;
6186  DiagnoseCalleeStaticArrayParam(*this, Param);
6187  }
6188  return;
6189  }
6190 
6191  std::optional<CharUnits> ArgSize =
6192  getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6193  std::optional<CharUnits> ParmSize =
6194  getASTContext().getTypeSizeInCharsIfKnown(CAT);
6195  if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6196  Diag(CallLoc, diag::warn_static_array_too_small)
6197  << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6198  << (unsigned)ParmSize->getQuantity() << 1;
6199  DiagnoseCalleeStaticArrayParam(*this, Param);
6200  }
6201 }
6202 
6203 /// Given a function expression of unknown-any type, try to rebuild it
6204 /// to have a function type.
6206 
6207 /// Is the given type a placeholder that we need to lower out
6208 /// immediately during argument processing?
6210  // Placeholders are never sugared.
6211  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6212  if (!placeholder) return false;
6213 
6214  switch (placeholder->getKind()) {
6215  // Ignore all the non-placeholder types.
6216 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6217  case BuiltinType::Id:
6218 #include "clang/Basic/OpenCLImageTypes.def"
6219 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6220  case BuiltinType::Sampled##Id:
6221 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
6222 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
6223 #include "clang/Basic/OpenCLImageTypes.def"
6224 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6225  case BuiltinType::Id:
6226 #include "clang/Basic/OpenCLExtensionTypes.def"
6227  // In practice we'll never use this, since all SVE types are sugared
6228  // via TypedefTypes rather than exposed directly as BuiltinTypes.
6229 #define SVE_TYPE(Name, Id, SingletonId) \
6230  case BuiltinType::Id:
6231 #include "clang/Basic/AArch64SVEACLETypes.def"
6232 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6233  case BuiltinType::Id:
6234 #include "clang/Basic/PPCTypes.def"
6235 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6236 #include "clang/Basic/RISCVVTypes.def"
6237 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6238 #include "clang/Basic/WebAssemblyReferenceTypes.def"
6239 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6240 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6241 #include "clang/AST/BuiltinTypes.def"
6242  return false;
6243 
6244  case BuiltinType::UnresolvedTemplate:
6245  // We cannot lower out overload sets; they might validly be resolved
6246  // by the call machinery.
6247  case BuiltinType::Overload:
6248  return false;
6249 
6250  // Unbridged casts in ARC can be handled in some call positions and
6251  // should be left in place.
6252  case BuiltinType::ARCUnbridgedCast:
6253  return false;
6254 
6255  // Pseudo-objects should be converted as soon as possible.
6256  case BuiltinType::PseudoObject:
6257  return true;
6258 
6259  // The debugger mode could theoretically but currently does not try
6260  // to resolve unknown-typed arguments based on known parameter types.
6261  case BuiltinType::UnknownAny:
6262  return true;
6263 
6264  // These are always invalid as call arguments and should be reported.
6265  case BuiltinType::BoundMember:
6266  case BuiltinType::BuiltinFn:
6267  case BuiltinType::IncompleteMatrixIdx:
6268  case BuiltinType::ArraySection:
6269  case BuiltinType::OMPArrayShaping:
6270  case BuiltinType::OMPIterator:
6271  return true;
6272 
6273  }
6274  llvm_unreachable("bad builtin type kind");
6275 }
6276 
6278  // Apply this processing to all the arguments at once instead of
6279  // dying at the first failure.
6280  bool hasInvalid = false;
6281  for (size_t i = 0, e = args.size(); i != e; i++) {
6282  if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6283  ExprResult result = CheckPlaceholderExpr(args[i]);
6284  if (result.isInvalid()) hasInvalid = true;
6285  else args[i] = result.get();
6286  }
6287  }
6288  return hasInvalid;
6289 }
6290 
6291 /// If a builtin function has a pointer argument with no explicit address
6292 /// space, then it should be able to accept a pointer to any address
6293 /// space as input. In order to do this, we need to replace the
6294 /// standard builtin declaration with one that uses the same address space
6295 /// as the call.
6296 ///
6297 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6298 /// it does not contain any pointer arguments without
6299 /// an address space qualifer. Otherwise the rewritten
6300 /// FunctionDecl is returned.
6301 /// TODO: Handle pointer return types.
6303  FunctionDecl *FDecl,
6304  MultiExprArg ArgExprs) {
6305 
6306  QualType DeclType = FDecl->getType();
6307  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6308 
6309  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6310  ArgExprs.size() < FT->getNumParams())
6311  return nullptr;
6312 
6313  bool NeedsNewDecl = false;
6314  unsigned i = 0;
6315  SmallVector<QualType, 8> OverloadParams;
6316 
6317  for (QualType ParamType : FT->param_types()) {
6318 
6319  // Convert array arguments to pointer to simplify type lookup.
6320  ExprResult ArgRes =
6322  if (ArgRes.isInvalid())
6323  return nullptr;
6324  Expr *Arg = ArgRes.get();
6325  QualType ArgType = Arg->getType();
6326  if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6327  !ArgType->isPointerType() ||
6328  !ArgType->getPointeeType().hasAddressSpace() ||
6330  OverloadParams.push_back(ParamType);
6331  continue;
6332  }
6333 
6334  QualType PointeeType = ParamType->getPointeeType();
6335  if (PointeeType.hasAddressSpace())
6336  continue;
6337 
6338  NeedsNewDecl = true;
6339  LangAS AS = ArgType->getPointeeType().getAddressSpace();
6340 
6341  PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6342  OverloadParams.push_back(Context.getPointerType(PointeeType));
6343  }
6344 
6345  if (!NeedsNewDecl)
6346  return nullptr;
6347 
6349  EPI.Variadic = FT->isVariadic();
6350  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6351  OverloadParams, EPI);
6352  DeclContext *Parent = FDecl->getParent();
6353  FunctionDecl *OverloadDecl = FunctionDecl::Create(
6354  Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6355  FDecl->getIdentifier(), OverloadTy,
6356  /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6357  false,
6358  /*hasPrototype=*/true);
6360  FT = cast<FunctionProtoType>(OverloadTy);
6361  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6362  QualType ParamType = FT->getParamType(i);
6363  ParmVarDecl *Parm =
6364  ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6365  SourceLocation(), nullptr, ParamType,
6366  /*TInfo=*/nullptr, SC_None, nullptr);
6367  Parm->setScopeInfo(0, i);
6368  Params.push_back(Parm);
6369  }
6370  OverloadDecl->setParams(Params);
6371  Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6372  return OverloadDecl;
6373 }
6374 
6375 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6376  FunctionDecl *Callee,
6377  MultiExprArg ArgExprs) {
6378  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6379  // similar attributes) really don't like it when functions are called with an
6380  // invalid number of args.
6381  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6382  /*PartialOverloading=*/false) &&
6383  !Callee->isVariadic())
6384  return;
6385  if (Callee->getMinRequiredArguments() > ArgExprs.size())
6386  return;
6387 
6388  if (const EnableIfAttr *Attr =
6389  S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6390  S.Diag(Fn->getBeginLoc(),
6391  isa<CXXMethodDecl>(Callee)
6392  ? diag::err_ovl_no_viable_member_function_in_call
6393  : diag::err_ovl_no_viable_function_in_call)
6394  << Callee << Callee->getSourceRange();
6395  S.Diag(Callee->getLocation(),
6396  diag::note_ovl_candidate_disabled_by_function_cond_attr)
6397  << Attr->getCond()->getSourceRange() << Attr->getMessage();
6398  return;
6399  }
6400 }
6401 
6403  const UnresolvedMemberExpr *const UME, Sema &S) {
6404 
6405  const auto GetFunctionLevelDCIfCXXClass =
6406  [](Sema &S) -> const CXXRecordDecl * {
6407  const DeclContext *const DC = S.getFunctionLevelDeclContext();
6408  if (!DC || !DC->getParent())
6409  return nullptr;
6410 
6411  // If the call to some member function was made from within a member
6412  // function body 'M' return return 'M's parent.
6413  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6414  return MD->getParent()->getCanonicalDecl();
6415  // else the call was made from within a default member initializer of a
6416  // class, so return the class.
6417  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6418  return RD->getCanonicalDecl();
6419  return nullptr;
6420  };
6421  // If our DeclContext is neither a member function nor a class (in the
6422  // case of a lambda in a default member initializer), we can't have an
6423  // enclosing 'this'.
6424 
6425  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6426  if (!CurParentClass)
6427  return false;
6428 
6429  // The naming class for implicit member functions call is the class in which
6430  // name lookup starts.
6431  const CXXRecordDecl *const NamingClass =
6432  UME->getNamingClass()->getCanonicalDecl();
6433  assert(NamingClass && "Must have naming class even for implicit access");
6434 
6435  // If the unresolved member functions were found in a 'naming class' that is
6436  // related (either the same or derived from) to the class that contains the
6437  // member function that itself contained the implicit member access.
6438 
6439  return CurParentClass == NamingClass ||
6440  CurParentClass->isDerivedFrom(NamingClass);
6441 }
6442 
6443 static void
6445  Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6446 
6447  if (!UME)
6448  return;
6449 
6450  LambdaScopeInfo *const CurLSI = S.getCurLambda();
6451  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6452  // already been captured, or if this is an implicit member function call (if
6453  // it isn't, an attempt to capture 'this' should already have been made).
6454  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6455  !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6456  return;
6457 
6458  // Check if the naming class in which the unresolved members were found is
6459  // related (same as or is a base of) to the enclosing class.
6460 
6462  return;
6463 
6464 
6465  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6466  // If the enclosing function is not dependent, then this lambda is
6467  // capture ready, so if we can capture this, do so.
6468  if (!EnclosingFunctionCtx->isDependentContext()) {
6469  // If the current lambda and all enclosing lambdas can capture 'this' -
6470  // then go ahead and capture 'this' (since our unresolved overload set
6471  // contains at least one non-static member function).
6472  if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6473  S.CheckCXXThisCapture(CallLoc);
6474  } else if (S.CurContext->isDependentContext()) {
6475  // ... since this is an implicit member reference, that might potentially
6476  // involve a 'this' capture, mark 'this' for potential capture in
6477  // enclosing lambdas.
6478  if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6479  CurLSI->addPotentialThisCapture(CallLoc);
6480  }
6481 }
6482 
6483 // Once a call is fully resolved, warn for unqualified calls to specific
6484 // C++ standard functions, like move and forward.
6486  const CallExpr *Call) {
6487  // We are only checking unary move and forward so exit early here.
6488  if (Call->getNumArgs() != 1)
6489  return;
6490 
6491  const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6492  if (!E || isa<UnresolvedLookupExpr>(E))
6493  return;
6494  const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6495  if (!DRE || !DRE->getLocation().isValid())
6496  return;
6497 
6498  if (DRE->getQualifier())
6499  return;
6500 
6501  const FunctionDecl *FD = Call->getDirectCallee();
6502  if (!FD)
6503  return;
6504 
6505  // Only warn for some functions deemed more frequent or problematic.
6506  unsigned BuiltinID = FD->getBuiltinID();
6507  if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6508  return;
6509 
6510  S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6511  << FD->getQualifiedNameAsString()
6512  << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6513 }
6514 
6516  MultiExprArg ArgExprs, SourceLocation RParenLoc,
6517  Expr *ExecConfig) {
6518  ExprResult Call =
6519  BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6520  /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6521  if (Call.isInvalid())
6522  return Call;
6523 
6524  // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6525  // language modes.
6526  if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6527  ULE && ULE->hasExplicitTemplateArgs() &&
6528  ULE->decls_begin() == ULE->decls_end()) {
6529  Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6530  ? diag::warn_cxx17_compat_adl_only_template_id
6531  : diag::ext_adl_only_template_id)
6532  << ULE->getName();
6533  }
6534 
6535  if (LangOpts.OpenMP)
6536  Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6537  ExecConfig);
6538  if (LangOpts.CPlusPlus) {
6539  if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6541  }
6542  return Call;
6543 }
6544 
6545 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6546 /// This provides the location of the left/right parens and a list of comma
6547 /// locations.
6549  MultiExprArg ArgExprs, SourceLocation RParenLoc,
6550  Expr *ExecConfig, bool IsExecConfig,
6551  bool AllowRecovery) {
6552  // Since this might be a postfix expression, get rid of ParenListExprs.
6553  ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6554  if (Result.isInvalid()) return ExprError();
6555  Fn = Result.get();
6556 
6557  if (CheckArgsForPlaceholders(ArgExprs))
6558  return ExprError();
6559 
6560  if (getLangOpts().CPlusPlus) {
6561  // If this is a pseudo-destructor expression, build the call immediately.
6562  if (isa<CXXPseudoDestructorExpr>(Fn)) {
6563  if (!ArgExprs.empty()) {
6564  // Pseudo-destructor calls should not have any arguments.
6565  Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6567  SourceRange(ArgExprs.front()->getBeginLoc(),
6568  ArgExprs.back()->getEndLoc()));
6569  }
6570 
6571  return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6572  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6573  }
6574  if (Fn->getType() == Context.PseudoObjectTy) {
6575  ExprResult result = CheckPlaceholderExpr(Fn);
6576  if (result.isInvalid()) return ExprError();
6577  Fn = result.get();
6578  }
6579 
6580  // Determine whether this is a dependent call inside a C++ template,
6581  // in which case we won't do any semantic analysis now.
6582  if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6583  if (ExecConfig) {
6584  return CUDAKernelCallExpr::Create(Context, Fn,
6585  cast<CallExpr>(ExecConfig), ArgExprs,
6586  Context.DependentTy, VK_PRValue,
6587  RParenLoc, CurFPFeatureOverrides());
6588  } else {
6589 
6591  *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6592  Fn->getBeginLoc());
6593 
6594  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6595  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6596  }
6597  }
6598 
6599  // Determine whether this is a call to an object (C++ [over.call.object]).
6600  if (Fn->getType()->isRecordType())
6601  return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6602  RParenLoc);
6603 
6604  if (Fn->getType() == Context.UnknownAnyTy) {
6605  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6606  if (result.isInvalid()) return ExprError();
6607  Fn = result.get();
6608  }
6609 
6610  if (Fn->getType() == Context.BoundMemberTy) {
6611  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6612  RParenLoc, ExecConfig, IsExecConfig,
6613  AllowRecovery);
6614  }
6615  }
6616 
6617  // Check for overloaded calls. This can happen even in C due to extensions.
6618  if (Fn->getType() == Context.OverloadTy) {
6620 
6621  // We aren't supposed to apply this logic if there's an '&' involved.
6622  if (!find.HasFormOfMemberPointer) {
6623  if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6624  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6625  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6626  OverloadExpr *ovl = find.Expression;
6627  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6628  return BuildOverloadedCallExpr(
6629  Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6630  /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6631  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6632  RParenLoc, ExecConfig, IsExecConfig,
6633  AllowRecovery);
6634  }
6635  }
6636 
6637  // If we're directly calling a function, get the appropriate declaration.
6638  if (Fn->getType() == Context.UnknownAnyTy) {
6639  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6640  if (result.isInvalid()) return ExprError();
6641  Fn = result.get();
6642  }
6643 
6644  Expr *NakedFn = Fn->IgnoreParens();
6645 
6646  bool CallingNDeclIndirectly = false;
6647  NamedDecl *NDecl = nullptr;
6648  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6649  if (UnOp->getOpcode() == UO_AddrOf) {
6650  CallingNDeclIndirectly = true;
6651  NakedFn = UnOp->getSubExpr()->IgnoreParens();
6652  }
6653  }
6654 
6655  if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6656  NDecl = DRE->getDecl();
6657 
6658  FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6659  if (FDecl && FDecl->getBuiltinID()) {
6660  // Rewrite the function decl for this builtin by replacing parameters
6661  // with no explicit address space with the address space of the arguments
6662  // in ArgExprs.
6663  if ((FDecl =
6664  rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6665  NDecl = FDecl;
6666  Fn = DeclRefExpr::Create(
6667  Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6668  SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6669  nullptr, DRE->isNonOdrUse());
6670  }
6671  }
6672  } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6673  NDecl = ME->getMemberDecl();
6674 
6675  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6676  if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6677  FD, /*Complain=*/true, Fn->getBeginLoc()))
6678  return ExprError();
6679 
6680  checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6681 
6682  // If this expression is a call to a builtin function in HIP device
6683  // compilation, allow a pointer-type argument to default address space to be
6684  // passed as a pointer-type parameter to a non-default address space.
6685  // If Arg is declared in the default address space and Param is declared
6686  // in a non-default address space, perform an implicit address space cast to
6687  // the parameter type.
6688  if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6689  FD->getBuiltinID()) {
6690  for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6691  ParmVarDecl *Param = FD->getParamDecl(Idx);
6692  if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6693  !ArgExprs[Idx]->getType()->isPointerType())
6694  continue;
6695 
6696  auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6697  auto ArgTy = ArgExprs[Idx]->getType();
6698  auto ArgPtTy = ArgTy->getPointeeType();
6699  auto ArgAS = ArgPtTy.getAddressSpace();
6700 
6701  // Add address space cast if target address spaces are different
6702  bool NeedImplicitASC =
6703  ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6704  ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6705  // or from specific AS which has target AS matching that of Param.
6706  getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6707  if (!NeedImplicitASC)
6708  continue;
6709 
6710  // First, ensure that the Arg is an RValue.
6711  if (ArgExprs[Idx]->isGLValue()) {
6712  ArgExprs[Idx] = ImplicitCastExpr::Create(
6713  Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6714  nullptr, VK_PRValue, FPOptionsOverride());
6715  }
6716 
6717  // Construct a new arg type with address space of Param
6718  Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6719  ArgPtQuals.setAddressSpace(ParamAS);
6720  auto NewArgPtTy =
6721  Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6722  auto NewArgTy =
6723  Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6724  ArgTy.getQualifiers());
6725 
6726  // Finally perform an implicit address space cast
6727  ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6728  CK_AddressSpaceConversion)
6729  .get();
6730  }
6731  }
6732  }
6733 
6734  if (Context.isDependenceAllowed() &&
6735  (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6736  assert(!getLangOpts().CPlusPlus);
6737  assert((Fn->containsErrors() ||
6738  llvm::any_of(ArgExprs,
6739  [](clang::Expr *E) { return E->containsErrors(); })) &&
6740  "should only occur in error-recovery path.");
6741  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6742  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6743  }
6744  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6745  ExecConfig, IsExecConfig);
6746 }
6747 
6748 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6749 // with the specified CallArgs
6751  MultiExprArg CallArgs) {
6752  StringRef Name = Context.BuiltinInfo.getName(Id);
6753  LookupResult R(*this, &Context.Idents.get(Name), Loc,
6755  LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6756 
6757  auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6758  assert(BuiltInDecl && "failed to find builtin declaration");
6759 
6760  ExprResult DeclRef =
6761  BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6762  assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6763 
6764  ExprResult Call =
6765  BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6766 
6767  assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6768  return Call.get();
6769 }
6770 
6771 /// Parse a __builtin_astype expression.
6772 ///
6773 /// __builtin_astype( value, dst type )
6774 ///
6776  SourceLocation BuiltinLoc,
6777  SourceLocation RParenLoc) {
6778  QualType DstTy = GetTypeFromParser(ParsedDestTy);
6779  return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6780 }
6781 
6782 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6784  SourceLocation BuiltinLoc,
6785  SourceLocation RParenLoc) {
6788  QualType SrcTy = E->getType();
6789  if (!SrcTy->isDependentType() &&
6790  Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6791  return ExprError(
6792  Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6793  << DestTy << SrcTy << E->getSourceRange());
6794  return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6795 }
6796 
6797 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6798 /// provided arguments.
6799 ///
6800 /// __builtin_convertvector( value, dst type )
6801 ///
6803  SourceLocation BuiltinLoc,
6804  SourceLocation RParenLoc) {
6805  TypeSourceInfo *TInfo;
6806  GetTypeFromParser(ParsedDestTy, &TInfo);
6807  return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6808 }
6809 
6810 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6811 /// i.e. an expression not of \p OverloadTy. The expression should
6812 /// unary-convert to an expression of function-pointer or
6813 /// block-pointer type.
6814 ///
6815 /// \param NDecl the declaration being called, if available
6817  SourceLocation LParenLoc,
6818  ArrayRef<Expr *> Args,
6819  SourceLocation RParenLoc, Expr *Config,
6820  bool IsExecConfig, ADLCallKind UsesADL) {
6821  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6822  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6823 
6824  // Functions with 'interrupt' attribute cannot be called directly.
6825  if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6826  Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6827  return ExprError();
6828  }
6829 
6830  // Interrupt handlers don't save off the VFP regs automatically on ARM,
6831  // so there's some risk when calling out to non-interrupt handler functions
6832  // that the callee might not preserve them. This is easy to diagnose here,
6833  // but can be very challenging to debug.
6834  // Likewise, X86 interrupt handlers may only call routines with attribute
6835  // no_caller_saved_registers since there is no efficient way to
6836  // save and restore the non-GPR state.
6837  if (auto *Caller = getCurFunctionDecl()) {
6838  if (Caller->hasAttr<ARMInterruptAttr>()) {
6839  bool VFP = Context.getTargetInfo().hasFeature("vfp");
6840  if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6841  Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6842  if (FDecl)
6843  Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6844  }
6845  }
6846  if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6847  Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6848  const TargetInfo &TI = Context.getTargetInfo();
6849  bool HasNonGPRRegisters =
6850  TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6851  if (HasNonGPRRegisters &&
6852  (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6853  Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6854  << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6855  if (FDecl)
6856  Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6857  }
6858  }
6859  }
6860 
6861  // Promote the function operand.
6862  // We special-case function promotion here because we only allow promoting
6863  // builtin functions to function pointers in the callee of a call.
6864  ExprResult Result;
6865  QualType ResultTy;
6866  if (BuiltinID &&
6867  Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6868  // Extract the return type from the (builtin) function pointer type.
6869  // FIXME Several builtins still have setType in
6870  // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6871  // Builtins.td to ensure they are correct before removing setType calls.
6872  QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6873  Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6874  ResultTy = FDecl->getCallResultType();
6875  } else {
6876  Result = CallExprUnaryConversions(Fn);
6877  ResultTy = Context.BoolTy;
6878  }
6879  if (Result.isInvalid())
6880  return ExprError();
6881  Fn = Result.get();
6882 
6883  // Check for a valid function type, but only if it is not a builtin which
6884  // requires custom type checking. These will be handled by
6885  // CheckBuiltinFunctionCall below just after creation of the call expression.
6886  const FunctionType *FuncT = nullptr;
6887  if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6888  retry:
6889  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6890  // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6891  // have type pointer to function".
6892  FuncT = PT->getPointeeType()->getAs<FunctionType>();
6893  if (!FuncT)
6894  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6895  << Fn->getType() << Fn->getSourceRange());
6896  } else if (const BlockPointerType *BPT =
6897  Fn->getType()->getAs<BlockPointerType>()) {
6898  FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6899  } else {
6900  // Handle calls to expressions of unknown-any type.
6901  if (Fn->getType() == Context.UnknownAnyTy) {
6902  ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6903  if (rewrite.isInvalid())
6904  return ExprError();
6905  Fn = rewrite.get();
6906  goto retry;
6907  }
6908 
6909  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6910  << Fn->getType() << Fn->getSourceRange());
6911  }
6912  }
6913 
6914  // Get the number of parameters in the function prototype, if any.
6915  // We will allocate space for max(Args.size(), NumParams) arguments
6916  // in the call expression.
6917  const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6918  unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6919 
6920  CallExpr *TheCall;
6921  if (Config) {
6922  assert(UsesADL == ADLCallKind::NotADL &&
6923  "CUDAKernelCallExpr should not use ADL");
6924  TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6925  Args, ResultTy, VK_PRValue, RParenLoc,
6926  CurFPFeatureOverrides(), NumParams);
6927  } else {
6928  TheCall =
6929  CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6930  CurFPFeatureOverrides(), NumParams, UsesADL);
6931  }
6932 
6933  if (!Context.isDependenceAllowed()) {
6934  // Forget about the nulled arguments since typo correction
6935  // do not handle them well.
6936  TheCall->shrinkNumArgs(Args.size());
6937  // C cannot always handle TypoExpr nodes in builtin calls and direct
6938  // function calls as their argument checking don't necessarily handle
6939  // dependent types properly, so make sure any TypoExprs have been
6940  // dealt with.
6941  ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6942  if (!Result.isUsable()) return ExprError();
6943  CallExpr *TheOldCall = TheCall;
6944  TheCall = dyn_cast<CallExpr>(Result.get());
6945  bool CorrectedTypos = TheCall != TheOldCall;
6946  if (!TheCall) return Result;
6947  Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6948 
6949  // A new call expression node was created if some typos were corrected.
6950  // However it may not have been constructed with enough storage. In this
6951  // case, rebuild the node with enough storage. The waste of space is
6952  // immaterial since this only happens when some typos were corrected.
6953  if (CorrectedTypos && Args.size() < NumParams) {
6954  if (Config)
6955  TheCall = CUDAKernelCallExpr::Create(
6956  Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6957  RParenLoc, CurFPFeatureOverrides(), NumParams);
6958  else
6959  TheCall =
6960  CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6961  CurFPFeatureOverrides(), NumParams, UsesADL);
6962  }
6963  // We can now handle the nulled arguments for the default arguments.
6964  TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6965  }
6966 
6967  // Bail out early if calling a builtin with custom type checking.
6968  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6969  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6970 
6971  if (getLangOpts().CUDA) {
6972  if (Config) {
6973  // CUDA: Kernel calls must be to global functions
6974  if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6975  return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6976  << FDecl << Fn->getSourceRange());
6977 
6978  // CUDA: Kernel function must have 'void' return type
6979  if (!FuncT->getReturnType()->isVoidType() &&
6980  !FuncT->getReturnType()->getAs<AutoType>() &&
6982  return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6983  << Fn->getType() << Fn->getSourceRange());
6984  } else {
6985  // CUDA: Calls to global functions must be configured
6986  if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6987  return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6988  << FDecl << Fn->getSourceRange());
6989  }
6990  }
6991 
6992  // Check for a valid return type
6993  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6994  FDecl))
6995  return ExprError();
6996 
6997  // We know the result type of the call, set it.
6998  TheCall->setType(FuncT->getCallResultType(Context));
7000 
7001  // WebAssembly tables can't be used as arguments.
7002  if (Context.getTargetInfo().getTriple().isWasm()) {
7003  for (const Expr *Arg : Args) {
7004  if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7005  return ExprError(Diag(Arg->getExprLoc(),
7006  diag::err_wasm_table_as_function_parameter));
7007  }
7008  }
7009  }
7010 
7011  if (Proto) {
7012  if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7013  IsExecConfig))
7014  return ExprError();
7015  } else {
7016  assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7017 
7018  if (FDecl) {
7019  // Check if we have too few/too many template arguments, based
7020  // on our knowledge of the function definition.
7021  const FunctionDecl *Def = nullptr;
7022  if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7023  Proto = Def->getType()->getAs<FunctionProtoType>();
7024  if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7025  Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7026  << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7027  }
7028 
7029  // If the function we're calling isn't a function prototype, but we have
7030  // a function prototype from a prior declaratiom, use that prototype.
7031  if (!FDecl->hasPrototype())
7032  Proto = FDecl->getType()->getAs<FunctionProtoType>();
7033  }
7034 
7035  // If we still haven't found a prototype to use but there are arguments to
7036  // the call, diagnose this as calling a function without a prototype.
7037  // However, if we found a function declaration, check to see if
7038  // -Wdeprecated-non-prototype was disabled where the function was declared.
7039  // If so, we will silence the diagnostic here on the assumption that this
7040  // interface is intentional and the user knows what they're doing. We will
7041  // also silence the diagnostic if there is a function declaration but it
7042  // was implicitly defined (the user already gets diagnostics about the
7043  // creation of the implicit function declaration, so the additional warning
7044  // is not helpful).
7045  if (!Proto && !Args.empty() &&
7046  (!FDecl || (!FDecl->isImplicit() &&
7047  !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7048  FDecl->getLocation()))))
7049  Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7050  << (FDecl != nullptr) << FDecl;
7051 
7052  // Promote the arguments (C99 6.5.2.2p6).
7053  for (unsigned i = 0, e = Args.size(); i != e; i++) {
7054  Expr *Arg = Args[i];
7055 
7056  if (Proto && i < Proto->getNumParams()) {
7058  Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7059  ExprResult ArgE =
7060  PerformCopyInitialization(Entity, SourceLocation(), Arg);
7061  if (ArgE.isInvalid())
7062  return true;
7063 
7064  Arg = ArgE.getAs<Expr>();
7065 
7066  } else {
7067  ExprResult ArgE = DefaultArgumentPromotion(Arg);
7068 
7069  if (ArgE.isInvalid())
7070  return true;
7071 
7072  Arg = ArgE.getAs<Expr>();
7073  }
7074 
7075  if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7076  diag::err_call_incomplete_argument, Arg))
7077  return ExprError();
7078 
7079  TheCall->setArg(i, Arg);
7080  }
7081  TheCall->computeDependence();
7082  }
7083 
7084  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7085  if (!isa<RequiresExprBodyDecl>(CurContext) &&
7086  Method->isImplicitObjectMemberFunction())
7087  return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7088  << Fn->getSourceRange() << 0);
7089 
7090  // Check for sentinels
7091  if (NDecl)
7092  DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7093 
7094  // Warn for unions passing across security boundary (CMSE).
7095  if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7096  for (unsigned i = 0, e = Args.size(); i != e; i++) {
7097  if (const auto *RT =
7098  dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7099  if (RT->getDecl()->isOrContainsUnion())
7100  Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7101  << 0 << i;
7102  }
7103  }
7104  }
7105 
7106  // Do special checking on direct calls to functions.
7107  if (FDecl) {
7108  if (CheckFunctionCall(FDecl, TheCall, Proto))
7109  return ExprError();
7110 
7111  checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7112 
7113  if (BuiltinID)
7114  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7115  } else if (NDecl) {
7116  if (CheckPointerCall(NDecl, TheCall, Proto))
7117  return ExprError();
7118  } else {
7119  if (CheckOtherCall(TheCall, Proto))
7120  return ExprError();
7121  }
7122 
7123  return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7124 }
7125 
7126 ExprResult
7128  SourceLocation RParenLoc, Expr *InitExpr) {
7129  assert(Ty && "ActOnCompoundLiteral(): missing type");
7130  assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7131 
7132  TypeSourceInfo *TInfo;
7133  QualType literalType = GetTypeFromParser(Ty, &TInfo);
7134  if (!TInfo)
7135  TInfo = Context.getTrivialTypeSourceInfo(literalType);
7136 
7137  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7138 }
7139 
7140 ExprResult
7142  SourceLocation RParenLoc, Expr *LiteralExpr) {
7143  QualType literalType = TInfo->getType();
7144 
7145  if (literalType->isArrayType()) {
7146  if (RequireCompleteSizedType(
7147  LParenLoc, Context.getBaseElementType(literalType),
7148  diag::err_array_incomplete_or_sizeless_type,
7149  SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7150  return ExprError();
7151  if (literalType->isVariableArrayType()) {
7152  // C23 6.7.10p4: An entity of variable length array type shall not be
7153  // initialized except by an empty initializer.
7154  //
7155  // The C extension warnings are issued from ParseBraceInitializer() and
7156  // do not need to be issued here. However, we continue to issue an error
7157  // in the case there are initializers or we are compiling C++. We allow
7158  // use of VLAs in C++, but it's not clear we want to allow {} to zero
7159  // init a VLA in C++ in all cases (such as with non-trivial constructors).
7160  // FIXME: should we allow this construct in C++ when it makes sense to do
7161  // so?
7162  //
7163  // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7164  // shall specify an object type or an array of unknown size, but not a
7165  // variable length array type. This seems odd, as it allows 'int a[size] =
7166  // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7167  // says, this is what's implemented here for C (except for the extension
7168  // that permits constant foldable size arrays)
7169 
7170  auto diagID = LangOpts.CPlusPlus
7171  ? diag::err_variable_object_no_init
7172  : diag::err_compound_literal_with_vla_type;
7173  if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7174  diagID))
7175  return ExprError();
7176  }
7177  } else if (!literalType->isDependentType() &&
7178  RequireCompleteType(LParenLoc, literalType,
7179  diag::err_typecheck_decl_incomplete_type,
7180  SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7181  return ExprError();
7182 
7183  InitializedEntity Entity
7187  SourceRange(LParenLoc, RParenLoc),
7188  /*InitList=*/true);
7189  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7190  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7191  &literalType);
7192  if (Result.isInvalid())
7193  return ExprError();
7194  LiteralExpr = Result.get();
7195 
7196  bool isFileScope = !CurContext->isFunctionOrMethod();
7197 
7198  // In C, compound literals are l-values for some reason.
7199  // For GCC compatibility, in C++, file-scope array compound literals with
7200  // constant initializers are also l-values, and compound literals are
7201  // otherwise prvalues.
7202  //
7203  // (GCC also treats C++ list-initialized file-scope array prvalues with
7204  // constant initializers as l-values, but that's non-conforming, so we don't
7205  // follow it there.)
7206  //
7207  // FIXME: It would be better to handle the lvalue cases as materializing and
7208  // lifetime-extending a temporary object, but our materialized temporaries
7209  // representation only supports lifetime extension from a variable, not "out
7210  // of thin air".
7211  // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7212  // is bound to the result of applying array-to-pointer decay to the compound
7213  // literal.
7214  // FIXME: GCC supports compound literals of reference type, which should
7215  // obviously have a value kind derived from the kind of reference involved.
7216  ExprValueKind VK =
7217  (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7218  ? VK_PRValue
7219  : VK_LValue;
7220 
7221  if (isFileScope)
7222  if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7223  for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7224  Expr *Init = ILE->getInit(i);
7225  ILE->setInit(i, ConstantExpr::Create(Context, Init));
7226  }
7227 
7228  auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7229  VK, LiteralExpr, isFileScope);
7230  if (isFileScope) {
7231  if (!LiteralExpr->isTypeDependent() &&
7232  !LiteralExpr->isValueDependent() &&
7233  !literalType->isDependentType()) // C99 6.5.2.5p3
7234  if (CheckForConstantInitializer(LiteralExpr))
7235  return ExprError();
7236  } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7237  literalType.getAddressSpace() != LangAS::Default) {
7238  // Embedded-C extensions to C99 6.5.2.5:
7239  // "If the compound literal occurs inside the body of a function, the
7240  // type name shall not be qualified by an address-space qualifier."
7241  Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7242  << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7243  return ExprError();
7244  }
7245 
7246  if (!isFileScope && !getLangOpts().CPlusPlus) {
7247  // Compound literals that have automatic storage duration are destroyed at
7248  // the end of the scope in C; in C++, they're just temporaries.
7249 
7250  // Emit diagnostics if it is or contains a C union type that is non-trivial
7251  // to destruct.
7253  checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7254  NTCUC_CompoundLiteral, NTCUK_Destruct);
7255 
7256  // Diagnose jumps that enter or exit the lifetime of the compound literal.
7257  if (literalType.isDestructedType()) {
7258  Cleanup.setExprNeedsCleanups(true);
7259  ExprCleanupObjects.push_back(E);
7260  getCurFunction()->setHasBranchProtectedScope();
7261  }
7262  }
7263 
7266  checkNonTrivialCUnionInInitializer(E->getInitializer(),
7267  E->getInitializer()->getExprLoc());
7268 
7269  return MaybeBindToTemporary(E);
7270 }
7271 
7272 ExprResult
7274  SourceLocation RBraceLoc) {
7275  // Only produce each kind of designated initialization diagnostic once.
7276  SourceLocation FirstDesignator;
7277  bool DiagnosedArrayDesignator = false;
7278  bool DiagnosedNestedDesignator = false;
7279  bool DiagnosedMixedDesignator = false;
7280 
7281  // Check that any designated initializers are syntactically valid in the
7282  // current language mode.
7283  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7284  if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7285  if (FirstDesignator.isInvalid())
7286  FirstDesignator = DIE->getBeginLoc();
7287 
7288  if (!getLangOpts().CPlusPlus)
7289  break;
7290 
7291  if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7292  DiagnosedNestedDesignator = true;
7293  Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7294  << DIE->getDesignatorsSourceRange();
7295  }
7296 
7297  for (auto &Desig : DIE->designators()) {
7298  if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7299  DiagnosedArrayDesignator = true;
7300  Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7301  << Desig.getSourceRange();
7302  }
7303  }
7304 
7305  if (!DiagnosedMixedDesignator &&
7306  !isa<DesignatedInitExpr>(InitArgList[0])) {
7307  DiagnosedMixedDesignator = true;
7308  Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7309  << DIE->getSourceRange();
7310  Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7311  << InitArgList[0]->getSourceRange();
7312  }
7313  } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7314  isa<DesignatedInitExpr>(InitArgList[0])) {
7315  DiagnosedMixedDesignator = true;
7316  auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7317  Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7318  << DIE->getSourceRange();
7319  Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7320  << InitArgList[I]->getSourceRange();
7321  }
7322  }
7323 
7324  if (FirstDesignator.isValid()) {
7325  // Only diagnose designated initiaization as a C++20 extension if we didn't
7326  // already diagnose use of (non-C++20) C99 designator syntax.
7327  if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7328  !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7329  Diag(FirstDesignator, getLangOpts().CPlusPlus20
7330  ? diag::warn_cxx17_compat_designated_init
7331  : diag::ext_cxx_designated_init);
7332  } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7333  Diag(FirstDesignator, diag::ext_designated_init);
7334  }
7335  }
7336 
7337  return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7338 }
7339 
7340 ExprResult
7342  SourceLocation RBraceLoc) {
7343  // Semantic analysis for initializers is done by ActOnDeclarator() and
7344  // CheckInitializer() - it requires knowledge of the object being initialized.
7345 
7346  // Immediately handle non-overload placeholders. Overloads can be
7347  // resolved contextually, but everything else here can't.
7348  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7349  if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7350  ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7351 
7352  // Ignore failures; dropping the entire initializer list because
7353  // of one failure would be terrible for indexing/etc.
7354  if (result.isInvalid()) continue;
7355 
7356  InitArgList[I] = result.get();
7357  }
7358  }
7359 
7360  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7361  RBraceLoc);
7362  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7363  return E;
7364 }
7365 
7366 /// Do an explicit extend of the given block pointer if we're in ARC.
7368  assert(E.get()->getType()->isBlockPointerType());
7369  assert(E.get()->isPRValue());
7370 
7371  // Only do this in an r-value context.
7372  if (!getLangOpts().ObjCAutoRefCount) return;
7373 
7375  Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7376  /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7377  Cleanup.setExprNeedsCleanups(true);
7378 }
7379 
7380 /// Prepares for a scalar cast, performing all the necessary stages
7381 /// except the final cast and returning the kind required.
7383  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7384  // Also, callers should have filtered out the invalid cases with
7385  // pointers. Everything else should be possible.
7386 
7387  QualType SrcTy = Src.get()->getType();
7388  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7389  return CK_NoOp;
7390 
7391  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7393  llvm_unreachable("member pointer type in C");
7394 
7395  case Type::STK_CPointer:
7398  switch (DestTy->getScalarTypeKind()) {
7399  case Type::STK_CPointer: {
7400  LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7401  LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7402  if (SrcAS != DestAS)
7403  return CK_AddressSpaceConversion;
7404  if (Context.hasCvrSimilarType(SrcTy, DestTy))
7405  return CK_NoOp;
7406  return CK_BitCast;
7407  }
7409  return (SrcKind == Type::STK_BlockPointer
7410  ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7412  if (SrcKind == Type::STK_ObjCObjectPointer)
7413  return CK_BitCast;
7414  if (SrcKind == Type::STK_CPointer)
7415  return CK_CPointerToObjCPointerCast;
7416  maybeExtendBlockObject(Src);
7417  return CK_BlockPointerToObjCPointerCast;
7418  case Type::STK_Bool:
7419  return CK_PointerToBoolean;
7420  case Type::STK_Integral:
7421  return CK_PointerToIntegral;
7422  case Type::STK_Floating:
7426  case Type::STK_FixedPoint:
7427  llvm_unreachable("illegal cast from pointer");
7428  }
7429  llvm_unreachable("Should have returned before this");
7430 
7431  case Type::STK_FixedPoint:
7432  switch (DestTy->getScalarTypeKind()) {
7433  case Type::STK_FixedPoint:
7434  return CK_FixedPointCast;
7435  case Type::STK_Bool:
7436  return CK_FixedPointToBoolean;
7437  case Type::STK_Integral:
7438  return CK_FixedPointToIntegral;
7439  case Type::STK_Floating:
7440  return CK_FixedPointToFloating;
7443  Diag(Src.get()->getExprLoc(),
7444  diag::err_unimplemented_conversion_with_fixed_point_type)
7445  << DestTy;
7446  return CK_IntegralCast;
7447  case Type::STK_CPointer:
7451  llvm_unreachable("illegal cast to pointer type");
7452  }
7453  llvm_unreachable("Should have returned before this");
7454 
7455  case Type::STK_Bool: // casting from bool is like casting from an integer
7456  case Type::STK_Integral:
7457  switch (DestTy->getScalarTypeKind()) {
7458  case Type::STK_CPointer:
7461  if (Src.get()->isNullPointerConstant(Context,
7463  return CK_NullToPointer;
7464  return CK_IntegralToPointer;
7465  case Type::STK_Bool:
7466  return CK_IntegralToBoolean;
7467  case Type::STK_Integral:
7468  return CK_IntegralCast;
7469  case Type::STK_Floating:
7470  return CK_IntegralToFloating;
7472  Src = ImpCastExprToType(Src.get(),
7473  DestTy->castAs<ComplexType>()->getElementType(),
7474  CK_IntegralCast);
7475  return CK_IntegralRealToComplex;
7477  Src = ImpCastExprToType(Src.get(),
7478  DestTy->castAs<ComplexType>()->getElementType(),
7479  CK_IntegralToFloating);
7480  return CK_FloatingRealToComplex;
7482  llvm_unreachable("member pointer type in C");
7483  case Type::STK_FixedPoint:
7484  return CK_IntegralToFixedPoint;
7485  }
7486  llvm_unreachable("Should have returned before this");
7487 
7488  case Type::STK_Floating:
7489  switch (DestTy->getScalarTypeKind()) {
7490  case Type::STK_Floating:
7491  return CK_FloatingCast;
7492  case Type::STK_Bool:
7493  return CK_FloatingToBoolean;
7494  case Type::STK_Integral:
7495  return CK_FloatingToIntegral;
7497  Src = ImpCastExprToType(Src.get(),
7498  DestTy->castAs<ComplexType>()->getElementType(),
7499  CK_FloatingCast);
7500  return CK_FloatingRealToComplex;
7502  Src = ImpCastExprToType(Src.get(),
7503  DestTy->castAs<ComplexType>()->getElementType(),
7504  CK_FloatingToIntegral);
7505  return CK_IntegralRealToComplex;
7506  case Type::STK_CPointer:
7509  llvm_unreachable("valid float->pointer cast?");
7511  llvm_unreachable("member pointer type in C");
7512  case Type::STK_FixedPoint:
7513  return CK_FloatingToFixedPoint;
7514  }
7515  llvm_unreachable("Should have returned before this");
7516 
7518  switch (DestTy->getScalarTypeKind()) {
7520  return CK_FloatingComplexCast;
7522  return CK_FloatingComplexToIntegralComplex;
7523  case Type::STK_Floating: {
7524  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7525  if (Context.hasSameType(ET, DestTy))
7526  return CK_FloatingComplexToReal;
7527  Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7528  return CK_FloatingCast;
7529  }
7530  case Type::STK_Bool:
7531  return CK_FloatingComplexToBoolean;
7532  case Type::STK_Integral:
7533  Src = ImpCastExprToType(Src.get(),
7534  SrcTy->castAs<ComplexType>()->getElementType(),
7535  CK_FloatingComplexToReal);
7536  return CK_FloatingToIntegral;
7537  case Type::STK_CPointer:
7540  llvm_unreachable("valid complex float->pointer cast?");
7542  llvm_unreachable("member pointer type in C");
7543  case Type::STK_FixedPoint:
7544  Diag(Src.get()->getExprLoc(),
7545  diag::err_unimplemented_conversion_with_fixed_point_type)
7546  << SrcTy;
7547  return CK_IntegralCast;
7548  }
7549  llvm_unreachable("Should have returned before this");
7550 
7552  switch (DestTy->getScalarTypeKind()) {
7554  return CK_IntegralComplexToFloatingComplex;
7556  return CK_IntegralComplexCast;
7557  case Type::STK_Integral: {
7558  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7559  if (Context.hasSameType(ET, DestTy))
7560  return CK_IntegralComplexToReal;
7561  Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7562  return CK_IntegralCast;
7563  }
7564  case Type::STK_Bool:
7565  return CK_IntegralComplexToBoolean;
7566  case Type::STK_Floating:
7567  Src = ImpCastExprToType(Src.get(),
7568  SrcTy->castAs<ComplexType>()->getElementType(),
7569  CK_IntegralComplexToReal);
7570  return CK_IntegralToFloating;
7571  case Type::STK_CPointer:
7574  llvm_unreachable("valid complex int->pointer cast?");
7576  llvm_unreachable("member pointer type in C");
7577  case Type::STK_FixedPoint:
7578  Diag(Src.get()->getExprLoc(),
7579  diag::err_unimplemented_conversion_with_fixed_point_type)
7580  << SrcTy;
7581  return CK_IntegralCast;
7582  }
7583  llvm_unreachable("Should have returned before this");
7584  }
7585 
7586  llvm_unreachable("Unhandled scalar cast");
7587 }
7588 
7590  QualType &eltType) {
7591  // Vectors are simple.
7592  if (const VectorType *vecType = type->getAs<VectorType>()) {
7593  len = vecType->getNumElements();
7594  eltType = vecType->getElementType();
7595  assert(eltType->isScalarType());
7596  return true;
7597  }
7598 
7599  // We allow lax conversion to and from non-vector types, but only if
7600  // they're real types (i.e. non-complex, non-pointer scalar types).
7601  if (!type->isRealType()) return false;
7602 
7603  len = 1;
7604  eltType = type;
7605  return true;
7606 }
7607 
7608 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7609 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7610 /// allowed?
7611 ///
7612 /// This will also return false if the two given types do not make sense from
7613 /// the perspective of SVE bitcasts.
7615  assert(srcTy->isVectorType() || destTy->isVectorType());
7616 
7617  auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7618  if (!FirstType->isSVESizelessBuiltinType())
7619  return false;
7620 
7621  const auto *VecTy = SecondType->getAs<VectorType>();
7622  return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7623  };
7624 
7625  return ValidScalableConversion(srcTy, destTy) ||
7626  ValidScalableConversion(destTy, srcTy);
7627 }
7628 
7629 /// Are the two types matrix types and do they have the same dimensions i.e.
7630 /// do they have the same number of rows and the same number of columns?
7632  if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7633  return false;
7634 
7635  const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7636  const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7637 
7638  return matSrcType->getNumRows() == matDestType->getNumRows() &&
7639  matSrcType->getNumColumns() == matDestType->getNumColumns();
7640 }
7641 
7643  assert(DestTy->isVectorType() || SrcTy->isVectorType());
7644 
7645  uint64_t SrcLen, DestLen;
7646  QualType SrcEltTy, DestEltTy;
7647  if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7648  return false;
7649  if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7650  return false;
7651 
7652  // ASTContext::getTypeSize will return the size rounded up to a
7653  // power of 2, so instead of using that, we need to use the raw
7654  // element size multiplied by the element count.
7655  uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7656  uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7657 
7658  return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7659 }
7660 
7661 // This returns true if at least one of the types is an altivec vector.
7663  assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7664  "expected at least one type to be a vector here");
7665 
7666  bool IsSrcTyAltivec =
7667  SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7669  (SrcTy->castAs<VectorType>()->getVectorKind() ==
7671  (SrcTy->castAs<VectorType>()->getVectorKind() ==
7673 
7674  bool IsDestTyAltivec = DestTy->isVectorType() &&
7675  ((DestTy->castAs<VectorType>()->getVectorKind() ==
7677  (DestTy->castAs<VectorType>()->getVectorKind() ==
7679  (DestTy->castAs<VectorType>()->getVectorKind() ==
7681 
7682  return (IsSrcTyAltivec || IsDestTyAltivec);
7683 }
7684 
7685 /// Are the two types lax-compatible vector types? That is, given
7686 /// that one of them is a vector, do they have equal storage sizes,
7687 /// where the storage size is the number of elements times the element
7688 /// size?
7689 ///
7690 /// This will also return false if either of the types is neither a
7691 /// vector nor a real type.
7693  assert(destTy->isVectorType() || srcTy->isVectorType());
7694 
7695  // Disallow lax conversions between scalars and ExtVectors (these
7696  // conversions are allowed for other vector types because common headers
7697  // depend on them). Most scalar OP ExtVector cases are handled by the
7698  // splat path anyway, which does what we want (convert, not bitcast).
7699  // What this rules out for ExtVectors is crazy things like char4*float.
7700  if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7701  if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7702 
7703  return areVectorTypesSameSize(srcTy, destTy);
7704 }
7705 
7706 /// Is this a legal conversion between two types, one of which is
7707 /// known to be a vector type?
7709  assert(destTy->isVectorType() || srcTy->isVectorType());
7710 
7711  switch (Context.getLangOpts().getLaxVectorConversions()) {
7713  return false;
7714 
7716  if (!srcTy->isIntegralOrEnumerationType()) {
7717  auto *Vec = srcTy->getAs<VectorType>();
7718  if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7719  return false;
7720  }
7721  if (!destTy->isIntegralOrEnumerationType()) {
7722  auto *Vec = destTy->getAs<VectorType>();
7723  if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7724  return false;
7725  }
7726  // OK, integer (vector) -> integer (vector) bitcast.
7727  break;
7728 
7730  break;
7731  }
7732 
7733  return areLaxCompatibleVectorTypes(srcTy, destTy);
7734 }
7735 
7737  CastKind &Kind) {
7738  if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7739  if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7740  return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7741  << DestTy << SrcTy << R;
7742  }
7743  } else if (SrcTy->isMatrixType()) {
7744  return Diag(R.getBegin(),
7745  diag::err_invalid_conversion_between_matrix_and_type)
7746  << SrcTy << DestTy << R;
7747  } else if (DestTy->isMatrixType()) {
7748  return Diag(R.getBegin(),
7749  diag::err_invalid_conversion_between_matrix_and_type)
7750  << DestTy << SrcTy << R;
7751  }
7752 
7753  Kind = CK_MatrixCast;
7754  return false;
7755 }
7756 
7758  CastKind &Kind) {
7759  assert(VectorTy->isVectorType() && "Not a vector type!");
7760 
7761  if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7762  if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7763  return Diag(R.getBegin(),
7764  Ty->isVectorType() ?
7765  diag::err_invalid_conversion_between_vectors :
7766  diag::err_invalid_conversion_between_vector_and_integer)
7767  << VectorTy << Ty << R;
7768  } else
7769  return Diag(R.getBegin(),
7770  diag::err_invalid_conversion_between_vector_and_scalar)
7771  << VectorTy << Ty << R;
7772 
7773  Kind = CK_BitCast;
7774  return false;
7775 }
7776 
7778  QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7779 
7780  if (DestElemTy == SplattedExpr->getType())
7781  return SplattedExpr;
7782 
7783  assert(DestElemTy->isFloatingType() ||
7784  DestElemTy->isIntegralOrEnumerationType());
7785 
7786  CastKind CK;
7787  if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7788  // OpenCL requires that we convert `true` boolean expressions to -1, but
7789  // only when splatting vectors.
7790  if (DestElemTy->isFloatingType()) {
7791  // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7792  // in two steps: boolean to signed integral, then to floating.
7793  ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7794  CK_BooleanToSignedIntegral);
7795  SplattedExpr = CastExprRes.get();
7796  CK = CK_IntegralToFloating;
7797  } else {
7798  CK = CK_BooleanToSignedIntegral;
7799  }
7800  } else {
7801  ExprResult CastExprRes = SplattedExpr;
7802  CK = PrepareScalarCast(CastExprRes, DestElemTy);
7803  if (CastExprRes.isInvalid())
7804  return ExprError();
7805  SplattedExpr = CastExprRes.get();
7806  }
7807  return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7808 }
7809 
7811  Expr *CastExpr, CastKind &Kind) {
7812  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7813 
7814  QualType SrcTy = CastExpr->getType();
7815 
7816  // If SrcTy is a VectorType, the total size must match to explicitly cast to
7817  // an ExtVectorType.
7818  // In OpenCL, casts between vectors of different types are not allowed.
7819  // (See OpenCL 6.2).
7820  if (SrcTy->isVectorType()) {
7821  if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7822  (getLangOpts().OpenCL &&
7823  !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7824  Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7825  << DestTy << SrcTy << R;
7826  return ExprError();
7827  }
7828  Kind = CK_BitCast;
7829  return CastExpr;
7830  }
7831 
7832  // All non-pointer scalars can be cast to ExtVector type. The appropriate
7833  // conversion will take place first from scalar to elt type, and then
7834  // splat from elt type to vector.
7835  if (SrcTy->isPointerType())
7836  return Diag(R.getBegin(),
7837  diag::err_invalid_conversion_between_vector_and_scalar)
7838  << DestTy << SrcTy << R;
7839 
7840  Kind = CK_VectorSplat;
7841  return prepareVectorSplat(DestTy, CastExpr);
7842 }
7843 
7844 ExprResult
7846  Declarator &D, ParsedType &Ty,
7847  SourceLocation RParenLoc, Expr *CastExpr) {
7848  assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7849  "ActOnCastExpr(): missing type or expr");
7850 
7851  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7852  if (D.isInvalidType())
7853  return ExprError();
7854 
7855  if (getLangOpts().CPlusPlus) {
7856  // Check that there are no default arguments (C++ only).
7857  CheckExtraCXXDefaultArguments(D);
7858  } else {
7859  // Make sure any TypoExprs have been dealt with.
7860  ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7861  if (!Res.isUsable())
7862  return ExprError();
7863  CastExpr = Res.get();
7864  }
7865 
7866  checkUnusedDeclAttributes(D);
7867 
7868  QualType castType = castTInfo->getType();
7869  Ty = CreateParsedType(castType, castTInfo);
7870 
7871  bool isVectorLiteral = false;
7872 
7873  // Check for an altivec or OpenCL literal,
7874  // i.e. all the elements are integer constants.
7875  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7876  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7877  if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7878  && castType->isVectorType() && (PE || PLE)) {
7879  if (PLE && PLE->getNumExprs() == 0) {
7880  Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7881  return ExprError();
7882  }
7883  if (PE || PLE->getNumExprs() == 1) {
7884  Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7885  if (!E->isTypeDependent() && !E->getType()->isVectorType())
7886  isVectorLiteral = true;
7887  }
7888  else
7889  isVectorLiteral = true;
7890  }
7891 
7892  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7893  // then handle it as such.
7894  if (isVectorLiteral)
7895  return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7896 
7897  // If the Expr being casted is a ParenListExpr, handle it specially.
7898  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7899  // sequence of BinOp comma operators.
7900  if (isa<ParenListExpr>(CastExpr)) {
7901  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7902  if (Result.isInvalid()) return ExprError();
7903  CastExpr = Result.get();
7904  }
7905 
7906  if (getLangOpts().CPlusPlus && !castType->isVoidType())
7907  Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7908 
7909  ObjC().CheckTollFreeBridgeCast(castType, CastExpr);
7910 
7911  ObjC().CheckObjCBridgeRelatedCast(castType, CastExpr);
7912 
7913  DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7914 
7915  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7916 }
7917 
7919  SourceLocation RParenLoc, Expr *E,
7920  TypeSourceInfo *TInfo) {
7921  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7922  "Expected paren or paren list expression");
7923 
7924  Expr **exprs;
7925  unsigned numExprs;
7926  Expr *subExpr;
7927  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7928  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7929  LiteralLParenLoc = PE->getLParenLoc();
7930  LiteralRParenLoc = PE->getRParenLoc();
7931  exprs = PE->getExprs();
7932  numExprs = PE->getNumExprs();
7933  } else { // isa<ParenExpr> by assertion at function entrance
7934  LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7935  LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7936  subExpr = cast<ParenExpr>(E)->getSubExpr();
7937  exprs = &subExpr;
7938  numExprs = 1;
7939  }
7940 
7941  QualType Ty = TInfo->getType();
7942  assert(Ty->isVectorType() && "Expected vector type");
7943 
7944  SmallVector<Expr *, 8> initExprs;
7945  const VectorType *VTy = Ty->castAs<VectorType>();
7946  unsigned numElems = VTy->getNumElements();
7947 
7948  // '(...)' form of vector initialization in AltiVec: the number of
7949  // initializers must be one or must match the size of the vector.
7950  // If a single value is specified in the initializer then it will be
7951  // replicated to all the components of the vector
7952  if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7953  VTy->getElementType()))
7954  return ExprError();
7955  if (ShouldSplatAltivecScalarInCast(VTy)) {
7956  // The number of initializers must be one or must match the size of the
7957  // vector. If a single value is specified in the initializer then it will
7958  // be replicated to all the components of the vector
7959  if (numExprs == 1) {
7960  QualType ElemTy = VTy->getElementType();
7961  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7962  if (Literal.isInvalid())
7963  return ExprError();
7964  Literal = ImpCastExprToType(Literal.get(), ElemTy,
7965  PrepareScalarCast(Literal, ElemTy));
7966  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7967  }
7968  else if (numExprs < numElems) {
7969  Diag(E->getExprLoc(),
7970  diag::err_incorrect_number_of_vector_initializers);
7971  return ExprError();
7972  }
7973  else
7974  initExprs.append(exprs, exprs + numExprs);
7975  }
7976  else {
7977  // For OpenCL, when the number of initializers is a single value,
7978  // it will be replicated to all components of the vector.
7979  if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
7980  numExprs == 1) {
7981  QualType ElemTy = VTy->getElementType();
7982  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7983  if (Literal.isInvalid())
7984  return ExprError();
7985  Literal = ImpCastExprToType(Literal.get(), ElemTy,
7986  PrepareScalarCast(Literal, ElemTy));
7987  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7988  }
7989 
7990  initExprs.append(exprs, exprs + numExprs);
7991  }
7992  // FIXME: This means that pretty-printing the final AST will produce curly
7993  // braces instead of the original commas.
7994  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7995  initExprs, LiteralRParenLoc);
7996  initE->setType(Ty);
7997  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7998 }
7999 
8000 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8001 /// the ParenListExpr into a sequence of comma binary operators.
8002 ExprResult
8004  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8005  if (!E)
8006  return OrigExpr;
8007 
8008  ExprResult Result(E->getExpr(0));
8009 
8010  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8011  Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8012  E->getExpr(i));
8013 
8014  if (Result.isInvalid()) return ExprError();
8015 
8016  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8017 }
8018 
8020  SourceLocation R,
8021  MultiExprArg Val) {
8022  return ParenListExpr::Create(Context, L, Val, R);
8023 }
8024 
8025 /// Emit a specialized diagnostic when one expression is a null pointer
8026 /// constant and the other is not a pointer. Returns true if a diagnostic is
8027 /// emitted.
8028 bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8029  SourceLocation QuestionLoc) {
8030  const Expr *NullExpr = LHSExpr;
8031  const Expr *NonPointerExpr = RHSExpr;
8033  NullExpr->isNullPointerConstant(Context,
8035 
8036  if (NullKind == Expr::NPCK_NotNull) {
8037  NullExpr = RHSExpr;
8038  NonPointerExpr = LHSExpr;
8039  NullKind =
8040  NullExpr->isNullPointerConstant(Context,
8042  }
8043 
8044  if (NullKind == Expr::NPCK_NotNull)
8045  return false;
8046 
8047  if (NullKind == Expr::NPCK_ZeroExpression)
8048  return false;
8049 
8050  if (NullKind == Expr::NPCK_ZeroLiteral) {
8051  // In this case, check to make sure that we got here from a "NULL"
8052  // string in the source code.
8053  NullExpr = NullExpr->IgnoreParenImpCasts();
8054  SourceLocation loc = NullExpr->getExprLoc();
8055  if (!findMacroSpelling(loc, "NULL"))
8056  return false;
8057  }
8058 
8059  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8060  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8061  << NonPointerExpr->getType() << DiagType
8062  << NonPointerExpr->getSourceRange();
8063  return true;
8064 }
8065 
8066 /// Return false if the condition expression is valid, true otherwise.
8067 static bool checkCondition(Sema &S, const Expr *Cond,
8068  SourceLocation QuestionLoc) {
8069  QualType CondTy = Cond->getType();
8070 
8071  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8072  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8073  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8074  << CondTy << Cond->getSourceRange();
8075  return true;
8076  }
8077 
8078  // C99 6.5.15p2
8079  if (CondTy->isScalarType()) return false;
8080 
8081  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8082  << CondTy << Cond->getSourceRange();
8083  return true;
8084 }
8085 
8086 /// Return false if the NullExpr can be promoted to PointerTy,
8087 /// true otherwise.
8088 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8089  QualType PointerTy) {
8090  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8091  !NullExpr.get()->isNullPointerConstant(S.Context,
8093  return true;
8094 
8095  NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8096  return false;
8097 }
8098 
8099 /// Checks compatibility between two pointers and return the resulting
8100 /// type.
8102  ExprResult &RHS,
8103  SourceLocation Loc) {
8104  QualType LHSTy = LHS.get()->getType();
8105  QualType RHSTy = RHS.get()->getType();
8106 
8107  if (S.Context.hasSameType(LHSTy, RHSTy)) {
8108  // Two identical pointers types are always compatible.
8109  return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8110  }
8111 
8112  QualType lhptee, rhptee;
8113 
8114  // Get the pointee types.
8115  bool IsBlockPointer = false;
8116  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8117  lhptee = LHSBTy->getPointeeType();
8118  rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8119  IsBlockPointer = true;
8120  } else {
8121  lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8122  rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8123  }
8124 
8125  // C99 6.5.15p6: If both operands are pointers to compatible types or to
8126  // differently qualified versions of compatible types, the result type is
8127  // a pointer to an appropriately qualified version of the composite
8128  // type.
8129 
8130  // Only CVR-qualifiers exist in the standard, and the differently-qualified
8131  // clause doesn't make sense for our extensions. E.g. address space 2 should
8132  // be incompatible with address space 3: they may live on different devices or
8133  // anything.
8134  Qualifiers lhQual = lhptee.getQualifiers();
8135  Qualifiers rhQual = rhptee.getQualifiers();
8136 
8137  LangAS ResultAddrSpace = LangAS::Default;
8138  LangAS LAddrSpace = lhQual.getAddressSpace();
8139  LangAS RAddrSpace = rhQual.getAddressSpace();
8140 
8141  // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8142  // spaces is disallowed.
8143  if (lhQual.isAddressSpaceSupersetOf(rhQual))
8144  ResultAddrSpace = LAddrSpace;
8145  else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8146  ResultAddrSpace = RAddrSpace;
8147  else {
8148  S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8149  << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8150  << RHS.get()->getSourceRange();
8151  return QualType();
8152  }
8153 
8154  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8155  auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8156  lhQual.removeCVRQualifiers();
8157  rhQual.removeCVRQualifiers();
8158 
8159  // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8160  // (C99 6.7.3) for address spaces. We assume that the check should behave in
8161  // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8162  // qual types are compatible iff
8163  // * corresponded types are compatible
8164  // * CVR qualifiers are equal
8165  // * address spaces are equal
8166  // Thus for conditional operator we merge CVR and address space unqualified
8167  // pointees and if there is a composite type we return a pointer to it with
8168  // merged qualifiers.
8169  LHSCastKind =
8170  LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8171  RHSCastKind =
8172  RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8173  lhQual.removeAddressSpace();
8174  rhQual.removeAddressSpace();
8175 
8176  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8177  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8178 
8179  QualType CompositeTy = S.Context.mergeTypes(
8180  lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8181  /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8182 
8183  if (CompositeTy.isNull()) {
8184  // In this situation, we assume void* type. No especially good
8185  // reason, but this is what gcc does, and we do have to pick
8186  // to get a consistent AST.
8187  QualType incompatTy;
8188  incompatTy = S.Context.getPointerType(
8189  S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8190  LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8191  RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8192 
8193  // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8194  // for casts between types with incompatible address space qualifiers.
8195  // For the following code the compiler produces casts between global and
8196  // local address spaces of the corresponded innermost pointees:
8197  // local int *global *a;
8198  // global int *global *b;
8199  // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8200  S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8201  << LHSTy << RHSTy << LHS.get()->getSourceRange()
8202  << RHS.get()->getSourceRange();
8203 
8204  return incompatTy;
8205  }
8206 
8207  // The pointer types are compatible.
8208  // In case of OpenCL ResultTy should have the address space qualifier
8209  // which is a superset of address spaces of both the 2nd and the 3rd
8210  // operands of the conditional operator.
8211  QualType ResultTy = [&, ResultAddrSpace]() {
8212  if (S.getLangOpts().OpenCL) {
8213  Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8214  CompositeQuals.setAddressSpace(ResultAddrSpace);
8215  return S.Context
8216  .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8217  .withCVRQualifiers(MergedCVRQual);
8218  }
8219  return CompositeTy.withCVRQualifiers(MergedCVRQual);
8220  }();
8221  if (IsBlockPointer)
8222  ResultTy = S.Context.getBlockPointerType(ResultTy);
8223  else
8224  ResultTy = S.Context.getPointerType(ResultTy);
8225 
8226  LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8227  RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8228  return ResultTy;
8229 }
8230 
8231 /// Return the resulting type when the operands are both block pointers.
8233  ExprResult &LHS,
8234  ExprResult &RHS,
8235  SourceLocation Loc) {
8236  QualType LHSTy = LHS.get()->getType();
8237  QualType RHSTy = RHS.get()->getType();
8238 
8239  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8240  if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8241  QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8242  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8243  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8244  return destType;
8245  }
8246  S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8247  << LHSTy << RHSTy << LHS.get()->getSourceRange()
8248  << RHS.get()->getSourceRange();
8249  return QualType();
8250  }
8251 
8252  // We have 2 block pointer types.
8253  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8254 }
8255 
8256 /// Return the resulting type when the operands are both pointers.
8257 static QualType
8259  ExprResult &RHS,
8260  SourceLocation Loc) {
8261  // get the pointer types
8262  QualType LHSTy = LHS.get()->getType();
8263  QualType RHSTy = RHS.get()->getType();
8264 
8265  // get the "pointed to" types
8266  QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8267  QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8268 
8269  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8270  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8271  // Figure out necessary qualifiers (C99 6.5.15p6)
8272  QualType destPointee
8273  = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8274  QualType destType = S.Context.getPointerType(destPointee);
8275  // Add qualifiers if necessary.
8276  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8277  // Promote to void*.
8278  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8279  return destType;
8280  }
8281  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8282  QualType destPointee
8283  = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8284  QualType destType = S.Context.getPointerType(destPointee);
8285  // Add qualifiers if necessary.
8286  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8287  // Promote to void*.
8288  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8289  return destType;
8290  }
8291 
8292  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8293 }
8294 
8295 /// Return false if the first expression is not an integer and the second
8296 /// expression is not a pointer, true otherwise.
8298  Expr* PointerExpr, SourceLocation Loc,
8299  bool IsIntFirstExpr) {
8300  if (!PointerExpr->getType()->isPointerType() ||
8301  !Int.get()->getType()->isIntegerType())
8302  return false;
8303 
8304  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8305  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8306 
8307  S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8308  << Expr1->getType() << Expr2->getType()
8309  << Expr1->getSourceRange() << Expr2->getSourceRange();
8310  Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8311  CK_IntegralToPointer);
8312  return true;
8313 }
8314 
8315 /// Simple conversion between integer and floating point types.
8316 ///
8317 /// Used when handling the OpenCL conditional operator where the
8318 /// condition is a vector while the other operands are scalar.
8319 ///
8320 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8321 /// types are either integer or floating type. Between the two
8322 /// operands, the type with the higher rank is defined as the "result
8323 /// type". The other operand needs to be promoted to the same type. No
8324 /// other type promotion is allowed. We cannot use
8325 /// UsualArithmeticConversions() for this purpose, since it always
8326 /// promotes promotable types.
8328  ExprResult &RHS,
8329  SourceLocation QuestionLoc) {
8331  if (LHS.isInvalid())
8332  return QualType();
8334  if (RHS.isInvalid())
8335  return QualType();
8336 
8337  // For conversion purposes, we ignore any qualifiers.
8338  // For example, "const float" and "float" are equivalent.
8339  QualType LHSType =
8341  QualType RHSType =
8343 
8344  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8345  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8346  << LHSType << LHS.get()->getSourceRange();
8347  return QualType();
8348  }
8349 
8350  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8351  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8352  << RHSType << RHS.get()->getSourceRange();
8353  return QualType();
8354  }
8355 
8356  // If both types are identical, no conversion is needed.
8357  if (LHSType == RHSType)
8358  return LHSType;
8359 
8360  // Now handle "real" floating types (i.e. float, double, long double).
8361  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8362  return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8363  /*IsCompAssign = */ false);
8364 
8365  // Finally, we have two differing integer types.
8366  return handleIntegerConversion<doIntegralCast, doIntegralCast>
8367  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8368 }
8369 
8370 /// Convert scalar operands to a vector that matches the
8371 /// condition in length.
8372 ///
8373 /// Used when handling the OpenCL conditional operator where the
8374 /// condition is a vector while the other operands are scalar.
8375 ///
8376 /// We first compute the "result type" for the scalar operands
8377 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8378 /// into a vector of that type where the length matches the condition
8379 /// vector type. s6.11.6 requires that the element types of the result
8380 /// and the condition must have the same number of bits.
8381 static QualType
8383  QualType CondTy, SourceLocation QuestionLoc) {
8384  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8385  if (ResTy.isNull()) return QualType();
8386 
8387  const VectorType *CV = CondTy->getAs<VectorType>();
8388  assert(CV);
8389 
8390  // Determine the vector result type
8391  unsigned NumElements = CV->getNumElements();
8392  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8393 
8394  // Ensure that all types have the same number of bits
8395  if (S.Context.getTypeSize(CV->getElementType())
8396  != S.Context.getTypeSize(ResTy)) {
8397  // Since VectorTy is created internally, it does not pretty print
8398  // with an OpenCL name. Instead, we just print a description.
8399  std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8400  SmallString<64> Str;
8401  llvm::raw_svector_ostream OS(Str);
8402  OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8403  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8404  << CondTy << OS.str();
8405  return QualType();
8406  }
8407 
8408  // Convert operands to the vector result type
8409  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8410  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8411 
8412  return VectorTy;
8413 }
8414 
8415 /// Return false if this is a valid OpenCL condition vector
8416 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8417  SourceLocation QuestionLoc) {
8418  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8419  // integral type.
8420  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8421  assert(CondTy);
8422  QualType EleTy = CondTy->getElementType();
8423  if (EleTy->isIntegerType()) return false;
8424 
8425  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8426  << Cond->getType() << Cond->getSourceRange();
8427  return true;
8428 }
8429 
8430 /// Return false if the vector condition type and the vector
8431 /// result type are compatible.
8432 ///
8433 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8434 /// number of elements, and their element types have the same number
8435 /// of bits.
8436 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8437  SourceLocation QuestionLoc) {
8438  const VectorType *CV = CondTy->getAs<VectorType>();
8439  const VectorType *RV = VecResTy->getAs<VectorType>();
8440  assert(CV && RV);
8441 
8442  if (CV->getNumElements() != RV->getNumElements()) {
8443  S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8444  << CondTy << VecResTy;
8445  return true;
8446  }
8447 
8448  QualType CVE = CV->getElementType();
8449  QualType RVE = RV->getElementType();
8450 
8451  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8452  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8453  << CondTy << VecResTy;
8454  return true;
8455  }
8456 
8457  return false;
8458 }
8459 
8460 /// Return the resulting type for the conditional operator in
8461 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8462 /// s6.3.i) when the condition is a vector type.
8463 static QualType
8465  ExprResult &LHS, ExprResult &RHS,
8466  SourceLocation QuestionLoc) {
8467  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8468  if (Cond.isInvalid())
8469  return QualType();
8470  QualType CondTy = Cond.get()->getType();
8471 
8472  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8473  return QualType();
8474 
8475  // If either operand is a vector then find the vector type of the
8476  // result as specified in OpenCL v1.1 s6.3.i.
8477  if (LHS.get()->getType()->isVectorType() ||
8478  RHS.get()->getType()->isVectorType()) {
8479  bool IsBoolVecLang =
8480  !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8481  QualType VecResTy =
8482  S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8483  /*isCompAssign*/ false,
8484  /*AllowBothBool*/ true,
8485  /*AllowBoolConversions*/ false,
8486  /*AllowBooleanOperation*/ IsBoolVecLang,
8487  /*ReportInvalid*/ true);
8488  if (VecResTy.isNull())
8489  return QualType();
8490  // The result type must match the condition type as specified in
8491  // OpenCL v1.1 s6.11.6.
8492  if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8493  return QualType();
8494  return VecResTy;
8495  }
8496 
8497  // Both operands are scalar.
8498  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8499 }
8500 
8501 /// Return true if the Expr is block type
8502 static bool checkBlockType(Sema &S, const Expr *E) {
8503  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8504  QualType Ty = CE->getCallee()->getType();
8505  if (Ty->isBlockPointerType()) {
8506  S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8507  return true;
8508  }
8509  }
8510  return false;
8511 }
8512 
8513 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8514 /// In that case, LHS = cond.
8515 /// C99 6.5.15
8517  ExprResult &RHS, ExprValueKind &VK,
8518  ExprObjectKind &OK,
8519  SourceLocation QuestionLoc) {
8520 
8521  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8522  if (!LHSResult.isUsable()) return QualType();
8523  LHS = LHSResult;
8524 
8525  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8526  if (!RHSResult.isUsable()) return QualType();
8527  RHS = RHSResult;
8528 
8529  // C++ is sufficiently different to merit its own checker.
8530  if (getLangOpts().CPlusPlus)
8531  return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8532 
8533  VK = VK_PRValue;
8534  OK = OK_Ordinary;
8535 
8536  if (Context.isDependenceAllowed() &&
8537  (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8538  RHS.get()->isTypeDependent())) {
8539  assert(!getLangOpts().CPlusPlus);
8540  assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8541  RHS.get()->containsErrors()) &&
8542  "should only occur in error-recovery path.");
8543  return Context.DependentTy;
8544  }
8545 
8546  // The OpenCL operator with a vector condition is sufficiently
8547  // different to merit its own checker.
8548  if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8549  Cond.get()->getType()->isExtVectorType())
8550  return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8551 
8552  // First, check the condition.
8553  Cond = UsualUnaryConversions(Cond.get());
8554  if (Cond.isInvalid())
8555  return QualType();
8556  if (checkCondition(*this, Cond.get(), QuestionLoc))
8557  return QualType();
8558 
8559  // Handle vectors.
8560  if (LHS.get()->getType()->isVectorType() ||
8561  RHS.get()->getType()->isVectorType())
8562  return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8563  /*AllowBothBool*/ true,
8564  /*AllowBoolConversions*/ false,
8565  /*AllowBooleanOperation*/ false,
8566  /*ReportInvalid*/ true);
8567 
8568  QualType ResTy =
8569  UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8570  if (LHS.isInvalid() || RHS.isInvalid())
8571  return QualType();
8572 
8573  // WebAssembly tables are not allowed as conditional LHS or RHS.
8574  QualType LHSTy = LHS.get()->getType();
8575  QualType RHSTy = RHS.get()->getType();
8576  if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8577  Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8578  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8579  return QualType();
8580  }
8581 
8582  // Diagnose attempts to convert between __ibm128, __float128 and long double
8583  // where such conversions currently can't be handled.
8584  if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8585  Diag(QuestionLoc,
8586  diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8587  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8588  return QualType();
8589  }
8590 
8591  // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8592  // selection operator (?:).
8593  if (getLangOpts().OpenCL &&
8594  ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8595  return QualType();
8596  }
8597 
8598  // If both operands have arithmetic type, do the usual arithmetic conversions
8599  // to find a common type: C99 6.5.15p3,5.
8600  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8601  // Disallow invalid arithmetic conversions, such as those between bit-
8602  // precise integers types of different sizes, or between a bit-precise
8603  // integer and another type.
8604  if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8605  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8606  << LHSTy << RHSTy << LHS.get()->getSourceRange()
8607  << RHS.get()->getSourceRange();
8608  return QualType();
8609  }
8610 
8611  LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8612  RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8613 
8614  return ResTy;
8615  }
8616 
8617  // If both operands are the same structure or union type, the result is that
8618  // type.
8619  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8620  if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8621  if (LHSRT->getDecl() == RHSRT->getDecl())
8622  // "If both the operands have structure or union type, the result has
8623  // that type." This implies that CV qualifiers are dropped.
8624  return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8625  RHSTy.getUnqualifiedType());
8626  // FIXME: Type of conditional expression must be complete in C mode.
8627  }
8628 
8629  // C99 6.5.15p5: "If both operands have void type, the result has void type."
8630  // The following || allows only one side to be void (a GCC-ism).
8631  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8632  QualType ResTy;
8633  if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8634  ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8635  } else if (RHSTy->isVoidType()) {
8636  ResTy = RHSTy;
8637  Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8638  << RHS.get()->getSourceRange();
8639  } else {
8640  ResTy = LHSTy;
8641  Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8642  << LHS.get()->getSourceRange();
8643  }
8644  LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8645  RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8646  return ResTy;
8647  }
8648 
8649  // C23 6.5.15p7:
8650  // ... if both the second and third operands have nullptr_t type, the
8651  // result also has that type.
8652  if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8653  return ResTy;
8654 
8655  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8656  // the type of the other operand."
8657  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8658  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8659 
8660  // All objective-c pointer type analysis is done here.
8661  QualType compositeType =
8662  ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8663  if (LHS.isInvalid() || RHS.isInvalid())
8664  return QualType();
8665  if (!compositeType.isNull())
8666  return compositeType;
8667 
8668 
8669  // Handle block pointer types.
8670  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8671  return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8672  QuestionLoc);
8673 
8674  // Check constraints for C object pointers types (C99 6.5.15p3,6).
8675  if (LHSTy->isPointerType() && RHSTy->isPointerType())
8676  return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8677  QuestionLoc);
8678 
8679  // GCC compatibility: soften pointer/integer mismatch. Note that
8680  // null pointers have been filtered out by this point.
8681  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8682  /*IsIntFirstExpr=*/true))
8683  return RHSTy;
8684  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8685  /*IsIntFirstExpr=*/false))
8686  return LHSTy;
8687 
8688  // Emit a better diagnostic if one of the expressions is a null pointer
8689  // constant and the other is not a pointer type. In this case, the user most
8690  // likely forgot to take the address of the other expression.
8691  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8692  return QualType();
8693 
8694  // Finally, if the LHS and RHS types are canonically the same type, we can
8695  // use the common sugared type.
8696  if (Context.hasSameType(LHSTy, RHSTy))
8697  return Context.getCommonSugaredType(LHSTy, RHSTy);
8698 
8699  // Otherwise, the operands are not compatible.
8700  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8701  << LHSTy << RHSTy << LHS.get()->getSourceRange()
8702  << RHS.get()->getSourceRange();
8703  return QualType();
8704 }
8705 
8706 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8707 /// ParenRange in parentheses.
8709  const PartialDiagnostic &Note,
8710  SourceRange ParenRange) {
8711  SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8712  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8713  EndLoc.isValid()) {
8714  Self.Diag(Loc, Note)
8715  << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8716  << FixItHint::CreateInsertion(EndLoc, ")");
8717  } else {
8718  // We can't display the parentheses, so just show the bare note.
8719  Self.Diag(Loc, Note) << ParenRange;
8720  }
8721 }
8722 
8724  return BinaryOperator::isAdditiveOp(Opc) ||
8726  BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8727  // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8728  // not any of the logical operators. Bitwise-xor is commonly used as a
8729  // logical-xor because there is no logical-xor operator. The logical
8730  // operators, including uses of xor, have a high false positive rate for
8731  // precedence warnings.
8732 }
8733 
8734 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8735 /// expression, either using a built-in or overloaded operator,
8736 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8737 /// expression.
8739  const Expr **RHSExprs) {
8740  // Don't strip parenthesis: we should not warn if E is in parenthesis.
8741  E = E->IgnoreImpCasts();
8743  E = E->IgnoreImpCasts();
8744  if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8745  E = MTE->getSubExpr();
8746  E = E->IgnoreImpCasts();
8747  }
8748 
8749  // Built-in binary operator.
8750  if (const auto *OP = dyn_cast<BinaryOperator>(E);
8751  OP && IsArithmeticOp(OP->getOpcode())) {
8752  *Opcode = OP->getOpcode();
8753  *RHSExprs = OP->getRHS();
8754  return true;
8755  }
8756 
8757  // Overloaded operator.
8758  if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8759  if (Call->getNumArgs() != 2)
8760  return false;
8761 
8762  // Make sure this is really a binary operator that is safe to pass into
8763  // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8764  OverloadedOperatorKind OO = Call->getOperator();
8765  if (OO < OO_Plus || OO > OO_Arrow ||
8766  OO == OO_PlusPlus || OO == OO_MinusMinus)
8767  return false;
8768 
8770  if (IsArithmeticOp(OpKind)) {
8771  *Opcode = OpKind;
8772  *RHSExprs = Call->getArg(1);
8773  return true;
8774  }
8775  }
8776 
8777  return false;
8778 }
8779 
8780 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8781 /// or is a logical expression such as (x==y) which has int type, but is
8782 /// commonly interpreted as boolean.
8783 static bool ExprLooksBoolean(const Expr *E) {
8784  E = E->IgnoreParenImpCasts();
8785 
8786  if (E->getType()->isBooleanType())
8787  return true;
8788  if (const auto *OP = dyn_cast<BinaryOperator>(E))
8789  return OP->isComparisonOp() || OP->isLogicalOp();
8790  if (const auto *OP = dyn_cast<UnaryOperator>(E))
8791  return OP->getOpcode() == UO_LNot;
8792  if (E->getType()->isPointerType())
8793  return true;
8794  // FIXME: What about overloaded operator calls returning "unspecified boolean
8795  // type"s (commonly pointer-to-members)?
8796 
8797  return false;
8798 }
8799 
8800 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8801 /// and binary operator are mixed in a way that suggests the programmer assumed
8802 /// the conditional operator has higher precedence, for example:
8803 /// "int x = a + someBinaryCondition ? 1 : 2".
8805  Expr *Condition, const Expr *LHSExpr,
8806  const Expr *RHSExpr) {
8807  BinaryOperatorKind CondOpcode;
8808  const Expr *CondRHS;
8809 
8810  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8811  return;
8812  if (!ExprLooksBoolean(CondRHS))
8813  return;
8814 
8815  // The condition is an arithmetic binary expression, with a right-
8816  // hand side that looks boolean, so warn.
8817 
8818  unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8819  ? diag::warn_precedence_bitwise_conditional
8820  : diag::warn_precedence_conditional;
8821 
8822  Self.Diag(OpLoc, DiagID)
8823  << Condition->getSourceRange()
8824  << BinaryOperator::getOpcodeStr(CondOpcode);
8825 
8827  Self, OpLoc,
8828  Self.PDiag(diag::note_precedence_silence)
8829  << BinaryOperator::getOpcodeStr(CondOpcode),
8830  SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8831 
8832  SuggestParentheses(Self, OpLoc,
8833  Self.PDiag(diag::note_precedence_conditional_first),
8834  SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8835 }
8836 
8837 /// Compute the nullability of a conditional expression.
8839  QualType LHSTy, QualType RHSTy,
8840  ASTContext &Ctx) {
8841  if (!ResTy->isAnyPointerType())
8842  return ResTy;
8843 
8844  auto GetNullability = [](QualType Ty) {
8845  std::optional<NullabilityKind> Kind = Ty->getNullability();
8846  if (Kind) {
8847  // For our purposes, treat _Nullable_result as _Nullable.
8850  return *Kind;
8851  }
8853  };
8854 
8855  auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8856  NullabilityKind MergedKind;
8857 
8858  // Compute nullability of a binary conditional expression.
8859  if (IsBin) {
8860  if (LHSKind == NullabilityKind::NonNull)
8861  MergedKind = NullabilityKind::NonNull;
8862  else
8863  MergedKind = RHSKind;
8864  // Compute nullability of a normal conditional expression.
8865  } else {
8866  if (LHSKind == NullabilityKind::Nullable ||
8867  RHSKind == NullabilityKind::Nullable)
8868  MergedKind = NullabilityKind::Nullable;
8869  else if (LHSKind == NullabilityKind::NonNull)
8870  MergedKind = RHSKind;
8871  else if (RHSKind == NullabilityKind::NonNull)
8872  MergedKind = LHSKind;
8873  else
8874  MergedKind = NullabilityKind::Unspecified;
8875  }
8876 
8877  // Return if ResTy already has the correct nullability.
8878  if (GetNullability(ResTy) == MergedKind)
8879  return ResTy;
8880 
8881  // Strip all nullability from ResTy.
8882  while (ResTy->getNullability())
8883  ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8884 
8885  // Create a new AttributedType with the new nullability kind.
8886  auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8887  return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8888 }
8889 
8890 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8891 /// in the case of a the GNU conditional expr extension.
8893  SourceLocation ColonLoc,
8894  Expr *CondExpr, Expr *LHSExpr,
8895  Expr *RHSExpr) {
8896  if (!Context.isDependenceAllowed()) {
8897  // C cannot handle TypoExpr nodes in the condition because it
8898  // doesn't handle dependent types properly, so make sure any TypoExprs have
8899  // been dealt with before checking the operands.
8900  ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8901  ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8902  ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8903 
8904  if (!CondResult.isUsable())
8905  return ExprError();
8906 
8907  if (LHSExpr) {
8908  if (!LHSResult.isUsable())
8909  return ExprError();
8910  }
8911 
8912  if (!RHSResult.isUsable())
8913  return ExprError();
8914 
8915  CondExpr = CondResult.get();
8916  LHSExpr = LHSResult.get();
8917  RHSExpr = RHSResult.get();
8918  }
8919 
8920  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8921  // was the condition.
8922  OpaqueValueExpr *opaqueValue = nullptr;
8923  Expr *commonExpr = nullptr;
8924  if (!LHSExpr) {
8925  commonExpr = CondExpr;
8926  // Lower out placeholder types first. This is important so that we don't
8927  // try to capture a placeholder. This happens in few cases in C++; such
8928  // as Objective-C++'s dictionary subscripting syntax.
8929  if (commonExpr->hasPlaceholderType()) {
8930  ExprResult result = CheckPlaceholderExpr(commonExpr);
8931  if (!result.isUsable()) return ExprError();
8932  commonExpr = result.get();
8933  }
8934  // We usually want to apply unary conversions *before* saving, except
8935  // in the special case of a C++ l-value conditional.
8936  if (!(getLangOpts().CPlusPlus
8937  && !commonExpr->isTypeDependent()
8938  && commonExpr->getValueKind() == RHSExpr->getValueKind()
8939  && commonExpr->isGLValue()
8940  && commonExpr->isOrdinaryOrBitFieldObject()
8941  && RHSExpr->isOrdinaryOrBitFieldObject()
8942  && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8943  ExprResult commonRes = UsualUnaryConversions(commonExpr);
8944  if (commonRes.isInvalid())
8945  return ExprError();
8946  commonExpr = commonRes.get();
8947  }
8948 
8949  // If the common expression is a class or array prvalue, materialize it
8950  // so that we can safely refer to it multiple times.
8951  if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8952  commonExpr->getType()->isArrayType())) {
8953  ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8954  if (MatExpr.isInvalid())
8955  return ExprError();
8956  commonExpr = MatExpr.get();
8957  }
8958 
8959  opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8960  commonExpr->getType(),
8961  commonExpr->getValueKind(),
8962  commonExpr->getObjectKind(),
8963  commonExpr);
8964  LHSExpr = CondExpr = opaqueValue;
8965  }
8966 
8967  QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8970  ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8971  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8972  VK, OK, QuestionLoc);
8973  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8974  RHS.isInvalid())
8975  return ExprError();
8976 
8977  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8978  RHS.get());
8979 
8980  CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8981 
8982  result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8983  Context);
8984 
8985  if (!commonExpr)
8986  return new (Context)
8987  ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8988  RHS.get(), result, VK, OK);
8989 
8990  return new (Context) BinaryConditionalOperator(
8991  commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8992  ColonLoc, result, VK, OK);
8993 }
8994 
8995 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
8997  unsigned FromAttributes = 0, ToAttributes = 0;
8998  if (const auto *FromFn =
8999  dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9000  FromAttributes =
9001  FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9002  if (const auto *ToFn =
9003  dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9004  ToAttributes =
9005  ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9006 
9007  return FromAttributes != ToAttributes;
9008 }
9009 
9010 // Check if we have a conversion between incompatible cmse function pointer
9011 // types, that is, a conversion between a function pointer with the
9012 // cmse_nonsecure_call attribute and one without.
9014  QualType ToType) {
9015  if (const auto *ToFn =
9016  dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9017  if (const auto *FromFn =
9018  dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9019  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9020  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9021 
9022  return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9023  }
9024  }
9025  return false;
9026 }
9027 
9028 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9029 // being closely modeled after the C99 spec:-). The odd characteristic of this
9030 // routine is it effectively iqnores the qualifiers on the top level pointee.
9031 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9032 // FIXME: add a couple examples in this comment.
9035  SourceLocation Loc) {
9036  assert(LHSType.isCanonical() && "LHS not canonicalized!");
9037  assert(RHSType.isCanonical() && "RHS not canonicalized!");
9038 
9039  // get the "pointed to" type (ignoring qualifiers at the top level)
9040  const Type *lhptee, *rhptee;
9041  Qualifiers lhq, rhq;
9042  std::tie(lhptee, lhq) =
9043  cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9044  std::tie(rhptee, rhq) =
9045  cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9046 
9048 
9049  // C99 6.5.16.1p1: This following citation is common to constraints
9050  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9051  // qualifiers of the type *pointed to* by the right;
9052 
9053  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9054  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9055  lhq.compatiblyIncludesObjCLifetime(rhq)) {
9056  // Ignore lifetime for further calculation.
9057  lhq.removeObjCLifetime();
9058  rhq.removeObjCLifetime();
9059  }
9060 
9061  if (!lhq.compatiblyIncludes(rhq)) {
9062  // Treat address-space mismatches as fatal.
9063  if (!lhq.isAddressSpaceSupersetOf(rhq))
9065 
9066  // It's okay to add or remove GC or lifetime qualifiers when converting to
9067  // and from void*.
9068  else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9071  && (lhptee->isVoidType() || rhptee->isVoidType()))
9072  ; // keep old
9073 
9074  // Treat lifetime mismatches as fatal.
9075  else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9077 
9078  // For GCC/MS compatibility, other qualifier mismatches are treated
9079  // as still compatible in C.
9081  }
9082 
9083  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9084  // incomplete type and the other is a pointer to a qualified or unqualified
9085  // version of void...
9086  if (lhptee->isVoidType()) {
9087  if (rhptee->isIncompleteOrObjectType())
9088  return ConvTy;
9089 
9090  // As an extension, we allow cast to/from void* to function pointer.
9091  assert(rhptee->isFunctionType());
9093  }
9094 
9095  if (rhptee->isVoidType()) {
9096  if (lhptee->isIncompleteOrObjectType())
9097  return ConvTy;
9098 
9099  // As an extension, we allow cast to/from void* to function pointer.
9100  assert(lhptee->isFunctionType());
9102  }
9103 
9104  if (!S.Diags.isIgnored(
9105  diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9106  Loc) &&
9107  RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9108  !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9110 
9111  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9112  // unqualified versions of compatible types, ...
9113  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9114  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9115  // Check if the pointee types are compatible ignoring the sign.
9116  // We explicitly check for char so that we catch "char" vs
9117  // "unsigned char" on systems where "char" is unsigned.
9118  if (lhptee->isCharType())
9119  ltrans = S.Context.UnsignedCharTy;
9120  else if (lhptee->hasSignedIntegerRepresentation())
9121  ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9122 
9123  if (rhptee->isCharType())
9124  rtrans = S.Context.UnsignedCharTy;
9125  else if (rhptee->hasSignedIntegerRepresentation())
9126  rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9127 
9128  if (ltrans == rtrans) {
9129  // Types are compatible ignoring the sign. Qualifier incompatibility
9130  // takes priority over sign incompatibility because the sign
9131  // warning can be disabled.
9132  if (ConvTy != Sema::Compatible)
9133  return ConvTy;
9134 
9136  }
9137 
9138  // If we are a multi-level pointer, it's possible that our issue is simply
9139  // one of qualification - e.g. char ** -> const char ** is not allowed. If
9140  // the eventual target type is the same and the pointers have the same
9141  // level of indirection, this must be the issue.
9142  if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9143  do {
9144  std::tie(lhptee, lhq) =
9145  cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9146  std::tie(rhptee, rhq) =
9147  cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9148 
9149  // Inconsistent address spaces at this point is invalid, even if the
9150  // address spaces would be compatible.
9151  // FIXME: This doesn't catch address space mismatches for pointers of
9152  // different nesting levels, like:
9153  // __local int *** a;
9154  // int ** b = a;
9155  // It's not clear how to actually determine when such pointers are
9156  // invalidly incompatible.
9157  if (lhq.getAddressSpace() != rhq.getAddressSpace())
9159 
9160  } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9161 
9162  if (lhptee == rhptee)
9164  }
9165 
9166  // General pointer incompatibility takes priority over qualifiers.
9167  if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9170  }
9171  if (!S.getLangOpts().CPlusPlus &&
9172  S.IsFunctionConversion(ltrans, rtrans, ltrans))
9174  if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9176  if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9178  return ConvTy;
9179 }
9180 
9181 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9182 /// block pointer types are compatible or whether a block and normal pointer
9183 /// are compatible. It is more restrict than comparing two function pointer
9184 // types.
9187  QualType RHSType) {
9188  assert(LHSType.isCanonical() && "LHS not canonicalized!");
9189  assert(RHSType.isCanonical() && "RHS not canonicalized!");
9190 
9191  QualType lhptee, rhptee;
9192 
9193  // get the "pointed to" type (ignoring qualifiers at the top level)
9194  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9195  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9196 
9197  // In C++, the types have to match exactly.
9198  if (S.getLangOpts().CPlusPlus)
9200 
9202 
9203  // For blocks we enforce that qualifiers are identical.
9204  Qualifiers LQuals = lhptee.getLocalQualifiers();
9205  Qualifiers RQuals = rhptee.getLocalQualifiers();
9206  if (S.getLangOpts().OpenCL) {
9207  LQuals.removeAddressSpace();
9208  RQuals.removeAddressSpace();
9209  }
9210  if (LQuals != RQuals)
9212 
9213  // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9214  // assignment.
9215  // The current behavior is similar to C++ lambdas. A block might be
9216  // assigned to a variable iff its return type and parameters are compatible
9217  // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9218  // an assignment. Presumably it should behave in way that a function pointer
9219  // assignment does in C, so for each parameter and return type:
9220  // * CVR and address space of LHS should be a superset of CVR and address
9221  // space of RHS.
9222  // * unqualified types should be compatible.
9223  if (S.getLangOpts().OpenCL) {
9225  S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9226  S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9228  } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9230 
9231  return ConvTy;
9232 }
9233 
9234 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9235 /// for assignment compatibility.
9238  QualType RHSType) {
9239  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9240  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9241 
9242  if (LHSType->isObjCBuiltinType()) {
9243  // Class is not compatible with ObjC object pointers.
9244  if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9245  !RHSType->isObjCQualifiedClassType())
9247  return Sema::Compatible;
9248  }
9249  if (RHSType->isObjCBuiltinType()) {
9250  if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9251  !LHSType->isObjCQualifiedClassType())
9253  return Sema::Compatible;
9254  }
9255  QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9256  QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9257 
9258  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9259  // make an exception for id<P>
9260  !LHSType->isObjCQualifiedIdType())
9262 
9263  if (S.Context.typesAreCompatible(LHSType, RHSType))
9264  return Sema::Compatible;
9265  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9268 }
9269 
9272  QualType LHSType, QualType RHSType) {
9273  // Fake up an opaque expression. We don't actually care about what
9274  // cast operations are required, so if CheckAssignmentConstraints
9275  // adds casts to this they'll be wasted, but fortunately that doesn't
9276  // usually happen on valid code.
9277  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9278  ExprResult RHSPtr = &RHSExpr;
9279  CastKind K;
9280 
9281  return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9282 }
9283 
9284 /// This helper function returns true if QT is a vector type that has element
9285 /// type ElementType.
9286 static bool isVector(QualType QT, QualType ElementType) {
9287  if (const VectorType *VT = QT->getAs<VectorType>())
9288  return VT->getElementType().getCanonicalType() == ElementType;
9289  return false;
9290 }
9291 
9292 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9293 /// has code to accommodate several GCC extensions when type checking
9294 /// pointers. Here are some objectionable examples that GCC considers warnings:
9295 ///
9296 /// int a, *pint;
9297 /// short *pshort;
9298 /// struct foo *pfoo;
9299 ///
9300 /// pint = pshort; // warning: assignment from incompatible pointer type
9301 /// a = pint; // warning: assignment makes integer from pointer without a cast
9302 /// pint = a; // warning: assignment makes pointer from integer without a cast
9303 /// pint = pfoo; // warning: assignment from incompatible pointer type
9304 ///
9305 /// As a result, the code for dealing with pointers is more complex than the
9306 /// C99 spec dictates.
9307 ///
9308 /// Sets 'Kind' for any result kind except Incompatible.
9311  CastKind &Kind, bool ConvertRHS) {
9312  QualType RHSType = RHS.get()->getType();
9313  QualType OrigLHSType = LHSType;
9314 
9315  // Get canonical types. We're not formatting these types, just comparing
9316  // them.
9317  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9318  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9319 
9320  // Common case: no conversion required.
9321  if (LHSType == RHSType) {
9322  Kind = CK_NoOp;
9323  return Compatible;
9324  }
9325 
9326  // If the LHS has an __auto_type, there are no additional type constraints
9327  // to be worried about.
9328  if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9329  if (AT->isGNUAutoType()) {
9330  Kind = CK_NoOp;
9331  return Compatible;
9332  }
9333  }
9334 
9335  // If we have an atomic type, try a non-atomic assignment, then just add an
9336  // atomic qualification step.
9337  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9338  Sema::AssignConvertType result =
9339  CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9340  if (result != Compatible)
9341  return result;
9342  if (Kind != CK_NoOp && ConvertRHS)
9343  RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9344  Kind = CK_NonAtomicToAtomic;
9345  return Compatible;
9346  }
9347 
9348  // If the left-hand side is a reference type, then we are in a
9349  // (rare!) case where we've allowed the use of references in C,
9350  // e.g., as a parameter type in a built-in function. In this case,
9351  // just make sure that the type referenced is compatible with the
9352  // right-hand side type. The caller is responsible for adjusting
9353  // LHSType so that the resulting expression does not have reference
9354  // type.
9355  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9356  if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9357  Kind = CK_LValueBitCast;
9358  return Compatible;
9359  }
9360  return Incompatible;
9361  }
9362 
9363  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9364  // to the same ExtVector type.
9365  if (LHSType->isExtVectorType()) {
9366  if (RHSType->isExtVectorType())
9367  return Incompatible;
9368  if (RHSType->isArithmeticType()) {
9369  // CK_VectorSplat does T -> vector T, so first cast to the element type.
9370  if (ConvertRHS)
9371  RHS = prepareVectorSplat(LHSType, RHS.get());
9372  Kind = CK_VectorSplat;
9373  return Compatible;
9374  }
9375  }
9376 
9377  // Conversions to or from vector type.
9378  if (LHSType->isVectorType() || RHSType->isVectorType()) {
9379  if (LHSType->isVectorType() && RHSType->isVectorType()) {
9380  // Allow assignments of an AltiVec vector type to an equivalent GCC
9381  // vector type and vice versa
9382  if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9383  Kind = CK_BitCast;
9384  return Compatible;
9385  }
9386 
9387  // If we are allowing lax vector conversions, and LHS and RHS are both
9388  // vectors, the total size only needs to be the same. This is a bitcast;
9389  // no bits are changed but the result type is different.
9390  if (isLaxVectorConversion(RHSType, LHSType)) {
9391  // The default for lax vector conversions with Altivec vectors will
9392  // change, so if we are converting between vector types where
9393  // at least one is an Altivec vector, emit a warning.
9394  if (Context.getTargetInfo().getTriple().isPPC() &&
9395  anyAltivecTypes(RHSType, LHSType) &&
9396  !Context.areCompatibleVectorTypes(RHSType, LHSType))
9397  Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9398  << RHSType << LHSType;
9399  Kind = CK_BitCast;
9400  return IncompatibleVectors;
9401  }
9402  }
9403 
9404  // When the RHS comes from another lax conversion (e.g. binops between
9405  // scalars and vectors) the result is canonicalized as a vector. When the
9406  // LHS is also a vector, the lax is allowed by the condition above. Handle
9407  // the case where LHS is a scalar.
9408  if (LHSType->isScalarType()) {
9409  const VectorType *VecType = RHSType->getAs<VectorType>();
9410  if (VecType && VecType->getNumElements() == 1 &&
9411  isLaxVectorConversion(RHSType, LHSType)) {
9412  if (Context.getTargetInfo().getTriple().isPPC() &&
9413  (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9414  VecType->getVectorKind() == VectorKind::AltiVecBool ||
9415  VecType->getVectorKind() == VectorKind::AltiVecPixel))
9416  Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9417  << RHSType << LHSType;
9418  ExprResult *VecExpr = &RHS;
9419  *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9420  Kind = CK_BitCast;
9421  return Compatible;
9422  }
9423  }
9424 
9425  // Allow assignments between fixed-length and sizeless SVE vectors.
9426  if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9427  (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9428  if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9429  Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9430  Kind = CK_BitCast;
9431  return Compatible;
9432  }
9433 
9434  // Allow assignments between fixed-length and sizeless RVV vectors.
9435  if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9436  (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9437  if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9438  Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9439  Kind = CK_BitCast;
9440  return Compatible;
9441  }
9442  }
9443 
9444  return Incompatible;
9445  }
9446 
9447  // Diagnose attempts to convert between __ibm128, __float128 and long double
9448  // where such conversions currently can't be handled.
9449  if (unsupportedTypeConversion(*this, LHSType, RHSType))
9450  return Incompatible;
9451 
9452  // Disallow assigning a _Complex to a real type in C++ mode since it simply
9453  // discards the imaginary part.
9454  if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9455  !LHSType->getAs<ComplexType>())
9456  return Incompatible;
9457 
9458  // Arithmetic conversions.
9459  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9460  !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9461  if (ConvertRHS)
9462  Kind = PrepareScalarCast(RHS, LHSType);
9463  return Compatible;
9464  }
9465 
9466  // Conversions to normal pointers.
9467  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9468  // U* -> T*
9469  if (isa<PointerType>(RHSType)) {
9470  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9471  LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9472  if (AddrSpaceL != AddrSpaceR)
9473  Kind = CK_AddressSpaceConversion;
9474  else if (Context.hasCvrSimilarType(RHSType, LHSType))
9475  Kind = CK_NoOp;
9476  else
9477  Kind = CK_BitCast;
9478  return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9479  RHS.get()->getBeginLoc());
9480  }
9481 
9482  // int -> T*
9483  if (RHSType->isIntegerType()) {
9484  Kind = CK_IntegralToPointer; // FIXME: null?
9485  return IntToPointer;
9486  }
9487 
9488  // C pointers are not compatible with ObjC object pointers,
9489  // with two exceptions:
9490  if (isa<ObjCObjectPointerType>(RHSType)) {
9491  // - conversions to void*
9492  if (LHSPointer->getPointeeType()->isVoidType()) {
9493  Kind = CK_BitCast;
9494  return Compatible;
9495  }
9496 
9497  // - conversions from 'Class' to the redefinition type
9498  if (RHSType->isObjCClassType() &&
9499  Context.hasSameType(LHSType,
9500  Context.getObjCClassRedefinitionType())) {
9501  Kind = CK_BitCast;
9502  return Compatible;
9503  }
9504 
9505  Kind = CK_BitCast;
9506  return IncompatiblePointer;
9507  }
9508 
9509  // U^ -> void*
9510  if (RHSType->getAs<BlockPointerType>()) {
9511  if (LHSPointer->getPointeeType()->isVoidType()) {
9512  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9513  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9514  ->getPointeeType()
9515  .getAddressSpace();
9516  Kind =
9517  AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9518  return Compatible;
9519  }
9520  }
9521 
9522  return Incompatible;
9523  }
9524 
9525  // Conversions to block pointers.
9526  if (isa<BlockPointerType>(LHSType)) {
9527  // U^ -> T^
9528  if (RHSType->isBlockPointerType()) {
9529  LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9530  ->getPointeeType()
9531  .getAddressSpace();
9532  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9533  ->getPointeeType()
9534  .getAddressSpace();
9535  Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9536  return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9537  }
9538 
9539  // int or null -> T^
9540  if (RHSType->isIntegerType()) {
9541  Kind = CK_IntegralToPointer; // FIXME: null
9542  return IntToBlockPointer;
9543  }
9544 
9545  // id -> T^
9546  if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9547  Kind = CK_AnyPointerToBlockPointerCast;
9548  return Compatible;
9549  }
9550 
9551  // void* -> T^
9552  if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9553  if (RHSPT->getPointeeType()->isVoidType()) {
9554  Kind = CK_AnyPointerToBlockPointerCast;
9555  return Compatible;
9556  }
9557 
9558  return Incompatible;
9559  }
9560 
9561  // Conversions to Objective-C pointers.
9562  if (isa<ObjCObjectPointerType>(LHSType)) {
9563  // A* -> B*
9564  if (RHSType->isObjCObjectPointerType()) {
9565  Kind = CK_BitCast;
9566  Sema::AssignConvertType result =
9567  checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9568  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9569  result == Compatible &&
9570  !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9571  result = IncompatibleObjCWeakRef;
9572  return result;
9573  }
9574 
9575  // int or null -> A*
9576  if (RHSType->isIntegerType()) {
9577  Kind = CK_IntegralToPointer; // FIXME: null
9578  return IntToPointer;
9579  }
9580 
9581  // In general, C pointers are not compatible with ObjC object pointers,
9582  // with two exceptions:
9583  if (isa<PointerType>(RHSType)) {
9584  Kind = CK_CPointerToObjCPointerCast;
9585 
9586  // - conversions from 'void*'
9587  if (RHSType->isVoidPointerType()) {
9588  return Compatible;
9589  }
9590 
9591  // - conversions to 'Class' from its redefinition type
9592  if (LHSType->isObjCClassType() &&
9593  Context.hasSameType(RHSType,
9594  Context.getObjCClassRedefinitionType())) {
9595  return Compatible;
9596  }
9597 
9598  return IncompatiblePointer;
9599  }
9600 
9601  // Only under strict condition T^ is compatible with an Objective-C pointer.
9602  if (RHSType->isBlockPointerType() &&
9603  LHSType->isBlockCompatibleObjCPointerType(Context)) {
9604  if (ConvertRHS)
9605  maybeExtendBlockObject(RHS);
9606  Kind = CK_BlockPointerToObjCPointerCast;
9607  return Compatible;
9608  }
9609 
9610  return Incompatible;
9611  }
9612 
9613  // Conversion to nullptr_t (C23 only)
9614  if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9615  RHS.get()->isNullPointerConstant(Context,
9617  // null -> nullptr_t
9618  Kind = CK_NullToPointer;
9619  return Compatible;
9620  }
9621 
9622  // Conversions from pointers that are not covered by the above.
9623  if (isa<PointerType>(RHSType)) {
9624  // T* -> _Bool
9625  if (LHSType == Context.BoolTy) {
9626  Kind = CK_PointerToBoolean;
9627  return Compatible;
9628  }
9629 
9630  // T* -> int
9631  if (LHSType->isIntegerType()) {
9632  Kind = CK_PointerToIntegral;
9633  return PointerToInt;
9634  }
9635 
9636  return Incompatible;
9637  }
9638 
9639  // Conversions from Objective-C pointers that are not covered by the above.
9640  if (isa<ObjCObjectPointerType>(RHSType)) {
9641  // T* -> _Bool
9642  if (LHSType == Context.BoolTy) {
9643  Kind = CK_PointerToBoolean;
9644  return Compatible;
9645  }
9646 
9647  // T* -> int
9648  if (LHSType->isIntegerType()) {
9649  Kind = CK_PointerToIntegral;
9650  return PointerToInt;
9651  }
9652 
9653  return Incompatible;
9654  }
9655 
9656  // struct A -> struct B
9657  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9658  if (Context.typesAreCompatible(LHSType, RHSType)) {
9659  Kind = CK_NoOp;
9660  return Compatible;
9661  }
9662  }
9663 
9664  if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9665  Kind = CK_IntToOCLSampler;
9666  return Compatible;
9667  }
9668 
9669  return Incompatible;
9670 }
9671 
9672 /// Constructs a transparent union from an expression that is
9673 /// used to initialize the transparent union.
9675  ExprResult &EResult, QualType UnionType,
9676  FieldDecl *Field) {
9677  // Build an initializer list that designates the appropriate member
9678  // of the transparent union.
9679  Expr *E = EResult.get();
9681  E, SourceLocation());
9682  Initializer->setType(UnionType);
9683  Initializer->setInitializedFieldInUnion(Field);
9684 
9685  // Build a compound literal constructing a value of the transparent
9686  // union type from this initializer list.
9687  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9688  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9689  VK_PRValue, Initializer, false);
9690 }
9691 
9694  ExprResult &RHS) {
9695  QualType RHSType = RHS.get()->getType();
9696 
9697  // If the ArgType is a Union type, we want to handle a potential
9698  // transparent_union GCC extension.
9699  const RecordType *UT = ArgType->getAsUnionType();
9700  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9701  return Incompatible;
9702 
9703  // The field to initialize within the transparent union.
9704  RecordDecl *UD = UT->getDecl();
9705  FieldDecl *InitField = nullptr;
9706  // It's compatible if the expression matches any of the fields.
9707  for (auto *it : UD->fields()) {
9708  if (it->getType()->isPointerType()) {
9709  // If the transparent union contains a pointer type, we allow:
9710  // 1) void pointer
9711  // 2) null pointer constant
9712  if (RHSType->isPointerType())
9713  if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9714  RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9715  InitField = it;
9716  break;
9717  }
9718 
9719  if (RHS.get()->isNullPointerConstant(Context,
9721  RHS = ImpCastExprToType(RHS.get(), it->getType(),
9722  CK_NullToPointer);
9723  InitField = it;
9724  break;
9725  }
9726  }
9727 
9728  CastKind Kind;
9729  if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9730  == Compatible) {
9731  RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9732  InitField = it;
9733  break;
9734  }
9735  }
9736 
9737  if (!InitField)
9738  return Incompatible;
9739 
9740  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9741  return Compatible;
9742 }
9743 
9746  bool Diagnose,
9747  bool DiagnoseCFAudited,
9748  bool ConvertRHS) {
9749  // We need to be able to tell the caller whether we diagnosed a problem, if
9750  // they ask us to issue diagnostics.
9751  assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9752 
9753  // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9754  // we can't avoid *all* modifications at the moment, so we need some somewhere
9755  // to put the updated value.
9756  ExprResult LocalRHS = CallerRHS;
9757  ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9758 
9759  if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9760  if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9761  if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9762  !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9763  Diag(RHS.get()->getExprLoc(),
9764  diag::warn_noderef_to_dereferenceable_pointer)
9765  << RHS.get()->getSourceRange();
9766  }
9767  }
9768  }
9769 
9770  if (getLangOpts().CPlusPlus) {
9771  if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9772  // C++ 5.17p3: If the left operand is not of class type, the
9773  // expression is implicitly converted (C++ 4) to the
9774  // cv-unqualified type of the left operand.
9775  QualType RHSType = RHS.get()->getType();
9776  if (Diagnose) {
9777  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9778  AA_Assigning);
9779  } else {
9781  TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9782  /*SuppressUserConversions=*/false,
9784  /*InOverloadResolution=*/false,
9785  /*CStyle=*/false,
9786  /*AllowObjCWritebackConversion=*/false);
9787  if (ICS.isFailure())
9788  return Incompatible;
9789  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9790  ICS, AA_Assigning);
9791  }
9792  if (RHS.isInvalid())
9793  return Incompatible;
9794  Sema::AssignConvertType result = Compatible;
9795  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9796  !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9797  result = IncompatibleObjCWeakRef;
9798  return result;
9799  }
9800 
9801  // FIXME: Currently, we fall through and treat C++ classes like C
9802  // structures.
9803  // FIXME: We also fall through for atomics; not sure what should
9804  // happen there, though.
9805  } else if (RHS.get()->getType() == Context.OverloadTy) {
9806  // As a set of extensions to C, we support overloading on functions. These
9807  // functions need to be resolved here.
9808  DeclAccessPair DAP;
9809  if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9810  RHS.get(), LHSType, /*Complain=*/false, DAP))
9811  RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9812  else
9813  return Incompatible;
9814  }
9815 
9816  // This check seems unnatural, however it is necessary to ensure the proper
9817  // conversion of functions/arrays. If the conversion were done for all
9818  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9819  // expressions that suppress this implicit conversion (&, sizeof). This needs
9820  // to happen before we check for null pointer conversions because C does not
9821  // undergo the same implicit conversions as C++ does above (by the calls to
9822  // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9823  // lvalue to rvalue cast before checking for null pointer constraints. This
9824  // addresses code like: nullptr_t val; int *ptr; ptr = val;
9825  //
9826  // Suppress this for references: C++ 8.5.3p5.
9827  if (!LHSType->isReferenceType()) {
9828  // FIXME: We potentially allocate here even if ConvertRHS is false.
9829  RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9830  if (RHS.isInvalid())
9831  return Incompatible;
9832  }
9833 
9834  // The constraints are expressed in terms of the atomic, qualified, or
9835  // unqualified type of the LHS.
9836  QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9837 
9838  // C99 6.5.16.1p1: the left operand is a pointer and the right is
9839  // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9840  if ((LHSTypeAfterConversion->isPointerType() ||
9841  LHSTypeAfterConversion->isObjCObjectPointerType() ||
9842  LHSTypeAfterConversion->isBlockPointerType()) &&
9843  ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9844  RHS.get()->isNullPointerConstant(Context,
9846  if (Diagnose || ConvertRHS) {
9847  CastKind Kind;
9848  CXXCastPath Path;
9849  CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9850  /*IgnoreBaseAccess=*/false, Diagnose);
9851  if (ConvertRHS)
9852  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9853  }
9854  return Compatible;
9855  }
9856  // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9857  // unqualified bool, and the right operand is a pointer or its type is
9858  // nullptr_t.
9859  if (getLangOpts().C23 && LHSType->isBooleanType() &&
9860  RHS.get()->getType()->isNullPtrType()) {
9861  // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9862  // only handles nullptr -> _Bool due to needing an extra conversion
9863  // step.
9864  // We model this by converting from nullptr -> void * and then let the
9865  // conversion from void * -> _Bool happen naturally.
9866  if (Diagnose || ConvertRHS) {
9867  CastKind Kind;
9868  CXXCastPath Path;
9869  CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
9870  /*IgnoreBaseAccess=*/false, Diagnose);
9871  if (ConvertRHS)
9872  RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9873  &Path);
9874  }
9875  }
9876 
9877  // OpenCL queue_t type assignment.
9878  if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9879  Context, Expr::NPC_ValueDependentIsNull)) {
9880  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9881  return Compatible;
9882  }
9883 
9884  CastKind Kind;
9885  Sema::AssignConvertType result =
9886  CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9887 
9888  // C99 6.5.16.1p2: The value of the right operand is converted to the
9889  // type of the assignment expression.
9890  // CheckAssignmentConstraints allows the left-hand side to be a reference,
9891  // so that we can use references in built-in functions even in C.
9892  // The getNonReferenceType() call makes sure that the resulting expression
9893  // does not have reference type.
9894  if (result != Incompatible && RHS.get()->getType() != LHSType) {
9895  QualType Ty = LHSType.getNonLValueExprType(Context);
9896  Expr *E = RHS.get();
9897 
9898  // Check for various Objective-C errors. If we are not reporting
9899  // diagnostics and just checking for errors, e.g., during overload
9900  // resolution, return Incompatible to indicate the failure.
9901  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9902  ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9904  DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9905  if (!Diagnose)
9906  return Incompatible;
9907  }
9908  if (getLangOpts().ObjC &&
9909  (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9910  E->getType(), E, Diagnose) ||
9911  ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9912  if (!Diagnose)
9913  return Incompatible;
9914  // Replace the expression with a corrected version and continue so we
9915  // can find further errors.
9916  RHS = E;
9917  return Compatible;
9918  }
9919 
9920  if (ConvertRHS)
9921  RHS = ImpCastExprToType(E, Ty, Kind);
9922  }
9923 
9924  return result;
9925 }
9926 
9927 namespace {
9928 /// The original operand to an operator, prior to the application of the usual
9929 /// arithmetic conversions and converting the arguments of a builtin operator
9930 /// candidate.
9931 struct OriginalOperand {
9932  explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9933  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9934  Op = MTE->getSubExpr();
9935  if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9936  Op = BTE->getSubExpr();
9937  if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9938  Orig = ICE->getSubExprAsWritten();
9939  Conversion = ICE->getConversionFunction();
9940  }
9941  }
9942 
9943  QualType getType() const { return Orig->getType(); }
9944 
9945  Expr *Orig;
9946  NamedDecl *Conversion;
9947 };
9948 }
9949 
9951  ExprResult &RHS) {
9952  OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9953 
9954  Diag(Loc, diag::err_typecheck_invalid_operands)
9955  << OrigLHS.getType() << OrigRHS.getType()
9956  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9957 
9958  // If a user-defined conversion was applied to either of the operands prior
9959  // to applying the built-in operator rules, tell the user about it.
9960  if (OrigLHS.Conversion) {
9961  Diag(OrigLHS.Conversion->getLocation(),
9962  diag::note_typecheck_invalid_operands_converted)
9963  << 0 << LHS.get()->getType();
9964  }
9965  if (OrigRHS.Conversion) {
9966  Diag(OrigRHS.Conversion->getLocation(),
9967  diag::note_typecheck_invalid_operands_converted)
9968  << 1 << RHS.get()->getType();
9969  }
9970 
9971  return QualType();
9972 }
9973 
9974 // Diagnose cases where a scalar was implicitly converted to a vector and
9975 // diagnose the underlying types. Otherwise, diagnose the error
9976 // as invalid vector logical operands for non-C++ cases.
9978  ExprResult &RHS) {
9979  QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9980  QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9981 
9982  bool LHSNatVec = LHSType->isVectorType();
9983  bool RHSNatVec = RHSType->isVectorType();
9984 
9985  if (!(LHSNatVec && RHSNatVec)) {
9986  Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9987  Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9988  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9989  << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9990  << Vector->getSourceRange();
9991  return QualType();
9992  }
9993 
9994  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9995  << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9996  << RHS.get()->getSourceRange();
9997 
9998  return QualType();
9999 }
10000 
10001 /// Try to convert a value of non-vector type to a vector type by converting
10002 /// the type to the element type of the vector and then performing a splat.
10003 /// If the language is OpenCL, we only use conversions that promote scalar
10004 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10005 /// for float->int.
10006 ///
10007 /// OpenCL V2.0 6.2.6.p2:
10008 /// An error shall occur if any scalar operand type has greater rank
10009 /// than the type of the vector element.
10010 ///
10011 /// \param scalar - if non-null, actually perform the conversions
10012 /// \return true if the operation fails (but without diagnosing the failure)
10013 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10014  QualType scalarTy,
10015  QualType vectorEltTy,
10016  QualType vectorTy,
10017  unsigned &DiagID) {
10018  // The conversion to apply to the scalar before splatting it,
10019  // if necessary.
10020  CastKind scalarCast = CK_NoOp;
10021 
10022  if (vectorEltTy->isIntegralType(S.Context)) {
10023  if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10024  (scalarTy->isIntegerType() &&
10025  S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10026  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10027  return true;
10028  }
10029  if (!scalarTy->isIntegralType(S.Context))
10030  return true;
10031  scalarCast = CK_IntegralCast;
10032  } else if (vectorEltTy->isRealFloatingType()) {
10033  if (scalarTy->isRealFloatingType()) {
10034  if (S.getLangOpts().OpenCL &&
10035  S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10036  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10037  return true;
10038  }
10039  scalarCast = CK_FloatingCast;
10040  }
10041  else if (scalarTy->isIntegralType(S.Context))
10042  scalarCast = CK_IntegralToFloating;
10043  else
10044  return true;
10045  } else {
10046  return true;
10047  }
10048 
10049  // Adjust scalar if desired.
10050  if (scalar) {
10051  if (scalarCast != CK_NoOp)
10052  *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10053  *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10054  }
10055  return false;
10056 }
10057 
10058 /// Convert vector E to a vector with the same number of elements but different
10059 /// element type.
10060 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10061  const auto *VecTy = E->getType()->getAs<VectorType>();
10062  assert(VecTy && "Expression E must be a vector");
10063  QualType NewVecTy =
10064  VecTy->isExtVectorType()
10065  ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10066  : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10067  VecTy->getVectorKind());
10068 
10069  // Look through the implicit cast. Return the subexpression if its type is
10070  // NewVecTy.
10071  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10072  if (ICE->getSubExpr()->getType() == NewVecTy)
10073  return ICE->getSubExpr();
10074 
10075  auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10076  return S.ImpCastExprToType(E, NewVecTy, Cast);
10077 }
10078 
10079 /// Test if a (constant) integer Int can be casted to another integer type
10080 /// IntTy without losing precision.
10082  QualType OtherIntTy) {
10083  QualType IntTy = Int->get()->getType().getUnqualifiedType();
10084 
10085  // Reject cases where the value of the Int is unknown as that would
10086  // possibly cause truncation, but accept cases where the scalar can be
10087  // demoted without loss of precision.
10088  Expr::EvalResult EVResult;
10089  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10090  int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10091  bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10092  bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10093 
10094  if (CstInt) {
10095  // If the scalar is constant and is of a higher order and has more active
10096  // bits that the vector element type, reject it.
10097  llvm::APSInt Result = EVResult.Val.getInt();
10098  unsigned NumBits = IntSigned
10099  ? (Result.isNegative() ? Result.getSignificantBits()
10100  : Result.getActiveBits())
10101  : Result.getActiveBits();
10102  if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10103  return true;
10104 
10105  // If the signedness of the scalar type and the vector element type
10106  // differs and the number of bits is greater than that of the vector
10107  // element reject it.
10108  return (IntSigned != OtherIntSigned &&
10109  NumBits > S.Context.getIntWidth(OtherIntTy));
10110  }
10111 
10112  // Reject cases where the value of the scalar is not constant and it's
10113  // order is greater than that of the vector element type.
10114  return (Order < 0);
10115 }
10116 
10117 /// Test if a (constant) integer Int can be casted to floating point type
10118 /// FloatTy without losing precision.
10120  QualType FloatTy) {
10121  QualType IntTy = Int->get()->getType().getUnqualifiedType();
10122 
10123  // Determine if the integer constant can be expressed as a floating point
10124  // number of the appropriate type.
10125  Expr::EvalResult EVResult;
10126  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10127 
10128  uint64_t Bits = 0;
10129  if (CstInt) {
10130  // Reject constants that would be truncated if they were converted to
10131  // the floating point type. Test by simple to/from conversion.
10132  // FIXME: Ideally the conversion to an APFloat and from an APFloat
10133  // could be avoided if there was a convertFromAPInt method
10134  // which could signal back if implicit truncation occurred.
10135  llvm::APSInt Result = EVResult.Val.getInt();
10136  llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10137  Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10138  llvm::APFloat::rmTowardZero);
10139  llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10140  !IntTy->hasSignedIntegerRepresentation());
10141  bool Ignored = false;
10142  Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10143  &Ignored);
10144  if (Result != ConvertBack)
10145  return true;
10146  } else {
10147  // Reject types that cannot be fully encoded into the mantissa of
10148  // the float.
10149  Bits = S.Context.getTypeSize(IntTy);
10150  unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10151  S.Context.getFloatTypeSemantics(FloatTy));
10152  if (Bits > FloatPrec)
10153  return true;
10154  }
10155 
10156  return false;
10157 }
10158 
10159 /// Attempt to convert and splat Scalar into a vector whose types matches
10160 /// Vector following GCC conversion rules. The rule is that implicit
10161 /// conversion can occur when Scalar can be casted to match Vector's element
10162 /// type without causing truncation of Scalar.
10164  ExprResult *Vector) {
10165  QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10166  QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10167  QualType VectorEltTy;
10168 
10169  if (const auto *VT = VectorTy->getAs<VectorType>()) {
10170  assert(!isa<ExtVectorType>(VT) &&
10171  "ExtVectorTypes should not be handled here!");
10172  VectorEltTy = VT->getElementType();
10173  } else if (VectorTy->isSveVLSBuiltinType()) {
10174  VectorEltTy =
10175  VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10176  } else {
10177  llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10178  }
10179 
10180  // Reject cases where the vector element type or the scalar element type are
10181  // not integral or floating point types.
10182  if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10183  return true;
10184 
10185  // The conversion to apply to the scalar before splatting it,
10186  // if necessary.
10187  CastKind ScalarCast = CK_NoOp;
10188 
10189  // Accept cases where the vector elements are integers and the scalar is
10190  // an integer.
10191  // FIXME: Notionally if the scalar was a floating point value with a precise
10192  // integral representation, we could cast it to an appropriate integer
10193  // type and then perform the rest of the checks here. GCC will perform
10194  // this conversion in some cases as determined by the input language.
10195  // We should accept it on a language independent basis.
10196  if (VectorEltTy->isIntegralType(S.Context) &&
10197  ScalarTy->isIntegralType(S.Context) &&
10198  S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10199 
10200  if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10201  return true;
10202 
10203  ScalarCast = CK_IntegralCast;
10204  } else if (VectorEltTy->isIntegralType(S.Context) &&
10205  ScalarTy->isRealFloatingType()) {
10206  if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10207  ScalarCast = CK_FloatingToIntegral;
10208  else
10209  return true;
10210  } else if (VectorEltTy->isRealFloatingType()) {
10211  if (ScalarTy->isRealFloatingType()) {
10212 
10213  // Reject cases where the scalar type is not a constant and has a higher
10214  // Order than the vector element type.
10215  llvm::APFloat Result(0.0);
10216 
10217  // Determine whether this is a constant scalar. In the event that the
10218  // value is dependent (and thus cannot be evaluated by the constant
10219  // evaluator), skip the evaluation. This will then diagnose once the
10220  // expression is instantiated.
10221  bool CstScalar = Scalar->get()->isValueDependent() ||
10222  Scalar->get()->EvaluateAsFloat(Result, S.Context);
10223  int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10224  if (!CstScalar && Order < 0)
10225  return true;
10226 
10227  // If the scalar cannot be safely casted to the vector element type,
10228  // reject it.
10229  if (CstScalar) {
10230  bool Truncated = false;
10231  Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10232  llvm::APFloat::rmNearestTiesToEven, &Truncated);
10233  if (Truncated)
10234  return true;
10235  }
10236 
10237  ScalarCast = CK_FloatingCast;
10238  } else if (ScalarTy->isIntegralType(S.Context)) {
10239  if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10240  return true;
10241 
10242  ScalarCast = CK_IntegralToFloating;
10243  } else
10244  return true;
10245  } else if (ScalarTy->isEnumeralType())
10246  return true;
10247 
10248  // Adjust scalar if desired.
10249  if (ScalarCast != CK_NoOp)
10250  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10251  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10252  return false;
10253 }
10254 
10256  SourceLocation Loc, bool IsCompAssign,
10257  bool AllowBothBool,
10258  bool AllowBoolConversions,
10259  bool AllowBoolOperation,
10260  bool ReportInvalid) {
10261  if (!IsCompAssign) {
10262  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10263  if (LHS.isInvalid())
10264  return QualType();
10265  }
10266  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10267  if (RHS.isInvalid())
10268  return QualType();
10269 
10270  // For conversion purposes, we ignore any qualifiers.
10271  // For example, "const float" and "float" are equivalent.
10272  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10273  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10274 
10275  const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10276  const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10277  assert(LHSVecType || RHSVecType);
10278 
10279  // AltiVec-style "vector bool op vector bool" combinations are allowed
10280  // for some operators but not others.
10281  if (!AllowBothBool && LHSVecType &&
10282  LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10283  RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10284  return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10285 
10286  // This operation may not be performed on boolean vectors.
10287  if (!AllowBoolOperation &&
10288  (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10289  return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10290 
10291  // If the vector types are identical, return.
10292  if (Context.hasSameType(LHSType, RHSType))
10293  return Context.getCommonSugaredType(LHSType, RHSType);
10294 
10295  // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10296  if (LHSVecType && RHSVecType &&
10297  Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10298  if (isa<ExtVectorType>(LHSVecType)) {
10299  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10300  return LHSType;
10301  }
10302 
10303  if (!IsCompAssign)
10304  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10305  return RHSType;
10306  }
10307 
10308  // AllowBoolConversions says that bool and non-bool AltiVec vectors
10309  // can be mixed, with the result being the non-bool type. The non-bool
10310  // operand must have integer element type.
10311  if (AllowBoolConversions && LHSVecType && RHSVecType &&
10312  LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10313  (Context.getTypeSize(LHSVecType->getElementType()) ==
10314  Context.getTypeSize(RHSVecType->getElementType()))) {
10315  if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10316  LHSVecType->getElementType()->isIntegerType() &&
10317  RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10318  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10319  return LHSType;
10320  }
10321  if (!IsCompAssign &&
10322  LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10323  RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10324  RHSVecType->getElementType()->isIntegerType()) {
10325  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10326  return RHSType;
10327  }
10328  }
10329 
10330  // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10331  // invalid since the ambiguity can affect the ABI.
10332  auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10333  unsigned &SVEorRVV) {
10334  const VectorType *VecType = SecondType->getAs<VectorType>();
10335  SVEorRVV = 0;
10336  if (FirstType->isSizelessBuiltinType() && VecType) {
10337  if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10339  return true;
10340  if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10342  SVEorRVV = 1;
10343  return true;
10344  }
10345  }
10346 
10347  return false;
10348  };
10349 
10350  unsigned SVEorRVV;
10351  if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10352  IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10353  Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10354  << SVEorRVV << LHSType << RHSType;
10355  return QualType();
10356  }
10357 
10358  // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10359  // invalid since the ambiguity can affect the ABI.
10360  auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10361  unsigned &SVEorRVV) {
10362  const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10363  const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10364 
10365  SVEorRVV = 0;
10366  if (FirstVecType && SecondVecType) {
10367  if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10368  if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10369  SecondVecType->getVectorKind() ==
10371  return true;
10372  if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10373  SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10374  SVEorRVV = 1;
10375  return true;
10376  }
10377  }
10378  return false;
10379  }
10380 
10381  if (SecondVecType &&
10382  SecondVecType->getVectorKind() == VectorKind::Generic) {
10383  if (FirstType->isSVESizelessBuiltinType())
10384  return true;
10385  if (FirstType->isRVVSizelessBuiltinType()) {
10386  SVEorRVV = 1;
10387  return true;
10388  }
10389  }
10390 
10391  return false;
10392  };
10393 
10394  if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10395  IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10396  Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10397  << SVEorRVV << LHSType << RHSType;
10398  return QualType();
10399  }
10400 
10401  // If there's a vector type and a scalar, try to convert the scalar to
10402  // the vector element type and splat.
10403  unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10404  if (!RHSVecType) {
10405  if (isa<ExtVectorType>(LHSVecType)) {
10406  if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10407  LHSVecType->getElementType(), LHSType,
10408  DiagID))
10409  return LHSType;
10410  } else {
10411  if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10412  return LHSType;
10413  }
10414  }
10415  if (!LHSVecType) {
10416  if (isa<ExtVectorType>(RHSVecType)) {
10417  if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10418  LHSType, RHSVecType->getElementType(),
10419  RHSType, DiagID))
10420  return RHSType;
10421  } else {
10422  if (LHS.get()->isLValue() ||
10423  !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10424  return RHSType;
10425  }
10426  }
10427 
10428  // FIXME: The code below also handles conversion between vectors and
10429  // non-scalars, we should break this down into fine grained specific checks
10430  // and emit proper diagnostics.
10431  QualType VecType = LHSVecType ? LHSType : RHSType;
10432  const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10433  QualType OtherType = LHSVecType ? RHSType : LHSType;
10434  ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10435  if (isLaxVectorConversion(OtherType, VecType)) {
10436  if (Context.getTargetInfo().getTriple().isPPC() &&
10437  anyAltivecTypes(RHSType, LHSType) &&
10438  !Context.areCompatibleVectorTypes(RHSType, LHSType))
10439  Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10440  // If we're allowing lax vector conversions, only the total (data) size
10441  // needs to be the same. For non compound assignment, if one of the types is
10442  // scalar, the result is always the vector type.
10443  if (!IsCompAssign) {
10444  *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10445  return VecType;
10446  // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10447  // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10448  // type. Note that this is already done by non-compound assignments in
10449  // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10450  // <1 x T> -> T. The result is also a vector type.
10451  } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10452  (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10453  ExprResult *RHSExpr = &RHS;
10454  *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10455  return VecType;
10456  }
10457  }
10458 
10459  // Okay, the expression is invalid.
10460 
10461  // If there's a non-vector, non-real operand, diagnose that.
10462  if ((!RHSVecType && !RHSType->isRealType()) ||
10463  (!LHSVecType && !LHSType->isRealType())) {
10464  Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10465  << LHSType << RHSType
10466  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10467  return QualType();
10468  }
10469 
10470  // OpenCL V1.1 6.2.6.p1:
10471  // If the operands are of more than one vector type, then an error shall
10472  // occur. Implicit conversions between vector types are not permitted, per
10473  // section 6.2.1.
10474  if (getLangOpts().OpenCL &&
10475  RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10476  LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10477  Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10478  << RHSType;
10479  return QualType();
10480  }
10481 
10482 
10483  // If there is a vector type that is not a ExtVector and a scalar, we reach
10484  // this point if scalar could not be converted to the vector's element type
10485  // without truncation.
10486  if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10487  (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10488  QualType Scalar = LHSVecType ? RHSType : LHSType;
10489  QualType Vector = LHSVecType ? LHSType : RHSType;
10490  unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10491  Diag(Loc,
10492  diag::err_typecheck_vector_not_convertable_implict_truncation)
10493  << ScalarOrVector << Scalar << Vector;
10494 
10495  return QualType();
10496  }
10497 
10498  // Otherwise, use the generic diagnostic.
10499  Diag(Loc, DiagID)
10500  << LHSType << RHSType
10501  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10502  return QualType();
10503 }
10504 
10507  bool IsCompAssign,
10508  ArithConvKind OperationKind) {
10509  if (!IsCompAssign) {
10510  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10511  if (LHS.isInvalid())
10512  return QualType();
10513  }
10514  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10515  if (RHS.isInvalid())
10516  return QualType();
10517 
10518  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10519  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10520 
10521  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10522  const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10523 
10524  unsigned DiagID = diag::err_typecheck_invalid_operands;
10525  if ((OperationKind == ACK_Arithmetic) &&
10526  ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10527  (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10528  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10529  << RHS.get()->getSourceRange();
10530  return QualType();
10531  }
10532 
10533  if (Context.hasSameType(LHSType, RHSType))
10534  return LHSType;
10535 
10536  if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10537  if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10538  return LHSType;
10539  }
10540  if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10541  if (LHS.get()->isLValue() ||
10542  !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10543  return RHSType;
10544  }
10545 
10546  if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10547  (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10548  Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10549  << LHSType << RHSType << LHS.get()->getSourceRange()
10550  << RHS.get()->getSourceRange();
10551  return QualType();
10552  }
10553 
10554  if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10555  Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10556  Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10557  Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10558  << LHSType << RHSType << LHS.get()->getSourceRange()
10559  << RHS.get()->getSourceRange();
10560  return QualType();
10561  }
10562 
10563  if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10564  QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10565  QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10566  bool ScalarOrVector =
10567  LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10568 
10569  Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10570  << ScalarOrVector << Scalar << Vector;
10571 
10572  return QualType();
10573  }
10574 
10575  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10576  << RHS.get()->getSourceRange();
10577  return QualType();
10578 }
10579 
10580 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10581 // expression. These are mainly cases where the null pointer is used as an
10582 // integer instead of a pointer.
10583 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10584  SourceLocation Loc, bool IsCompare) {
10585  // The canonical way to check for a GNU null is with isNullPointerConstant,
10586  // but we use a bit of a hack here for speed; this is a relatively
10587  // hot path, and isNullPointerConstant is slow.
10588  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10589  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10590 
10591  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10592 
10593  // Avoid analyzing cases where the result will either be invalid (and
10594  // diagnosed as such) or entirely valid and not something to warn about.
10595  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10596  NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10597  return;
10598 
10599  // Comparison operations would not make sense with a null pointer no matter
10600  // what the other expression is.
10601  if (!IsCompare) {
10602  S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10603  << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10604  << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10605  return;
10606  }
10607 
10608  // The rest of the operations only make sense with a null pointer
10609  // if the other expression is a pointer.
10610  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10611  NonNullType->canDecayToPointerType())
10612  return;
10613 
10614  S.Diag(Loc, diag::warn_null_in_comparison_operation)
10615  << LHSNull /* LHS is NULL */ << NonNullType
10616  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10617 }
10618 
10620  SourceLocation Loc) {
10621  const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10622  const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10623  if (!LUE || !RUE)
10624  return;
10625  if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10626  RUE->getKind() != UETT_SizeOf)
10627  return;
10628 
10629  const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10630  QualType LHSTy = LHSArg->getType();
10631  QualType RHSTy;
10632 
10633  if (RUE->isArgumentType())
10634  RHSTy = RUE->getArgumentType().getNonReferenceType();
10635  else
10636  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10637 
10638  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10639  if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10640  return;
10641 
10642  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10643  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10644  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10645  S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10646  << LHSArgDecl;
10647  }
10648  } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10649  QualType ArrayElemTy = ArrayTy->getElementType();
10650  if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10651  ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10652  RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10653  S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10654  return;
10655  S.Diag(Loc, diag::warn_division_sizeof_array)
10656  << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10657  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10658  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10659  S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10660  << LHSArgDecl;
10661  }
10662 
10663  S.Diag(Loc, diag::note_precedence_silence) << RHS;
10664  }
10665 }
10666 
10668  ExprResult &RHS,
10669  SourceLocation Loc, bool IsDiv) {
10670  // Check for division/remainder by zero.
10671  Expr::EvalResult RHSValue;
10672  if (!RHS.get()->isValueDependent() &&
10673  RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10674  RHSValue.Val.getInt() == 0)
10675  S.DiagRuntimeBehavior(Loc, RHS.get(),
10676  S.PDiag(diag::warn_remainder_division_by_zero)
10677  << IsDiv << RHS.get()->getSourceRange());
10678 }
10679 
10682  bool IsCompAssign, bool IsDiv) {
10683  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10684 
10685  QualType LHSTy = LHS.get()->getType();
10686  QualType RHSTy = RHS.get()->getType();
10687  if (LHSTy->isVectorType() || RHSTy->isVectorType())
10688  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10689  /*AllowBothBool*/ getLangOpts().AltiVec,
10690  /*AllowBoolConversions*/ false,
10691  /*AllowBooleanOperation*/ false,
10692  /*ReportInvalid*/ true);
10693  if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10694  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10695  ACK_Arithmetic);
10696  if (!IsDiv &&
10697  (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10698  return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10699  // For division, only matrix-by-scalar is supported. Other combinations with
10700  // matrix types are invalid.
10701  if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10702  return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10703 
10704  QualType compType = UsualArithmeticConversions(
10705  LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10706  if (LHS.isInvalid() || RHS.isInvalid())
10707  return QualType();
10708 
10709 
10710  if (compType.isNull() || !compType->isArithmeticType())
10711  return InvalidOperands(Loc, LHS, RHS);
10712  if (IsDiv) {
10713  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10714  DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10715  }
10716  return compType;
10717 }
10718 
10720  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10721  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10722 
10723  if (LHS.get()->getType()->isVectorType() ||
10724  RHS.get()->getType()->isVectorType()) {
10725  if (LHS.get()->getType()->hasIntegerRepresentation() &&
10726  RHS.get()->getType()->hasIntegerRepresentation())
10727  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10728  /*AllowBothBool*/ getLangOpts().AltiVec,
10729  /*AllowBoolConversions*/ false,
10730  /*AllowBooleanOperation*/ false,
10731  /*ReportInvalid*/ true);
10732  return InvalidOperands(Loc, LHS, RHS);
10733  }
10734 
10735  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10736  RHS.get()->getType()->isSveVLSBuiltinType()) {
10737  if (LHS.get()->getType()->hasIntegerRepresentation() &&
10738  RHS.get()->getType()->hasIntegerRepresentation())
10739  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10740  ACK_Arithmetic);
10741 
10742  return InvalidOperands(Loc, LHS, RHS);
10743  }
10744 
10745  QualType compType = UsualArithmeticConversions(
10746  LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10747  if (LHS.isInvalid() || RHS.isInvalid())
10748  return QualType();
10749 
10750  if (compType.isNull() || !compType->isIntegerType())
10751  return InvalidOperands(Loc, LHS, RHS);
10752  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10753  return compType;
10754 }
10755 
10756 /// Diagnose invalid arithmetic on two void pointers.
10758  Expr *LHSExpr, Expr *RHSExpr) {
10759  S.Diag(Loc, S.getLangOpts().CPlusPlus
10760  ? diag::err_typecheck_pointer_arith_void_type
10761  : diag::ext_gnu_void_ptr)
10762  << 1 /* two pointers */ << LHSExpr->getSourceRange()
10763  << RHSExpr->getSourceRange();
10764 }
10765 
10766 /// Diagnose invalid arithmetic on a void pointer.
10768  Expr *Pointer) {
10769  S.Diag(Loc, S.getLangOpts().CPlusPlus
10770  ? diag::err_typecheck_pointer_arith_void_type
10771  : diag::ext_gnu_void_ptr)
10772  << 0 /* one pointer */ << Pointer->getSourceRange();
10773 }
10774 
10775 /// Diagnose invalid arithmetic on a null pointer.
10776 ///
10777 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10778 /// idiom, which we recognize as a GNU extension.
10779 ///
10781  Expr *Pointer, bool IsGNUIdiom) {
10782  if (IsGNUIdiom)
10783  S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10784  << Pointer->getSourceRange();
10785  else
10786  S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10787  << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10788 }
10789 
10790 /// Diagnose invalid subraction on a null pointer.
10791 ///
10793  Expr *Pointer, bool BothNull) {
10794  // Null - null is valid in C++ [expr.add]p7
10795  if (BothNull && S.getLangOpts().CPlusPlus)
10796  return;
10797 
10798  // Is this s a macro from a system header?
10800  return;
10801 
10802  S.DiagRuntimeBehavior(Loc, Pointer,
10803  S.PDiag(diag::warn_pointer_sub_null_ptr)
10804  << S.getLangOpts().CPlusPlus
10805  << Pointer->getSourceRange());
10806 }
10807 
10808 /// Diagnose invalid arithmetic on two function pointers.
10810  Expr *LHS, Expr *RHS) {
10811  assert(LHS->getType()->isAnyPointerType());
10812  assert(RHS->getType()->isAnyPointerType());
10813  S.Diag(Loc, S.getLangOpts().CPlusPlus
10814  ? diag::err_typecheck_pointer_arith_function_type
10815  : diag::ext_gnu_ptr_func_arith)
10816  << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10817  // We only show the second type if it differs from the first.
10819  RHS->getType())
10820  << RHS->getType()->getPointeeType()
10821  << LHS->getSourceRange() << RHS->getSourceRange();
10822 }
10823 
10824 /// Diagnose invalid arithmetic on a function pointer.
10826  Expr *Pointer) {
10827  assert(Pointer->getType()->isAnyPointerType());
10828  S.Diag(Loc, S.getLangOpts().CPlusPlus
10829  ? diag::err_typecheck_pointer_arith_function_type
10830  : diag::ext_gnu_ptr_func_arith)
10831  << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10832  << 0 /* one pointer, so only one type */
10833  << Pointer->getSourceRange();
10834 }
10835 
10836 /// Emit error if Operand is incomplete pointer type
10837 ///
10838 /// \returns True if pointer has incomplete type
10840  Expr *Operand) {
10841  QualType ResType = Operand->getType();
10842  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10843  ResType = ResAtomicType->getValueType();
10844 
10845  assert(ResType->isAnyPointerType());
10846  QualType PointeeTy = ResType->getPointeeType();
10847  return S.RequireCompleteSizedType(
10848  Loc, PointeeTy,
10849  diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10850  Operand->getSourceRange());
10851 }
10852 
10853 /// Check the validity of an arithmetic pointer operand.
10854 ///
10855 /// If the operand has pointer type, this code will check for pointer types
10856 /// which are invalid in arithmetic operations. These will be diagnosed
10857 /// appropriately, including whether or not the use is supported as an
10858 /// extension.
10859 ///
10860 /// \returns True when the operand is valid to use (even if as an extension).
10862  Expr *Operand) {
10863  QualType ResType = Operand->getType();
10864  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10865  ResType = ResAtomicType->getValueType();
10866 
10867  if (!ResType->isAnyPointerType()) return true;
10868 
10869  QualType PointeeTy = ResType->getPointeeType();
10870  if (PointeeTy->isVoidType()) {
10871  diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10872  return !S.getLangOpts().CPlusPlus;
10873  }
10874  if (PointeeTy->isFunctionType()) {
10876  return !S.getLangOpts().CPlusPlus;
10877  }
10878 
10879  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10880 
10881  return true;
10882 }
10883 
10884 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10885 /// operands.
10886 ///
10887 /// This routine will diagnose any invalid arithmetic on pointer operands much
10888 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10889 /// for emitting a single diagnostic even for operations where both LHS and RHS
10890 /// are (potentially problematic) pointers.
10891 ///
10892 /// \returns True when the operand is valid to use (even if as an extension).
10894  Expr *LHSExpr, Expr *RHSExpr) {
10895  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10896  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10897  if (!isLHSPointer && !isRHSPointer) return true;
10898 
10899  QualType LHSPointeeTy, RHSPointeeTy;
10900  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10901  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10902 
10903  // if both are pointers check if operation is valid wrt address spaces
10904  if (isLHSPointer && isRHSPointer) {
10905  if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10906  S.Diag(Loc,
10907  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10908  << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10909  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10910  return false;
10911  }
10912  }
10913 
10914  // Check for arithmetic on pointers to incomplete types.
10915  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10916  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10917  if (isLHSVoidPtr || isRHSVoidPtr) {
10918  if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10919  else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10920  else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10921 
10922  return !S.getLangOpts().CPlusPlus;
10923  }
10924 
10925  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10926  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10927  if (isLHSFuncPtr || isRHSFuncPtr) {
10928  if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10929  else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10930  RHSExpr);
10931  else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10932 
10933  return !S.getLangOpts().CPlusPlus;
10934  }
10935 
10936  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10937  return false;
10938  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10939  return false;
10940 
10941  return true;
10942 }
10943 
10944 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10945 /// literal.
10946 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10947  Expr *LHSExpr, Expr *RHSExpr) {
10948  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10949  Expr* IndexExpr = RHSExpr;
10950  if (!StrExpr) {
10951  StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10952  IndexExpr = LHSExpr;
10953  }
10954 
10955  bool IsStringPlusInt = StrExpr &&
10957  if (!IsStringPlusInt || IndexExpr->isValueDependent())
10958  return;
10959 
10960  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10961  Self.Diag(OpLoc, diag::warn_string_plus_int)
10962  << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10963 
10964  // Only print a fixit for "str" + int, not for int + "str".
10965  if (IndexExpr == RHSExpr) {
10966  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10967  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10968  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10970  << FixItHint::CreateInsertion(EndLoc, "]");
10971  } else
10972  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10973 }
10974 
10975 /// Emit a warning when adding a char literal to a string.
10976 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10977  Expr *LHSExpr, Expr *RHSExpr) {
10978  const Expr *StringRefExpr = LHSExpr;
10979  const CharacterLiteral *CharExpr =
10980  dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10981 
10982  if (!CharExpr) {
10983  CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10984  StringRefExpr = RHSExpr;
10985  }
10986 
10987  if (!CharExpr || !StringRefExpr)
10988  return;
10989 
10990  const QualType StringType = StringRefExpr->getType();
10991 
10992  // Return if not a PointerType.
10993  if (!StringType->isAnyPointerType())
10994  return;
10995 
10996  // Return if not a CharacterType.
10997  if (!StringType->getPointeeType()->isAnyCharacterType())
10998  return;
10999 
11000  ASTContext &Ctx = Self.getASTContext();
11001  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11002 
11003  const QualType CharType = CharExpr->getType();
11004  if (!CharType->isAnyCharacterType() &&
11005  CharType->isIntegerType() &&
11006  llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11007  Self.Diag(OpLoc, diag::warn_string_plus_char)
11008  << DiagRange << Ctx.CharTy;
11009  } else {
11010  Self.Diag(OpLoc, diag::warn_string_plus_char)
11011  << DiagRange << CharExpr->getType();
11012  }
11013 
11014  // Only print a fixit for str + char, not for char + str.
11015  if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11016  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11017  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11018  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11020  << FixItHint::CreateInsertion(EndLoc, "]");
11021  } else {
11022  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11023  }
11024 }
11025 
11026 /// Emit error when two pointers are incompatible.
11028  Expr *LHSExpr, Expr *RHSExpr) {
11029  assert(LHSExpr->getType()->isAnyPointerType());
11030  assert(RHSExpr->getType()->isAnyPointerType());
11031  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11032  << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11033  << RHSExpr->getSourceRange();
11034 }
11035 
11036 // C99 6.5.6
11039  QualType* CompLHSTy) {
11040  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11041 
11042  if (LHS.get()->getType()->isVectorType() ||
11043  RHS.get()->getType()->isVectorType()) {
11044  QualType compType =
11045  CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11046  /*AllowBothBool*/ getLangOpts().AltiVec,
11047  /*AllowBoolConversions*/ getLangOpts().ZVector,
11048  /*AllowBooleanOperation*/ false,
11049  /*ReportInvalid*/ true);
11050  if (CompLHSTy) *CompLHSTy = compType;
11051  return compType;
11052  }
11053 
11054  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11055  RHS.get()->getType()->isSveVLSBuiltinType()) {
11056  QualType compType =
11057  CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11058  if (CompLHSTy)
11059  *CompLHSTy = compType;
11060  return compType;
11061  }
11062 
11063  if (LHS.get()->getType()->isConstantMatrixType() ||
11064  RHS.get()->getType()->isConstantMatrixType()) {
11065  QualType compType =
11066  CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11067  if (CompLHSTy)
11068  *CompLHSTy = compType;
11069  return compType;
11070  }
11071 
11072  QualType compType = UsualArithmeticConversions(
11073  LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11074  if (LHS.isInvalid() || RHS.isInvalid())
11075  return QualType();
11076 
11077  // Diagnose "string literal" '+' int and string '+' "char literal".
11078  if (Opc == BO_Add) {
11079  diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11080  diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11081  }
11082 
11083  // handle the common case first (both operands are arithmetic).
11084  if (!compType.isNull() && compType->isArithmeticType()) {
11085  if (CompLHSTy) *CompLHSTy = compType;
11086  return compType;
11087  }
11088 
11089  // Type-checking. Ultimately the pointer's going to be in PExp;
11090  // note that we bias towards the LHS being the pointer.
11091  Expr *PExp = LHS.get(), *IExp = RHS.get();
11092 
11093  bool isObjCPointer;
11094  if (PExp->getType()->isPointerType()) {
11095  isObjCPointer = false;
11096  } else if (PExp->getType()->isObjCObjectPointerType()) {
11097  isObjCPointer = true;
11098  } else {
11099  std::swap(PExp, IExp);
11100  if (PExp->getType()->isPointerType()) {
11101  isObjCPointer = false;
11102  } else if (PExp->getType()->isObjCObjectPointerType()) {
11103  isObjCPointer = true;
11104  } else {
11105  return InvalidOperands(Loc, LHS, RHS);
11106  }
11107  }
11108  assert(PExp->getType()->isAnyPointerType());
11109 
11110  if (!IExp->getType()->isIntegerType())
11111  return InvalidOperands(Loc, LHS, RHS);
11112 
11113  // Adding to a null pointer results in undefined behavior.
11116  // In C++ adding zero to a null pointer is defined.
11117  Expr::EvalResult KnownVal;
11118  if (!getLangOpts().CPlusPlus ||
11119  (!IExp->isValueDependent() &&
11120  (!IExp->EvaluateAsInt(KnownVal, Context) ||
11121  KnownVal.Val.getInt() != 0))) {
11122  // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11124  Context, BO_Add, PExp, IExp);
11125  diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11126  }
11127  }
11128 
11129  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11130  return QualType();
11131 
11132  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11133  return QualType();
11134 
11135  // Check array bounds for pointer arithemtic
11136  CheckArrayAccess(PExp, IExp);
11137 
11138  if (CompLHSTy) {
11139  QualType LHSTy = Context.isPromotableBitField(LHS.get());
11140  if (LHSTy.isNull()) {
11141  LHSTy = LHS.get()->getType();
11142  if (Context.isPromotableIntegerType(LHSTy))
11143  LHSTy = Context.getPromotedIntegerType(LHSTy);
11144  }
11145  *CompLHSTy = LHSTy;
11146  }
11147 
11148  return PExp->getType();
11149 }
11150 
11151 // C99 6.5.6
11154  QualType* CompLHSTy) {
11155  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11156 
11157  if (LHS.get()->getType()->isVectorType() ||
11158  RHS.get()->getType()->isVectorType()) {
11159  QualType compType =
11160  CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11161  /*AllowBothBool*/ getLangOpts().AltiVec,
11162  /*AllowBoolConversions*/ getLangOpts().ZVector,
11163  /*AllowBooleanOperation*/ false,
11164  /*ReportInvalid*/ true);
11165  if (CompLHSTy) *CompLHSTy = compType;
11166  return compType;
11167  }
11168 
11169  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11170  RHS.get()->getType()->isSveVLSBuiltinType()) {
11171  QualType compType =
11172  CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11173  if (CompLHSTy)
11174  *CompLHSTy = compType;
11175  return compType;
11176  }
11177 
11178  if (LHS.get()->getType()->isConstantMatrixType() ||
11179  RHS.get()->getType()->isConstantMatrixType()) {
11180  QualType compType =
11181  CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11182  if (CompLHSTy)
11183  *CompLHSTy = compType;
11184  return compType;
11185  }
11186 
11187  QualType compType = UsualArithmeticConversions(
11188  LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11189  if (LHS.isInvalid() || RHS.isInvalid())
11190  return QualType();
11191 
11192  // Enforce type constraints: C99 6.5.6p3.
11193 
11194  // Handle the common case first (both operands are arithmetic).
11195  if (!compType.isNull() && compType->isArithmeticType()) {
11196  if (CompLHSTy) *CompLHSTy = compType;
11197  return compType;
11198  }
11199 
11200  // Either ptr - int or ptr - ptr.
11201  if (LHS.get()->getType()->isAnyPointerType()) {
11202  QualType lpointee = LHS.get()->getType()->getPointeeType();
11203 
11204  // Diagnose bad cases where we step over interface counts.
11205  if (LHS.get()->getType()->isObjCObjectPointerType() &&
11206  checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11207  return QualType();
11208 
11209  // The result type of a pointer-int computation is the pointer type.
11210  if (RHS.get()->getType()->isIntegerType()) {
11211  // Subtracting from a null pointer should produce a warning.
11212  // The last argument to the diagnose call says this doesn't match the
11213  // GNU int-to-pointer idiom.
11214  if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11216  // In C++ adding zero to a null pointer is defined.
11217  Expr::EvalResult KnownVal;
11218  if (!getLangOpts().CPlusPlus ||
11219  (!RHS.get()->isValueDependent() &&
11220  (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11221  KnownVal.Val.getInt() != 0))) {
11222  diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11223  }
11224  }
11225 
11226  if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11227  return QualType();
11228 
11229  // Check array bounds for pointer arithemtic
11230  CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11231  /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11232 
11233  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11234  return LHS.get()->getType();
11235  }
11236 
11237  // Handle pointer-pointer subtractions.
11238  if (const PointerType *RHSPTy
11239  = RHS.get()->getType()->getAs<PointerType>()) {
11240  QualType rpointee = RHSPTy->getPointeeType();
11241 
11242  if (getLangOpts().CPlusPlus) {
11243  // Pointee types must be the same: C++ [expr.add]
11244  if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11245  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11246  }
11247  } else {
11248  // Pointee types must be compatible C99 6.5.6p3
11249  if (!Context.typesAreCompatible(
11250  Context.getCanonicalType(lpointee).getUnqualifiedType(),
11251  Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11252  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11253  return QualType();
11254  }
11255  }
11256 
11258  LHS.get(), RHS.get()))
11259  return QualType();
11260 
11261  bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11263  bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11265 
11266  // Subtracting nullptr or from nullptr is suspect
11267  if (LHSIsNullPtr)
11268  diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11269  if (RHSIsNullPtr)
11270  diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11271 
11272  // The pointee type may have zero size. As an extension, a structure or
11273  // union may have zero size or an array may have zero length. In this
11274  // case subtraction does not make sense.
11275  if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11276  CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11277  if (ElementSize.isZero()) {
11278  Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11279  << rpointee.getUnqualifiedType()
11280  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11281  }
11282  }
11283 
11284  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11285  return Context.getPointerDiffType();
11286  }
11287  }
11288 
11289  return InvalidOperands(Loc, LHS, RHS);
11290 }
11291 
11293  if (const EnumType *ET = T->getAs<EnumType>())
11294  return ET->getDecl()->isScoped();
11295  return false;
11296 }
11297 
11300  QualType LHSType) {
11301  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11302  // so skip remaining warnings as we don't want to modify values within Sema.
11303  if (S.getLangOpts().OpenCL)
11304  return;
11305 
11306  // Check right/shifter operand
11307  Expr::EvalResult RHSResult;
11308  if (RHS.get()->isValueDependent() ||
11309  !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11310  return;
11311  llvm::APSInt Right = RHSResult.Val.getInt();
11312 
11313  if (Right.isNegative()) {
11314  S.DiagRuntimeBehavior(Loc, RHS.get(),
11315  S.PDiag(diag::warn_shift_negative)
11316  << RHS.get()->getSourceRange());
11317  return;
11318  }
11319 
11320  QualType LHSExprType = LHS.get()->getType();
11321  uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11322  if (LHSExprType->isBitIntType())
11323  LeftSize = S.Context.getIntWidth(LHSExprType);
11324  else if (LHSExprType->isFixedPointType()) {
11325  auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11326  LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11327  }
11328  if (Right.uge(LeftSize)) {
11329  S.DiagRuntimeBehavior(Loc, RHS.get(),
11330  S.PDiag(diag::warn_shift_gt_typewidth)
11331  << RHS.get()->getSourceRange());
11332  return;
11333  }
11334 
11335  // FIXME: We probably need to handle fixed point types specially here.
11336  if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11337  return;
11338 
11339  // When left shifting an ICE which is signed, we can check for overflow which
11340  // according to C++ standards prior to C++2a has undefined behavior
11341  // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11342  // more than the maximum value representable in the result type, so never
11343  // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11344  // expression is still probably a bug.)
11345  Expr::EvalResult LHSResult;
11346  if (LHS.get()->isValueDependent() ||
11347  LHSType->hasUnsignedIntegerRepresentation() ||
11348  !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11349  return;
11350  llvm::APSInt Left = LHSResult.Val.getInt();
11351 
11352  // Don't warn if signed overflow is defined, then all the rest of the
11353  // diagnostics will not be triggered because the behavior is defined.
11354  // Also don't warn in C++20 mode (and newer), as signed left shifts
11355  // always wrap and never overflow.
11356  if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11357  return;
11358 
11359  // If LHS does not have a non-negative value then, the
11360  // behavior is undefined before C++2a. Warn about it.
11361  if (Left.isNegative()) {
11362  S.DiagRuntimeBehavior(Loc, LHS.get(),
11363  S.PDiag(diag::warn_shift_lhs_negative)
11364  << LHS.get()->getSourceRange());
11365  return;
11366  }
11367 
11368  llvm::APInt ResultBits =
11369  static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11370  if (ResultBits.ule(LeftSize))
11371  return;
11372  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11373  Result = Result.shl(Right);
11374 
11375  // Print the bit representation of the signed integer as an unsigned
11376  // hexadecimal number.
11377  SmallString<40> HexResult;
11378  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11379 
11380  // If we are only missing a sign bit, this is less likely to result in actual
11381  // bugs -- if the result is cast back to an unsigned type, it will have the
11382  // expected value. Thus we place this behind a different warning that can be
11383  // turned off separately if needed.
11384  if (ResultBits - 1 == LeftSize) {
11385  S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11386  << HexResult << LHSType
11387  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11388  return;
11389  }
11390 
11391  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11392  << HexResult.str() << Result.getSignificantBits() << LHSType
11393  << Left.getBitWidth() << LHS.get()->getSourceRange()
11394  << RHS.get()->getSourceRange();
11395 }
11396 
11397 /// Return the resulting type when a vector is shifted
11398 /// by a scalar or vector shift amount.
11400  SourceLocation Loc, bool IsCompAssign) {
11401  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11402  if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11403  !LHS.get()->getType()->isVectorType()) {
11404  S.Diag(Loc, diag::err_shift_rhs_only_vector)
11405  << RHS.get()->getType() << LHS.get()->getType()
11406  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11407  return QualType();
11408  }
11409 
11410  if (!IsCompAssign) {
11411  LHS = S.UsualUnaryConversions(LHS.get());
11412  if (LHS.isInvalid()) return QualType();
11413  }
11414 
11415  RHS = S.UsualUnaryConversions(RHS.get());
11416  if (RHS.isInvalid()) return QualType();
11417 
11418  QualType LHSType = LHS.get()->getType();
11419  // Note that LHS might be a scalar because the routine calls not only in
11420  // OpenCL case.
11421  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11422  QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11423 
11424  // Note that RHS might not be a vector.
11425  QualType RHSType = RHS.get()->getType();
11426  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11427  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11428 
11429  // Do not allow shifts for boolean vectors.
11430  if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11431  (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11432  S.Diag(Loc, diag::err_typecheck_invalid_operands)
11433  << LHS.get()->getType() << RHS.get()->getType()
11434  << LHS.get()->getSourceRange();
11435  return QualType();
11436  }
11437 
11438  // The operands need to be integers.
11439  if (!LHSEleType->isIntegerType()) {
11440  S.Diag(Loc, diag::err_typecheck_expect_int)
11441  << LHS.get()->getType() << LHS.get()->getSourceRange();
11442  return QualType();
11443  }
11444 
11445  if (!RHSEleType->isIntegerType()) {
11446  S.Diag(Loc, diag::err_typecheck_expect_int)
11447  << RHS.get()->getType() << RHS.get()->getSourceRange();
11448  return QualType();
11449  }
11450 
11451  if (!LHSVecTy) {
11452  assert(RHSVecTy);
11453  if (IsCompAssign)
11454  return RHSType;
11455  if (LHSEleType != RHSEleType) {
11456  LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11457  LHSEleType = RHSEleType;
11458  }
11459  QualType VecTy =
11460  S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11461  LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11462  LHSType = VecTy;
11463  } else if (RHSVecTy) {
11464  // OpenCL v1.1 s6.3.j says that for vector types, the operators
11465  // are applied component-wise. So if RHS is a vector, then ensure
11466  // that the number of elements is the same as LHS...
11467  if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11468  S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11469  << LHS.get()->getType() << RHS.get()->getType()
11470  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11471  return QualType();
11472  }
11473  if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11474  const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11475  const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11476  if (LHSBT != RHSBT &&
11477  S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11478  S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11479  << LHS.get()->getType() << RHS.get()->getType()
11480  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11481  }
11482  }
11483  } else {
11484  // ...else expand RHS to match the number of elements in LHS.
11485  QualType VecTy =
11486  S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11487  RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11488  }
11489 
11490  return LHSType;
11491 }
11492 
11495  bool IsCompAssign) {
11496  if (!IsCompAssign) {
11497  LHS = S.UsualUnaryConversions(LHS.get());
11498  if (LHS.isInvalid())
11499  return QualType();
11500  }
11501 
11502  RHS = S.UsualUnaryConversions(RHS.get());
11503  if (RHS.isInvalid())
11504  return QualType();
11505 
11506  QualType LHSType = LHS.get()->getType();
11507  const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11508  QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11509  ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11510  : LHSType;
11511 
11512  // Note that RHS might not be a vector
11513  QualType RHSType = RHS.get()->getType();
11514  const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11515  QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11516  ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11517  : RHSType;
11518 
11519  if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11520  (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11521  S.Diag(Loc, diag::err_typecheck_invalid_operands)
11522  << LHSType << RHSType << LHS.get()->getSourceRange();
11523  return QualType();
11524  }
11525 
11526  if (!LHSEleType->isIntegerType()) {
11527  S.Diag(Loc, diag::err_typecheck_expect_int)
11528  << LHS.get()->getType() << LHS.get()->getSourceRange();
11529  return QualType();
11530  }
11531 
11532  if (!RHSEleType->isIntegerType()) {
11533  S.Diag(Loc, diag::err_typecheck_expect_int)
11534  << RHS.get()->getType() << RHS.get()->getSourceRange();
11535  return QualType();
11536  }
11537 
11538  if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11539  (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11540  S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11541  S.Diag(Loc, diag::err_typecheck_invalid_operands)
11542  << LHSType << RHSType << LHS.get()->getSourceRange()
11543  << RHS.get()->getSourceRange();
11544  return QualType();
11545  }
11546 
11547  if (!LHSType->isSveVLSBuiltinType()) {
11548  assert(RHSType->isSveVLSBuiltinType());
11549  if (IsCompAssign)
11550  return RHSType;
11551  if (LHSEleType != RHSEleType) {
11552  LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11553  LHSEleType = RHSEleType;
11554  }
11555  const llvm::ElementCount VecSize =
11556  S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11557  QualType VecTy =
11558  S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11559  LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11560  LHSType = VecTy;
11561  } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11562  if (S.Context.getTypeSize(RHSBuiltinTy) !=
11563  S.Context.getTypeSize(LHSBuiltinTy)) {
11564  S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11565  << LHSType << RHSType << LHS.get()->getSourceRange()
11566  << RHS.get()->getSourceRange();
11567  return QualType();
11568  }
11569  } else {
11570  const llvm::ElementCount VecSize =
11571  S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11572  if (LHSEleType != RHSEleType) {
11573  RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11574  RHSEleType = LHSEleType;
11575  }
11576  QualType VecTy =
11577  S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11578  RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11579  }
11580 
11581  return LHSType;
11582 }
11583 
11584 // C99 6.5.7
11587  bool IsCompAssign) {
11588  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11589 
11590  // Vector shifts promote their scalar inputs to vector type.
11591  if (LHS.get()->getType()->isVectorType() ||
11592  RHS.get()->getType()->isVectorType()) {
11593  if (LangOpts.ZVector) {
11594  // The shift operators for the z vector extensions work basically
11595  // like general shifts, except that neither the LHS nor the RHS is
11596  // allowed to be a "vector bool".
11597  if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11598  if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11599  return InvalidOperands(Loc, LHS, RHS);
11600  if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11601  if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11602  return InvalidOperands(Loc, LHS, RHS);
11603  }
11604  return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11605  }
11606 
11607  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11608  RHS.get()->getType()->isSveVLSBuiltinType())
11609  return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11610 
11611  // Shifts don't perform usual arithmetic conversions, they just do integer
11612  // promotions on each operand. C99 6.5.7p3
11613 
11614  // For the LHS, do usual unary conversions, but then reset them away
11615  // if this is a compound assignment.
11616  ExprResult OldLHS = LHS;
11617  LHS = UsualUnaryConversions(LHS.get());
11618  if (LHS.isInvalid())
11619  return QualType();
11620  QualType LHSType = LHS.get()->getType();
11621  if (IsCompAssign) LHS = OldLHS;
11622 
11623  // The RHS is simpler.
11624  RHS = UsualUnaryConversions(RHS.get());
11625  if (RHS.isInvalid())
11626  return QualType();
11627  QualType RHSType = RHS.get()->getType();
11628 
11629  // C99 6.5.7p2: Each of the operands shall have integer type.
11630  // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11631  if ((!LHSType->isFixedPointOrIntegerType() &&
11632  !LHSType->hasIntegerRepresentation()) ||
11633  !RHSType->hasIntegerRepresentation())
11634  return InvalidOperands(Loc, LHS, RHS);
11635 
11636  // C++0x: Don't allow scoped enums. FIXME: Use something better than
11637  // hasIntegerRepresentation() above instead of this.
11638  if (isScopedEnumerationType(LHSType) ||
11639  isScopedEnumerationType(RHSType)) {
11640  return InvalidOperands(Loc, LHS, RHS);
11641  }
11642  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11643 
11644  // "The type of the result is that of the promoted left operand."
11645  return LHSType;
11646 }
11647 
11648 /// Diagnose bad pointer comparisons.
11650  ExprResult &LHS, ExprResult &RHS,
11651  bool IsError) {
11652  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11653  : diag::ext_typecheck_comparison_of_distinct_pointers)
11654  << LHS.get()->getType() << RHS.get()->getType()
11655  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11656 }
11657 
11658 /// Returns false if the pointers are converted to a composite type,
11659 /// true otherwise.
11661  ExprResult &LHS, ExprResult &RHS) {
11662  // C++ [expr.rel]p2:
11663  // [...] Pointer conversions (4.10) and qualification
11664  // conversions (4.4) are performed on pointer operands (or on
11665  // a pointer operand and a null pointer constant) to bring
11666  // them to their composite pointer type. [...]
11667  //
11668  // C++ [expr.eq]p1 uses the same notion for (in)equality
11669  // comparisons of pointers.
11670 
11671  QualType LHSType = LHS.get()->getType();
11672  QualType RHSType = RHS.get()->getType();
11673  assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11674  LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11675 
11676  QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11677  if (T.isNull()) {
11678  if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11679  (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11680  diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11681  else
11682  S.InvalidOperands(Loc, LHS, RHS);
11683  return true;
11684  }
11685 
11686  return false;
11687 }
11688 
11690  ExprResult &LHS,
11691  ExprResult &RHS,
11692  bool IsError) {
11693  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11694  : diag::ext_typecheck_comparison_of_fptr_to_void)
11695  << LHS.get()->getType() << RHS.get()->getType()
11696  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11697 }
11698 
11700  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11701  case Stmt::ObjCArrayLiteralClass:
11702  case Stmt::ObjCDictionaryLiteralClass:
11703  case Stmt::ObjCStringLiteralClass:
11704  case Stmt::ObjCBoxedExprClass:
11705  return true;
11706  default:
11707  // Note that ObjCBoolLiteral is NOT an object literal!
11708  return false;
11709  }
11710 }
11711 
11712 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11713  const ObjCObjectPointerType *Type =
11714  LHS->getType()->getAs<ObjCObjectPointerType>();
11715 
11716  // If this is not actually an Objective-C object, bail out.
11717  if (!Type)
11718  return false;
11719 
11720  // Get the LHS object's interface type.
11721  QualType InterfaceType = Type->getPointeeType();
11722 
11723  // If the RHS isn't an Objective-C object, bail out.
11724  if (!RHS->getType()->isObjCObjectPointerType())
11725  return false;
11726 
11727  // Try to find the -isEqual: method.
11728  Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11729  ObjCMethodDecl *Method =
11730  S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11731  /*IsInstance=*/true);
11732  if (!Method) {
11733  if (Type->isObjCIdType()) {
11734  // For 'id', just check the global pool.
11735  Method =
11737  /*receiverId=*/true);
11738  } else {
11739  // Check protocols.
11740  Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11741  /*IsInstance=*/true);
11742  }
11743  }
11744 
11745  if (!Method)
11746  return false;
11747 
11748  QualType T = Method->parameters()[0]->getType();
11749  if (!T->isObjCObjectPointerType())
11750  return false;
11751 
11752  QualType R = Method->getReturnType();
11753  if (!R->isScalarType())
11754  return false;
11755 
11756  return true;
11757 }
11758 
11760  ExprResult &LHS, ExprResult &RHS,
11762  Expr *Literal;
11763  Expr *Other;
11764  if (isObjCObjectLiteral(LHS)) {
11765  Literal = LHS.get();
11766  Other = RHS.get();
11767  } else {
11768  Literal = RHS.get();
11769  Other = LHS.get();
11770  }
11771 
11772  // Don't warn on comparisons against nil.
11773  Other = Other->IgnoreParenCasts();
11774  if (Other->isNullPointerConstant(S.getASTContext(),
11776  return;
11777 
11778  // This should be kept in sync with warn_objc_literal_comparison.
11779  // LK_String should always be after the other literals, since it has its own
11780  // warning flag.
11782  assert(LiteralKind != SemaObjC::LK_Block);
11783  if (LiteralKind == SemaObjC::LK_None) {
11784  llvm_unreachable("Unknown Objective-C object literal kind");
11785  }
11786 
11787  if (LiteralKind == SemaObjC::LK_String)
11788  S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11789  << Literal->getSourceRange();
11790  else
11791  S.Diag(Loc, diag::warn_objc_literal_comparison)
11792  << LiteralKind << Literal->getSourceRange();
11793 
11794  if (BinaryOperator::isEqualityOp(Opc) &&
11795  hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11796  SourceLocation Start = LHS.get()->getBeginLoc();
11798  CharSourceRange OpRange =
11800 
11801  S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11802  << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11803  << FixItHint::CreateReplacement(OpRange, " isEqual:")
11805  }
11806 }
11807 
11808 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11811  BinaryOperatorKind Opc) {
11812  // Check that left hand side is !something.
11813  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11814  if (!UO || UO->getOpcode() != UO_LNot) return;
11815 
11816  // Only check if the right hand side is non-bool arithmetic type.
11817  if (RHS.get()->isKnownToHaveBooleanValue()) return;
11818 
11819  // Make sure that the something in !something is not bool.
11820  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11821  if (SubExpr->isKnownToHaveBooleanValue()) return;
11822 
11823  // Emit warning.
11824  bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11825  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11826  << Loc << IsBitwiseOp;
11827 
11828  // First note suggest !(x < y)
11829  SourceLocation FirstOpen = SubExpr->getBeginLoc();
11830  SourceLocation FirstClose = RHS.get()->getEndLoc();
11831  FirstClose = S.getLocForEndOfToken(FirstClose);
11832  if (FirstClose.isInvalid())
11833  FirstOpen = SourceLocation();
11834  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11835  << IsBitwiseOp
11836  << FixItHint::CreateInsertion(FirstOpen, "(")
11837  << FixItHint::CreateInsertion(FirstClose, ")");
11838 
11839  // Second note suggests (!x) < y
11840  SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11841  SourceLocation SecondClose = LHS.get()->getEndLoc();
11842  SecondClose = S.getLocForEndOfToken(SecondClose);
11843  if (SecondClose.isInvalid())
11844  SecondOpen = SourceLocation();
11845  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11846  << FixItHint::CreateInsertion(SecondOpen, "(")
11847  << FixItHint::CreateInsertion(SecondClose, ")");
11848 }
11849 
11850 // Returns true if E refers to a non-weak array.
11851 static bool checkForArray(const Expr *E) {
11852  const ValueDecl *D = nullptr;
11853  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11854  D = DR->getDecl();
11855  } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11856  if (Mem->isImplicitAccess())
11857  D = Mem->getMemberDecl();
11858  }
11859  if (!D)
11860  return false;
11861  return D->getType()->isArrayType() && !D->isWeak();
11862 }
11863 
11864 /// Diagnose some forms of syntactically-obvious tautological comparison.
11866  Expr *LHS, Expr *RHS,
11867  BinaryOperatorKind Opc) {
11868  Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11869  Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11870 
11871  QualType LHSType = LHS->getType();
11872  QualType RHSType = RHS->getType();
11873  if (LHSType->hasFloatingRepresentation() ||
11874  (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11876  return;
11877 
11878  // WebAssembly Tables cannot be compared, therefore shouldn't emit
11879  // Tautological diagnostics.
11880  if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11881  return;
11882 
11883  // Comparisons between two array types are ill-formed for operator<=>, so
11884  // we shouldn't emit any additional warnings about it.
11885  if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11886  return;
11887 
11888  // For non-floating point types, check for self-comparisons of the form
11889  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11890  // often indicate logic errors in the program.
11891  //
11892  // NOTE: Don't warn about comparison expressions resulting from macro
11893  // expansion. Also don't warn about comparisons which are only self
11894  // comparisons within a template instantiation. The warnings should catch
11895  // obvious cases in the definition of the template anyways. The idea is to
11896  // warn when the typed comparison operator will always evaluate to the same
11897  // result.
11898 
11899  // Used for indexing into %select in warn_comparison_always
11900  enum {
11901  AlwaysConstant,
11902  AlwaysTrue,
11903  AlwaysFalse,
11904  AlwaysEqual, // std::strong_ordering::equal from operator<=>
11905  };
11906 
11907  // C++2a [depr.array.comp]:
11908  // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11909  // operands of array type are deprecated.
11910  if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11911  RHSStripped->getType()->isArrayType()) {
11912  S.Diag(Loc, diag::warn_depr_array_comparison)
11913  << LHS->getSourceRange() << RHS->getSourceRange()
11914  << LHSStripped->getType() << RHSStripped->getType();
11915  // Carry on to produce the tautological comparison warning, if this
11916  // expression is potentially-evaluated, we can resolve the array to a
11917  // non-weak declaration, and so on.
11918  }
11919 
11920  if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11921  if (Expr::isSameComparisonOperand(LHS, RHS)) {
11922  unsigned Result;
11923  switch (Opc) {
11924  case BO_EQ:
11925  case BO_LE:
11926  case BO_GE:
11927  Result = AlwaysTrue;
11928  break;
11929  case BO_NE:
11930  case BO_LT:
11931  case BO_GT:
11932  Result = AlwaysFalse;
11933  break;
11934  case BO_Cmp:
11935  Result = AlwaysEqual;
11936  break;
11937  default:
11938  Result = AlwaysConstant;
11939  break;
11940  }
11941  S.DiagRuntimeBehavior(Loc, nullptr,
11942  S.PDiag(diag::warn_comparison_always)
11943  << 0 /*self-comparison*/
11944  << Result);
11945  } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11946  // What is it always going to evaluate to?
11947  unsigned Result;
11948  switch (Opc) {
11949  case BO_EQ: // e.g. array1 == array2
11950  Result = AlwaysFalse;
11951  break;
11952  case BO_NE: // e.g. array1 != array2
11953  Result = AlwaysTrue;
11954  break;
11955  default: // e.g. array1 <= array2
11956  // The best we can say is 'a constant'
11957  Result = AlwaysConstant;
11958  break;
11959  }
11960  S.DiagRuntimeBehavior(Loc, nullptr,
11961  S.PDiag(diag::warn_comparison_always)
11962  << 1 /*array comparison*/
11963  << Result);
11964  }
11965  }
11966 
11967  if (isa<CastExpr>(LHSStripped))
11968  LHSStripped = LHSStripped->IgnoreParenCasts();
11969  if (isa<CastExpr>(RHSStripped))
11970  RHSStripped = RHSStripped->IgnoreParenCasts();
11971 
11972  // Warn about comparisons against a string constant (unless the other
11973  // operand is null); the user probably wants string comparison function.
11974  Expr *LiteralString = nullptr;
11975  Expr *LiteralStringStripped = nullptr;
11976  if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11977  !RHSStripped->isNullPointerConstant(S.Context,
11979  LiteralString = LHS;
11980  LiteralStringStripped = LHSStripped;
11981  } else if ((isa<StringLiteral>(RHSStripped) ||
11982  isa<ObjCEncodeExpr>(RHSStripped)) &&
11983  !LHSStripped->isNullPointerConstant(S.Context,
11985  LiteralString = RHS;
11986  LiteralStringStripped = RHSStripped;
11987  }
11988 
11989  if (LiteralString) {
11990  S.DiagRuntimeBehavior(Loc, nullptr,
11991  S.PDiag(diag::warn_stringcompare)
11992  << isa<ObjCEncodeExpr>(LiteralStringStripped)
11993  << LiteralString->getSourceRange());
11994  }
11995 }
11996 
11998  switch (CK) {
11999  default: {
12000 #ifndef NDEBUG
12001  llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12002  << "\n";
12003 #endif
12004  llvm_unreachable("unhandled cast kind");
12005  }
12006  case CK_UserDefinedConversion:
12007  return ICK_Identity;
12008  case CK_LValueToRValue:
12009  return ICK_Lvalue_To_Rvalue;
12010  case CK_ArrayToPointerDecay:
12011  return ICK_Array_To_Pointer;
12012  case CK_FunctionToPointerDecay:
12013  return ICK_Function_To_Pointer;
12014  case CK_IntegralCast:
12015  return ICK_Integral_Conversion;
12016  case CK_FloatingCast:
12017  return ICK_Floating_Conversion;
12018  case CK_IntegralToFloating:
12019  case CK_FloatingToIntegral:
12020  return ICK_Floating_Integral;
12021  case CK_IntegralComplexCast:
12022  case CK_FloatingComplexCast:
12023  case CK_FloatingComplexToIntegralComplex:
12024  case CK_IntegralComplexToFloatingComplex:
12025  return ICK_Complex_Conversion;
12026  case CK_FloatingComplexToReal:
12027  case CK_FloatingRealToComplex:
12028  case CK_IntegralComplexToReal:
12029  case CK_IntegralRealToComplex:
12030  return ICK_Complex_Real;
12031  case CK_HLSLArrayRValue:
12032  return ICK_HLSL_Array_RValue;
12033  }
12034 }
12035 
12037  QualType FromType,
12038  SourceLocation Loc) {
12039  // Check for a narrowing implicit conversion.
12042  SCS.setToType(0, FromType);
12043  SCS.setToType(1, ToType);
12044  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12045  SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12046 
12047  APValue PreNarrowingValue;
12048  QualType PreNarrowingType;
12049  switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12050  PreNarrowingType,
12051  /*IgnoreFloatToIntegralConversion*/ true)) {
12053  // Implicit conversion to a narrower type, but the expression is
12054  // value-dependent so we can't tell whether it's actually narrowing.
12055  case NK_Not_Narrowing:
12056  return false;
12057 
12058  case NK_Constant_Narrowing:
12059  // Implicit conversion to a narrower type, and the value is not a constant
12060  // expression.
12061  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12062  << /*Constant*/ 1
12063  << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12064  return true;
12065 
12066  case NK_Variable_Narrowing:
12067  // Implicit conversion to a narrower type, and the value is not a constant
12068  // expression.
12069  case NK_Type_Narrowing:
12070  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12071  << /*Constant*/ 0 << FromType << ToType;
12072  // TODO: It's not a constant expression, but what if the user intended it
12073  // to be? Can we produce notes to help them figure out why it isn't?
12074  return true;
12075  }
12076  llvm_unreachable("unhandled case in switch");
12077 }
12078 
12080  ExprResult &LHS,
12081  ExprResult &RHS,
12082  SourceLocation Loc) {
12083  QualType LHSType = LHS.get()->getType();
12084  QualType RHSType = RHS.get()->getType();
12085  // Dig out the original argument type and expression before implicit casts
12086  // were applied. These are the types/expressions we need to check the
12087  // [expr.spaceship] requirements against.
12088  ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12089  ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12090  QualType LHSStrippedType = LHSStripped.get()->getType();
12091  QualType RHSStrippedType = RHSStripped.get()->getType();
12092 
12093  // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12094  // other is not, the program is ill-formed.
12095  if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12096  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12097  return QualType();
12098  }
12099 
12100  // FIXME: Consider combining this with checkEnumArithmeticConversions.
12101  int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12102  RHSStrippedType->isEnumeralType();
12103  if (NumEnumArgs == 1) {
12104  bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12105  QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12106  if (OtherTy->hasFloatingRepresentation()) {
12107  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12108  return QualType();
12109  }
12110  }
12111  if (NumEnumArgs == 2) {
12112  // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12113  // type E, the operator yields the result of converting the operands
12114  // to the underlying type of E and applying <=> to the converted operands.
12115  if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12116  S.InvalidOperands(Loc, LHS, RHS);
12117  return QualType();
12118  }
12119  QualType IntType =
12120  LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12121  assert(IntType->isArithmeticType());
12122 
12123  // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12124  // promote the boolean type, and all other promotable integer types, to
12125  // avoid this.
12126  if (S.Context.isPromotableIntegerType(IntType))
12127  IntType = S.Context.getPromotedIntegerType(IntType);
12128 
12129  LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12130  RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12131  LHSType = RHSType = IntType;
12132  }
12133 
12134  // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12135  // usual arithmetic conversions are applied to the operands.
12136  QualType Type =
12138  if (LHS.isInvalid() || RHS.isInvalid())
12139  return QualType();
12140  if (Type.isNull())
12141  return S.InvalidOperands(Loc, LHS, RHS);
12142 
12143  std::optional<ComparisonCategoryType> CCT =
12145  if (!CCT)
12146  return S.InvalidOperands(Loc, LHS, RHS);
12147 
12148  bool HasNarrowing = checkThreeWayNarrowingConversion(
12149  S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12150  HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12151  RHS.get()->getBeginLoc());
12152  if (HasNarrowing)
12153  return QualType();
12154 
12155  assert(!Type.isNull() && "composite type for <=> has not been set");
12156 
12157  return S.CheckComparisonCategoryType(
12159 }
12160 
12162  ExprResult &RHS,
12164  BinaryOperatorKind Opc) {
12165  if (Opc == BO_Cmp)
12166  return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12167 
12168  // C99 6.5.8p3 / C99 6.5.9p4
12169  QualType Type =
12171  if (LHS.isInvalid() || RHS.isInvalid())
12172  return QualType();
12173  if (Type.isNull())
12174  return S.InvalidOperands(Loc, LHS, RHS);
12175  assert(Type->isArithmeticType() || Type->isEnumeralType());
12176 
12178  return S.InvalidOperands(Loc, LHS, RHS);
12179 
12180  // Check for comparisons of floating point operands using != and ==.
12182  S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12183 
12184  // The result of comparisons is 'bool' in C++, 'int' in C.
12185  return S.Context.getLogicalOperationType();
12186 }
12187 
12189  if (!NullE.get()->getType()->isAnyPointerType())
12190  return;
12191  int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12192  if (!E.get()->getType()->isAnyPointerType() &&
12193  E.get()->isNullPointerConstant(Context,
12196  if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12197  if (CL->getValue() == 0)
12198  Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12199  << NullValue
12201  NullValue ? "NULL" : "(void *)0");
12202  } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12203  TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12205  if (T == Context.CharTy)
12206  Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12207  << NullValue
12209  NullValue ? "NULL" : "(void *)0");
12210  }
12211  }
12212 }
12213 
12214 // C99 6.5.8, C++ [expr.rel]
12217  BinaryOperatorKind Opc) {
12218  bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12219  bool IsThreeWay = Opc == BO_Cmp;
12220  bool IsOrdered = IsRelational || IsThreeWay;
12221  auto IsAnyPointerType = [](ExprResult E) {
12222  QualType Ty = E.get()->getType();
12223  return Ty->isPointerType() || Ty->isMemberPointerType();
12224  };
12225 
12226  // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12227  // type, array-to-pointer, ..., conversions are performed on both operands to
12228  // bring them to their composite type.
12229  // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12230  // any type-related checks.
12231  if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12232  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12233  if (LHS.isInvalid())
12234  return QualType();
12235  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12236  if (RHS.isInvalid())
12237  return QualType();
12238  } else {
12239  LHS = DefaultLvalueConversion(LHS.get());
12240  if (LHS.isInvalid())
12241  return QualType();
12242  RHS = DefaultLvalueConversion(RHS.get());
12243  if (RHS.isInvalid())
12244  return QualType();
12245  }
12246 
12247  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12248  if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12249  CheckPtrComparisonWithNullChar(LHS, RHS);
12250  CheckPtrComparisonWithNullChar(RHS, LHS);
12251  }
12252 
12253  // Handle vector comparisons separately.
12254  if (LHS.get()->getType()->isVectorType() ||
12255  RHS.get()->getType()->isVectorType())
12256  return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12257 
12258  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12259  RHS.get()->getType()->isSveVLSBuiltinType())
12260  return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12261 
12262  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12263  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12264 
12265  QualType LHSType = LHS.get()->getType();
12266  QualType RHSType = RHS.get()->getType();
12267  if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12268  (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12269  return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12270 
12271  if ((LHSType->isPointerType() &&
12273  (RHSType->isPointerType() &&
12275  return InvalidOperands(Loc, LHS, RHS);
12276 
12277  const Expr::NullPointerConstantKind LHSNullKind =
12279  const Expr::NullPointerConstantKind RHSNullKind =
12281  bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12282  bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12283 
12284  auto computeResultTy = [&]() {
12285  if (Opc != BO_Cmp)
12286  return Context.getLogicalOperationType();
12287  assert(getLangOpts().CPlusPlus);
12288  assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12289 
12290  QualType CompositeTy = LHS.get()->getType();
12291  assert(!CompositeTy->isReferenceType());
12292 
12293  std::optional<ComparisonCategoryType> CCT =
12295  if (!CCT)
12296  return InvalidOperands(Loc, LHS, RHS);
12297 
12298  if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12299  // P0946R0: Comparisons between a null pointer constant and an object
12300  // pointer result in std::strong_equality, which is ill-formed under
12301  // P1959R0.
12302  Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12303  << (LHSIsNull ? LHS.get()->getSourceRange()
12304  : RHS.get()->getSourceRange());
12305  return QualType();
12306  }
12307 
12308  return CheckComparisonCategoryType(
12309  *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12310  };
12311 
12312  if (!IsOrdered && LHSIsNull != RHSIsNull) {
12313  bool IsEquality = Opc == BO_EQ;
12314  if (RHSIsNull)
12315  DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12316  RHS.get()->getSourceRange());
12317  else
12318  DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12319  LHS.get()->getSourceRange());
12320  }
12321 
12322  if (IsOrdered && LHSType->isFunctionPointerType() &&
12323  RHSType->isFunctionPointerType()) {
12324  // Valid unless a relational comparison of function pointers
12325  bool IsError = Opc == BO_Cmp;
12326  auto DiagID =
12327  IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12328  : getLangOpts().CPlusPlus
12329  ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12330  : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12331  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12332  << RHS.get()->getSourceRange();
12333  if (IsError)
12334  return QualType();
12335  }
12336 
12337  if ((LHSType->isIntegerType() && !LHSIsNull) ||
12338  (RHSType->isIntegerType() && !RHSIsNull)) {
12339  // Skip normal pointer conversion checks in this case; we have better
12340  // diagnostics for this below.
12341  } else if (getLangOpts().CPlusPlus) {
12342  // Equality comparison of a function pointer to a void pointer is invalid,
12343  // but we allow it as an extension.
12344  // FIXME: If we really want to allow this, should it be part of composite
12345  // pointer type computation so it works in conditionals too?
12346  if (!IsOrdered &&
12347  ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12348  (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12349  // This is a gcc extension compatibility comparison.
12350  // In a SFINAE context, we treat this as a hard error to maintain
12351  // conformance with the C++ standard.
12353  *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12354 
12355  if (isSFINAEContext())
12356  return QualType();
12357 
12358  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12359  return computeResultTy();
12360  }
12361 
12362  // C++ [expr.eq]p2:
12363  // If at least one operand is a pointer [...] bring them to their
12364  // composite pointer type.
12365  // C++ [expr.spaceship]p6
12366  // If at least one of the operands is of pointer type, [...] bring them
12367  // to their composite pointer type.
12368  // C++ [expr.rel]p2:
12369  // If both operands are pointers, [...] bring them to their composite
12370  // pointer type.
12371  // For <=>, the only valid non-pointer types are arrays and functions, and
12372  // we already decayed those, so this is really the same as the relational
12373  // comparison rule.
12374  if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12375  (IsOrdered ? 2 : 1) &&
12376  (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12377  RHSType->isObjCObjectPointerType()))) {
12378  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12379  return QualType();
12380  return computeResultTy();
12381  }
12382  } else if (LHSType->isPointerType() &&
12383  RHSType->isPointerType()) { // C99 6.5.8p2
12384  // All of the following pointer-related warnings are GCC extensions, except
12385  // when handling null pointer constants.
12386  QualType LCanPointeeTy =
12387  LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12388  QualType RCanPointeeTy =
12389  RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12390 
12391  // C99 6.5.9p2 and C99 6.5.8p2
12392  if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12393  RCanPointeeTy.getUnqualifiedType())) {
12394  if (IsRelational) {
12395  // Pointers both need to point to complete or incomplete types
12396  if ((LCanPointeeTy->isIncompleteType() !=
12397  RCanPointeeTy->isIncompleteType()) &&
12398  !getLangOpts().C11) {
12399  Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12400  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12401  << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12402  << RCanPointeeTy->isIncompleteType();
12403  }
12404  }
12405  } else if (!IsRelational &&
12406  (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12407  // Valid unless comparison between non-null pointer and function pointer
12408  if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12409  && !LHSIsNull && !RHSIsNull)
12411  /*isError*/false);
12412  } else {
12413  // Invalid
12414  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12415  }
12416  if (LCanPointeeTy != RCanPointeeTy) {
12417  // Treat NULL constant as a special case in OpenCL.
12418  if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12419  if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12420  Diag(Loc,
12421  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12422  << LHSType << RHSType << 0 /* comparison */
12423  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12424  }
12425  }
12426  LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12427  LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12428  CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12429  : CK_BitCast;
12430  if (LHSIsNull && !RHSIsNull)
12431  LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12432  else
12433  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12434  }
12435  return computeResultTy();
12436  }
12437 
12438 
12439  // C++ [expr.eq]p4:
12440  // Two operands of type std::nullptr_t or one operand of type
12441  // std::nullptr_t and the other a null pointer constant compare
12442  // equal.
12443  // C23 6.5.9p5:
12444  // If both operands have type nullptr_t or one operand has type nullptr_t
12445  // and the other is a null pointer constant, they compare equal if the
12446  // former is a null pointer.
12447  if (!IsOrdered && LHSIsNull && RHSIsNull) {
12448  if (LHSType->isNullPtrType()) {
12449  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12450  return computeResultTy();
12451  }
12452  if (RHSType->isNullPtrType()) {
12453  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12454  return computeResultTy();
12455  }
12456  }
12457 
12458  if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12459  // C23 6.5.9p6:
12460  // Otherwise, at least one operand is a pointer. If one is a pointer and
12461  // the other is a null pointer constant or has type nullptr_t, they
12462  // compare equal
12463  if (LHSIsNull && RHSType->isPointerType()) {
12464  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12465  return computeResultTy();
12466  }
12467  if (RHSIsNull && LHSType->isPointerType()) {
12468  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12469  return computeResultTy();
12470  }
12471  }
12472 
12473  // Comparison of Objective-C pointers and block pointers against nullptr_t.
12474  // These aren't covered by the composite pointer type rules.
12475  if (!IsOrdered && RHSType->isNullPtrType() &&
12476  (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12477  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12478  return computeResultTy();
12479  }
12480  if (!IsOrdered && LHSType->isNullPtrType() &&
12481  (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12482  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12483  return computeResultTy();
12484  }
12485 
12486  if (getLangOpts().CPlusPlus) {
12487  if (IsRelational &&
12488  ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12489  (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12490  // HACK: Relational comparison of nullptr_t against a pointer type is
12491  // invalid per DR583, but we allow it within std::less<> and friends,
12492  // since otherwise common uses of it break.
12493  // FIXME: Consider removing this hack once LWG fixes std::less<> and
12494  // friends to have std::nullptr_t overload candidates.
12495  DeclContext *DC = CurContext;
12496  if (isa<FunctionDecl>(DC))
12497  DC = DC->getParent();
12498  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12499  if (CTSD->isInStdNamespace() &&
12500  llvm::StringSwitch<bool>(CTSD->getName())
12501  .Cases("less", "less_equal", "greater", "greater_equal", true)
12502  .Default(false)) {
12503  if (RHSType->isNullPtrType())
12504  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12505  else
12506  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12507  return computeResultTy();
12508  }
12509  }
12510  }
12511 
12512  // C++ [expr.eq]p2:
12513  // If at least one operand is a pointer to member, [...] bring them to
12514  // their composite pointer type.
12515  if (!IsOrdered &&
12516  (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12517  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12518  return QualType();
12519  else
12520  return computeResultTy();
12521  }
12522  }
12523 
12524  // Handle block pointer types.
12525  if (!IsOrdered && LHSType->isBlockPointerType() &&
12526  RHSType->isBlockPointerType()) {
12527  QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12528  QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12529 
12530  if (!LHSIsNull && !RHSIsNull &&
12531  !Context.typesAreCompatible(lpointee, rpointee)) {
12532  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12533  << LHSType << RHSType << LHS.get()->getSourceRange()
12534  << RHS.get()->getSourceRange();
12535  }
12536  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12537  return computeResultTy();
12538  }
12539 
12540  // Allow block pointers to be compared with null pointer constants.
12541  if (!IsOrdered
12542  && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12543  || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12544  if (!LHSIsNull && !RHSIsNull) {
12545  if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12546  ->getPointeeType()->isVoidType())
12547  || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12548  ->getPointeeType()->isVoidType())))
12549  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12550  << LHSType << RHSType << LHS.get()->getSourceRange()
12551  << RHS.get()->getSourceRange();
12552  }
12553  if (LHSIsNull && !RHSIsNull)
12554  LHS = ImpCastExprToType(LHS.get(), RHSType,
12555  RHSType->isPointerType() ? CK_BitCast
12556  : CK_AnyPointerToBlockPointerCast);
12557  else
12558  RHS = ImpCastExprToType(RHS.get(), LHSType,
12559  LHSType->isPointerType() ? CK_BitCast
12560  : CK_AnyPointerToBlockPointerCast);
12561  return computeResultTy();
12562  }
12563 
12564  if (LHSType->isObjCObjectPointerType() ||
12565  RHSType->isObjCObjectPointerType()) {
12566  const PointerType *LPT = LHSType->getAs<PointerType>();
12567  const PointerType *RPT = RHSType->getAs<PointerType>();
12568  if (LPT || RPT) {
12569  bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12570  bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12571 
12572  if (!LPtrToVoid && !RPtrToVoid &&
12573  !Context.typesAreCompatible(LHSType, RHSType)) {
12574  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12575  /*isError*/false);
12576  }
12577  // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12578  // the RHS, but we have test coverage for this behavior.
12579  // FIXME: Consider using convertPointersToCompositeType in C++.
12580  if (LHSIsNull && !RHSIsNull) {
12581  Expr *E = LHS.get();
12582  if (getLangOpts().ObjCAutoRefCount)
12583  ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12585  LHS = ImpCastExprToType(E, RHSType,
12586  RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12587  }
12588  else {
12589  Expr *E = RHS.get();
12590  if (getLangOpts().ObjCAutoRefCount)
12591  ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12593  /*Diagnose=*/true,
12594  /*DiagnoseCFAudited=*/false, Opc);
12595  RHS = ImpCastExprToType(E, LHSType,
12596  LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12597  }
12598  return computeResultTy();
12599  }
12600  if (LHSType->isObjCObjectPointerType() &&
12601  RHSType->isObjCObjectPointerType()) {
12602  if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12603  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12604  /*isError*/false);
12605  if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12606  diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12607 
12608  if (LHSIsNull && !RHSIsNull)
12609  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12610  else
12611  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12612  return computeResultTy();
12613  }
12614 
12615  if (!IsOrdered && LHSType->isBlockPointerType() &&
12616  RHSType->isBlockCompatibleObjCPointerType(Context)) {
12617  LHS = ImpCastExprToType(LHS.get(), RHSType,
12618  CK_BlockPointerToObjCPointerCast);
12619  return computeResultTy();
12620  } else if (!IsOrdered &&
12621  LHSType->isBlockCompatibleObjCPointerType(Context) &&
12622  RHSType->isBlockPointerType()) {
12623  RHS = ImpCastExprToType(RHS.get(), LHSType,
12624  CK_BlockPointerToObjCPointerCast);
12625  return computeResultTy();
12626  }
12627  }
12628  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12629  (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12630  unsigned DiagID = 0;
12631  bool isError = false;
12632  if (LangOpts.DebuggerSupport) {
12633  // Under a debugger, allow the comparison of pointers to integers,
12634  // since users tend to want to compare addresses.
12635  } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12636  (RHSIsNull && RHSType->isIntegerType())) {
12637  if (IsOrdered) {
12638  isError = getLangOpts().CPlusPlus;
12639  DiagID =
12640  isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12641  : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12642  }
12643  } else if (getLangOpts().CPlusPlus) {
12644  DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12645  isError = true;
12646  } else if (IsOrdered)
12647  DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12648  else
12649  DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12650 
12651  if (DiagID) {
12652  Diag(Loc, DiagID)
12653  << LHSType << RHSType << LHS.get()->getSourceRange()
12654  << RHS.get()->getSourceRange();
12655  if (isError)
12656  return QualType();
12657  }
12658 
12659  if (LHSType->isIntegerType())
12660  LHS = ImpCastExprToType(LHS.get(), RHSType,
12661  LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12662  else
12663  RHS = ImpCastExprToType(RHS.get(), LHSType,
12664  RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12665  return computeResultTy();
12666  }
12667 
12668  // Handle block pointers.
12669  if (!IsOrdered && RHSIsNull
12670  && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12671  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12672  return computeResultTy();
12673  }
12674  if (!IsOrdered && LHSIsNull
12675  && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12676  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12677  return computeResultTy();
12678  }
12679 
12680  if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12681  if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12682  return computeResultTy();
12683  }
12684 
12685  if (LHSType->isQueueT() && RHSType->isQueueT()) {
12686  return computeResultTy();
12687  }
12688 
12689  if (LHSIsNull && RHSType->isQueueT()) {
12690  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12691  return computeResultTy();
12692  }
12693 
12694  if (LHSType->isQueueT() && RHSIsNull) {
12695  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12696  return computeResultTy();
12697  }
12698  }
12699 
12700  return InvalidOperands(Loc, LHS, RHS);
12701 }
12702 
12703 // Return a signed ext_vector_type that is of identical size and number of
12704 // elements. For floating point vectors, return an integer type of identical
12705 // size and number of elements. In the non ext_vector_type case, search from
12706 // the largest type to the smallest type to avoid cases where long long == long,
12707 // where long gets picked over long long.
12709  const VectorType *VTy = V->castAs<VectorType>();
12710  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12711 
12712  if (isa<ExtVectorType>(VTy)) {
12713  if (VTy->isExtVectorBoolType())
12714  return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12715  if (TypeSize == Context.getTypeSize(Context.CharTy))
12716  return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12717  if (TypeSize == Context.getTypeSize(Context.ShortTy))
12718  return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12719  if (TypeSize == Context.getTypeSize(Context.IntTy))
12720  return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12721  if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12722  return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12723  if (TypeSize == Context.getTypeSize(Context.LongTy))
12724  return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12725  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12726  "Unhandled vector element size in vector compare");
12727  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12728  }
12729 
12730  if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12731  return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12733  if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12734  return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12736  if (TypeSize == Context.getTypeSize(Context.LongTy))
12737  return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12739  if (TypeSize == Context.getTypeSize(Context.IntTy))
12740  return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12742  if (TypeSize == Context.getTypeSize(Context.ShortTy))
12743  return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12745  assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12746  "Unhandled vector element size in vector compare");
12747  return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12749 }
12750 
12752  const BuiltinType *VTy = V->castAs<BuiltinType>();
12753  assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12754 
12755  const QualType ETy = V->getSveEltType(Context);
12756  const auto TypeSize = Context.getTypeSize(ETy);
12757 
12758  const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12759  const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12760  return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12761 }
12762 
12763 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12764 /// operates on extended vector types. Instead of producing an IntTy result,
12765 /// like a scalar comparison, a vector comparison produces a vector of integer
12766 /// types.
12769  BinaryOperatorKind Opc) {
12770  if (Opc == BO_Cmp) {
12771  Diag(Loc, diag::err_three_way_vector_comparison);
12772  return QualType();
12773  }
12774 
12775  // Check to make sure we're operating on vectors of the same type and width,
12776  // Allowing one side to be a scalar of element type.
12777  QualType vType =
12778  CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12779  /*AllowBothBool*/ true,
12780  /*AllowBoolConversions*/ getLangOpts().ZVector,
12781  /*AllowBooleanOperation*/ true,
12782  /*ReportInvalid*/ true);
12783  if (vType.isNull())
12784  return vType;
12785 
12786  QualType LHSType = LHS.get()->getType();
12787 
12788  // Determine the return type of a vector compare. By default clang will return
12789  // a scalar for all vector compares except vector bool and vector pixel.
12790  // With the gcc compiler we will always return a vector type and with the xl
12791  // compiler we will always return a scalar type. This switch allows choosing
12792  // which behavior is prefered.
12793  if (getLangOpts().AltiVec) {
12794  switch (getLangOpts().getAltivecSrcCompat()) {
12796  // If AltiVec, the comparison results in a numeric type, i.e.
12797  // bool for C++, int for C
12798  if (vType->castAs<VectorType>()->getVectorKind() ==
12800  return Context.getLogicalOperationType();
12801  else
12802  Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12803  break;
12805  // For GCC we always return the vector type.
12806  break;
12808  return Context.getLogicalOperationType();
12809  break;
12810  }
12811  }
12812 
12813  // For non-floating point types, check for self-comparisons of the form
12814  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12815  // often indicate logic errors in the program.
12816  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12817 
12818  // Check for comparisons of floating point operands using != and ==.
12819  if (LHSType->hasFloatingRepresentation()) {
12820  assert(RHS.get()->getType()->hasFloatingRepresentation());
12821  CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12822  }
12823 
12824  // Return a signed type for the vector.
12825  return GetSignedVectorType(vType);
12826 }
12827 
12829  ExprResult &RHS,
12831  BinaryOperatorKind Opc) {
12832  if (Opc == BO_Cmp) {
12833  Diag(Loc, diag::err_three_way_vector_comparison);
12834  return QualType();
12835  }
12836 
12837  // Check to make sure we're operating on vectors of the same type and width,
12838  // Allowing one side to be a scalar of element type.
12839  QualType vType = CheckSizelessVectorOperands(
12840  LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12841 
12842  if (vType.isNull())
12843  return vType;
12844 
12845  QualType LHSType = LHS.get()->getType();
12846 
12847  // For non-floating point types, check for self-comparisons of the form
12848  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12849  // often indicate logic errors in the program.
12850  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12851 
12852  // Check for comparisons of floating point operands using != and ==.
12853  if (LHSType->hasFloatingRepresentation()) {
12854  assert(RHS.get()->getType()->hasFloatingRepresentation());
12855  CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12856  }
12857 
12858  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12859  const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12860 
12861  if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12862  RHSBuiltinTy->isSVEBool())
12863  return LHSType;
12864 
12865  // Return a signed type for the vector.
12866  return GetSignedSizelessVectorType(vType);
12867 }
12868 
12869 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12870  const ExprResult &XorRHS,
12871  const SourceLocation Loc) {
12872  // Do not diagnose macros.
12873  if (Loc.isMacroID())
12874  return;
12875 
12876  // Do not diagnose if both LHS and RHS are macros.
12877  if (XorLHS.get()->getExprLoc().isMacroID() &&
12878  XorRHS.get()->getExprLoc().isMacroID())
12879  return;
12880 
12881  bool Negative = false;
12882  bool ExplicitPlus = false;
12883  const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12884  const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12885 
12886  if (!LHSInt)
12887  return;
12888  if (!RHSInt) {
12889  // Check negative literals.
12890  if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12891  UnaryOperatorKind Opc = UO->getOpcode();
12892  if (Opc != UO_Minus && Opc != UO_Plus)
12893  return;
12894  RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12895  if (!RHSInt)
12896  return;
12897  Negative = (Opc == UO_Minus);
12898  ExplicitPlus = !Negative;
12899  } else {
12900  return;
12901  }
12902  }
12903 
12904  const llvm::APInt &LeftSideValue = LHSInt->getValue();
12905  llvm::APInt RightSideValue = RHSInt->getValue();
12906  if (LeftSideValue != 2 && LeftSideValue != 10)
12907  return;
12908 
12909  if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12910  return;
12911 
12913  LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12914  llvm::StringRef ExprStr =
12915  Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12916 
12917  CharSourceRange XorRange =
12919  llvm::StringRef XorStr =
12921  // Do not diagnose if xor keyword/macro is used.
12922  if (XorStr == "xor")
12923  return;
12924 
12925  std::string LHSStr = std::string(Lexer::getSourceText(
12926  CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12927  S.getSourceManager(), S.getLangOpts()));
12928  std::string RHSStr = std::string(Lexer::getSourceText(
12929  CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12930  S.getSourceManager(), S.getLangOpts()));
12931 
12932  if (Negative) {
12933  RightSideValue = -RightSideValue;
12934  RHSStr = "-" + RHSStr;
12935  } else if (ExplicitPlus) {
12936  RHSStr = "+" + RHSStr;
12937  }
12938 
12939  StringRef LHSStrRef = LHSStr;
12940  StringRef RHSStrRef = RHSStr;
12941  // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12942  // literals.
12943  if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12944  RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12945  LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12946  RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12947  (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12948  (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12949  LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12950  return;
12951 
12952  bool SuggestXor =
12953  S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12954  const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12955  int64_t RightSideIntValue = RightSideValue.getSExtValue();
12956  if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12957  std::string SuggestedExpr = "1 << " + RHSStr;
12958  bool Overflow = false;
12959  llvm::APInt One = (LeftSideValue - 1);
12960  llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12961  if (Overflow) {
12962  if (RightSideIntValue < 64)
12963  S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12964  << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12965  << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12966  else if (RightSideIntValue == 64)
12967  S.Diag(Loc, diag::warn_xor_used_as_pow)
12968  << ExprStr << toString(XorValue, 10, true);
12969  else
12970  return;
12971  } else {
12972  S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12973  << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12974  << toString(PowValue, 10, true)
12976  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12977  }
12978 
12979  S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12980  << ("0x2 ^ " + RHSStr) << SuggestXor;
12981  } else if (LeftSideValue == 10) {
12982  std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12983  S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12984  << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12985  << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12986  S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12987  << ("0xA ^ " + RHSStr) << SuggestXor;
12988  }
12989 }
12990 
12992  SourceLocation Loc) {
12993  // Ensure that either both operands are of the same vector type, or
12994  // one operand is of a vector type and the other is of its element type.
12995  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12996  /*AllowBothBool*/ true,
12997  /*AllowBoolConversions*/ false,
12998  /*AllowBooleanOperation*/ false,
12999  /*ReportInvalid*/ false);
13000  if (vType.isNull())
13001  return InvalidOperands(Loc, LHS, RHS);
13002  if (getLangOpts().OpenCL &&
13003  getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13004  vType->hasFloatingRepresentation())
13005  return InvalidOperands(Loc, LHS, RHS);
13006  // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13007  // usage of the logical operators && and || with vectors in C. This
13008  // check could be notionally dropped.
13009  if (!getLangOpts().CPlusPlus &&
13010  !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13011  return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13012 
13013  return GetSignedVectorType(LHS.get()->getType());
13014 }
13015 
13018  bool IsCompAssign) {
13019  if (!IsCompAssign) {
13020  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13021  if (LHS.isInvalid())
13022  return QualType();
13023  }
13024  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13025  if (RHS.isInvalid())
13026  return QualType();
13027 
13028  // For conversion purposes, we ignore any qualifiers.
13029  // For example, "const float" and "float" are equivalent.
13030  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13031  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13032 
13033  const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13034  const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13035  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13036 
13037  if (Context.hasSameType(LHSType, RHSType))
13038  return Context.getCommonSugaredType(LHSType, RHSType);
13039 
13040  // Type conversion may change LHS/RHS. Keep copies to the original results, in
13041  // case we have to return InvalidOperands.
13042  ExprResult OriginalLHS = LHS;
13043  ExprResult OriginalRHS = RHS;
13044  if (LHSMatType && !RHSMatType) {
13045  RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13046  if (!RHS.isInvalid())
13047  return LHSType;
13048 
13049  return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13050  }
13051 
13052  if (!LHSMatType && RHSMatType) {
13053  LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13054  if (!LHS.isInvalid())
13055  return RHSType;
13056  return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13057  }
13058 
13059  return InvalidOperands(Loc, LHS, RHS);
13060 }
13061 
13064  bool IsCompAssign) {
13065  if (!IsCompAssign) {
13066  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13067  if (LHS.isInvalid())
13068  return QualType();
13069  }
13070  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13071  if (RHS.isInvalid())
13072  return QualType();
13073 
13074  auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13075  auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13076  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13077 
13078  if (LHSMatType && RHSMatType) {
13079  if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13080  return InvalidOperands(Loc, LHS, RHS);
13081 
13082  if (Context.hasSameType(LHSMatType, RHSMatType))
13083  return Context.getCommonSugaredType(
13084  LHS.get()->getType().getUnqualifiedType(),
13085  RHS.get()->getType().getUnqualifiedType());
13086 
13087  QualType LHSELTy = LHSMatType->getElementType(),
13088  RHSELTy = RHSMatType->getElementType();
13089  if (!Context.hasSameType(LHSELTy, RHSELTy))
13090  return InvalidOperands(Loc, LHS, RHS);
13091 
13092  return Context.getConstantMatrixType(
13093  Context.getCommonSugaredType(LHSELTy, RHSELTy),
13094  LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13095  }
13096  return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13097 }
13098 
13100  switch (Opc) {
13101  default:
13102  return false;
13103  case BO_And:
13104  case BO_AndAssign:
13105  case BO_Or:
13106  case BO_OrAssign:
13107  case BO_Xor:
13108  case BO_XorAssign:
13109  return true;
13110  }
13111 }
13112 
13115  BinaryOperatorKind Opc) {
13116  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13117 
13118  bool IsCompAssign =
13119  Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13120 
13121  bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13122 
13123  if (LHS.get()->getType()->isVectorType() ||
13124  RHS.get()->getType()->isVectorType()) {
13125  if (LHS.get()->getType()->hasIntegerRepresentation() &&
13126  RHS.get()->getType()->hasIntegerRepresentation())
13127  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13128  /*AllowBothBool*/ true,
13129  /*AllowBoolConversions*/ getLangOpts().ZVector,
13130  /*AllowBooleanOperation*/ LegalBoolVecOperator,
13131  /*ReportInvalid*/ true);
13132  return InvalidOperands(Loc, LHS, RHS);
13133  }
13134 
13135  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13136  RHS.get()->getType()->isSveVLSBuiltinType()) {
13137  if (LHS.get()->getType()->hasIntegerRepresentation() &&
13138  RHS.get()->getType()->hasIntegerRepresentation())
13139  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13140  ACK_BitwiseOp);
13141  return InvalidOperands(Loc, LHS, RHS);
13142  }
13143 
13144  if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13145  RHS.get()->getType()->isSveVLSBuiltinType()) {
13146  if (LHS.get()->getType()->hasIntegerRepresentation() &&
13147  RHS.get()->getType()->hasIntegerRepresentation())
13148  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13149  ACK_BitwiseOp);
13150  return InvalidOperands(Loc, LHS, RHS);
13151  }
13152 
13153  if (Opc == BO_And)
13154  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13155 
13156  if (LHS.get()->getType()->hasFloatingRepresentation() ||
13158  return InvalidOperands(Loc, LHS, RHS);
13159 
13160  ExprResult LHSResult = LHS, RHSResult = RHS;
13161  QualType compType = UsualArithmeticConversions(
13162  LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13163  if (LHSResult.isInvalid() || RHSResult.isInvalid())
13164  return QualType();
13165  LHS = LHSResult.get();
13166  RHS = RHSResult.get();
13167 
13168  if (Opc == BO_Xor)
13169  diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13170 
13171  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13172  return compType;
13173  return InvalidOperands(Loc, LHS, RHS);
13174 }
13175 
13176 // C99 6.5.[13,14]
13179  BinaryOperatorKind Opc) {
13180  // Check vector operands differently.
13181  if (LHS.get()->getType()->isVectorType() ||
13182  RHS.get()->getType()->isVectorType())
13183  return CheckVectorLogicalOperands(LHS, RHS, Loc);
13184 
13185  bool EnumConstantInBoolContext = false;
13186  for (const ExprResult &HS : {LHS, RHS}) {
13187  if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13188  const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13189  if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13190  EnumConstantInBoolContext = true;
13191  }
13192  }
13193 
13194  if (EnumConstantInBoolContext)
13195  Diag(Loc, diag::warn_enum_constant_in_bool_context);
13196 
13197  // WebAssembly tables can't be used with logical operators.
13198  QualType LHSTy = LHS.get()->getType();
13199  QualType RHSTy = RHS.get()->getType();
13200  const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13201  const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13202  if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13203  (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13204  return InvalidOperands(Loc, LHS, RHS);
13205  }
13206 
13207  // Diagnose cases where the user write a logical and/or but probably meant a
13208  // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13209  // is a constant.
13210  if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13211  !LHS.get()->getType()->isBooleanType() &&
13212  RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13213  // Don't warn in macros or template instantiations.
13214  !Loc.isMacroID() && !inTemplateInstantiation()) {
13215  // If the RHS can be constant folded, and if it constant folds to something
13216  // that isn't 0 or 1 (which indicate a potential logical operation that
13217  // happened to fold to true/false) then warn.
13218  // Parens on the RHS are ignored.
13219  Expr::EvalResult EVResult;
13220  if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13221  llvm::APSInt Result = EVResult.Val.getInt();
13222  if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13223  !RHS.get()->getExprLoc().isMacroID()) ||
13224  (Result != 0 && Result != 1)) {
13225  Diag(Loc, diag::warn_logical_instead_of_bitwise)
13226  << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13227  // Suggest replacing the logical operator with the bitwise version
13228  Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13229  << (Opc == BO_LAnd ? "&" : "|")
13231  SourceRange(Loc, getLocForEndOfToken(Loc)),
13232  Opc == BO_LAnd ? "&" : "|");
13233  if (Opc == BO_LAnd)
13234  // Suggest replacing "Foo() && kNonZero" with "Foo()"
13235  Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13237  SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13238  RHS.get()->getEndLoc()));
13239  }
13240  }
13241  }
13242 
13243  if (!Context.getLangOpts().CPlusPlus) {
13244  // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13245  // not operate on the built-in scalar and vector float types.
13246  if (Context.getLangOpts().OpenCL &&
13247  Context.getLangOpts().OpenCLVersion < 120) {
13248  if (LHS.get()->getType()->isFloatingType() ||
13249  RHS.get()->getType()->isFloatingType())
13250  return InvalidOperands(Loc, LHS, RHS);
13251  }
13252 
13253  LHS = UsualUnaryConversions(LHS.get());
13254  if (LHS.isInvalid())
13255  return QualType();
13256 
13257  RHS = UsualUnaryConversions(RHS.get());
13258  if (RHS.isInvalid())
13259  return QualType();
13260 
13261  if (!LHS.get()->getType()->isScalarType() ||
13262  !RHS.get()->getType()->isScalarType())
13263  return InvalidOperands(Loc, LHS, RHS);
13264 
13265  return Context.IntTy;
13266  }
13267 
13268  // The following is safe because we only use this method for
13269  // non-overloadable operands.
13270 
13271  // C++ [expr.log.and]p1
13272  // C++ [expr.log.or]p1
13273  // The operands are both contextually converted to type bool.
13274  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13275  if (LHSRes.isInvalid())
13276  return InvalidOperands(Loc, LHS, RHS);
13277  LHS = LHSRes;
13278 
13279  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13280  if (RHSRes.isInvalid())
13281  return InvalidOperands(Loc, LHS, RHS);
13282  RHS = RHSRes;
13283 
13284  // C++ [expr.log.and]p2
13285  // C++ [expr.log.or]p2
13286  // The result is a bool.
13287  return Context.BoolTy;
13288 }
13289 
13290 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13291  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13292  if (!ME) return false;
13293  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13294  ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13296  if (!Base) return false;
13297  return Base->getMethodDecl() != nullptr;
13298 }
13299 
13300 /// Is the given expression (which must be 'const') a reference to a
13301 /// variable which was originally non-const, but which has become
13302 /// 'const' due to being captured within a block?
13305  assert(E->isLValue() && E->getType().isConstQualified());
13306  E = E->IgnoreParens();
13307 
13308  // Must be a reference to a declaration from an enclosing scope.
13309  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13310  if (!DRE) return NCCK_None;
13311  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13312 
13313  // The declaration must be a variable which is not declared 'const'.
13314  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13315  if (!var) return NCCK_None;
13316  if (var->getType().isConstQualified()) return NCCK_None;
13317  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13318 
13319  // Decide whether the first capture was for a block or a lambda.
13320  DeclContext *DC = S.CurContext, *Prev = nullptr;
13321  // Decide whether the first capture was for a block or a lambda.
13322  while (DC) {
13323  // For init-capture, it is possible that the variable belongs to the
13324  // template pattern of the current context.
13325  if (auto *FD = dyn_cast<FunctionDecl>(DC))
13326  if (var->isInitCapture() &&
13327  FD->getTemplateInstantiationPattern() == var->getDeclContext())
13328  break;
13329  if (DC == var->getDeclContext())
13330  break;
13331  Prev = DC;
13332  DC = DC->getParent();
13333  }
13334  // Unless we have an init-capture, we've gone one step too far.
13335  if (!var->isInitCapture())
13336  DC = Prev;
13337  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13338 }
13339 
13340 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13341  Ty = Ty.getNonReferenceType();
13342  if (IsDereference && Ty->isPointerType())
13343  Ty = Ty->getPointeeType();
13344  return !Ty.isConstQualified();
13345 }
13346 
13347 // Update err_typecheck_assign_const and note_typecheck_assign_const
13348 // when this enum is changed.
13349 enum {
13355  ConstUnknown, // Keep as last element
13356 };
13357 
13358 /// Emit the "read-only variable not assignable" error and print notes to give
13359 /// more information about why the variable is not assignable, such as pointing
13360 /// to the declaration of a const variable, showing that a method is const, or
13361 /// that the function is returning a const reference.
13362 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13363  SourceLocation Loc) {
13364  SourceRange ExprRange = E->getSourceRange();
13365 
13366  // Only emit one error on the first const found. All other consts will emit
13367  // a note to the error.
13368  bool DiagnosticEmitted = false;
13369 
13370  // Track if the current expression is the result of a dereference, and if the
13371  // next checked expression is the result of a dereference.
13372  bool IsDereference = false;
13373  bool NextIsDereference = false;
13374 
13375  // Loop to process MemberExpr chains.
13376  while (true) {
13377  IsDereference = NextIsDereference;
13378 
13379  E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13380  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13381  NextIsDereference = ME->isArrow();
13382  const ValueDecl *VD = ME->getMemberDecl();
13383  if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13384  // Mutable fields can be modified even if the class is const.
13385  if (Field->isMutable()) {
13386  assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13387  break;
13388  }
13389 
13390  if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13391  if (!DiagnosticEmitted) {
13392  S.Diag(Loc, diag::err_typecheck_assign_const)
13393  << ExprRange << ConstMember << false /*static*/ << Field
13394  << Field->getType();
13395  DiagnosticEmitted = true;
13396  }
13397  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13398  << ConstMember << false /*static*/ << Field << Field->getType()
13399  << Field->getSourceRange();
13400  }
13401  E = ME->getBase();
13402  continue;
13403  } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13404  if (VDecl->getType().isConstQualified()) {
13405  if (!DiagnosticEmitted) {
13406  S.Diag(Loc, diag::err_typecheck_assign_const)
13407  << ExprRange << ConstMember << true /*static*/ << VDecl
13408  << VDecl->getType();
13409  DiagnosticEmitted = true;
13410  }
13411  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13412  << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13413  << VDecl->getSourceRange();
13414  }
13415  // Static fields do not inherit constness from parents.
13416  break;
13417  }
13418  break; // End MemberExpr
13419  } else if (const ArraySubscriptExpr *ASE =
13420  dyn_cast<ArraySubscriptExpr>(E)) {
13421  E = ASE->getBase()->IgnoreParenImpCasts();
13422  continue;
13423  } else if (const ExtVectorElementExpr *EVE =
13424  dyn_cast<ExtVectorElementExpr>(E)) {
13425  E = EVE->getBase()->IgnoreParenImpCasts();
13426  continue;
13427  }
13428  break;
13429  }
13430 
13431  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13432  // Function calls
13433  const FunctionDecl *FD = CE->getDirectCallee();
13434  if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13435  if (!DiagnosticEmitted) {
13436  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13437  << ConstFunction << FD;
13438  DiagnosticEmitted = true;
13439  }
13441  diag::note_typecheck_assign_const)
13442  << ConstFunction << FD << FD->getReturnType()
13443  << FD->getReturnTypeSourceRange();
13444  }
13445  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13446  // Point to variable declaration.
13447  if (const ValueDecl *VD = DRE->getDecl()) {
13448  if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13449  if (!DiagnosticEmitted) {
13450  S.Diag(Loc, diag::err_typecheck_assign_const)
13451  << ExprRange << ConstVariable << VD << VD->getType();
13452  DiagnosticEmitted = true;
13453  }
13454  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13455  << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13456  }
13457  }
13458  } else if (isa<CXXThisExpr>(E)) {
13459  if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13460  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13461  if (MD->isConst()) {
13462  if (!DiagnosticEmitted) {
13463  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13464  << ConstMethod << MD;
13465  DiagnosticEmitted = true;
13466  }
13467  S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13468  << ConstMethod << MD << MD->getSourceRange();
13469  }
13470  }
13471  }
13472  }
13473 
13474  if (DiagnosticEmitted)
13475  return;
13476 
13477  // Can't determine a more specific message, so display the generic error.
13478  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13479 }
13480 
13484  OEK_LValue
13485 };
13486 
13487 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13488  const RecordType *Ty,
13490  OriginalExprKind OEK,
13491  bool &DiagnosticEmitted) {
13492  std::vector<const RecordType *> RecordTypeList;
13493  RecordTypeList.push_back(Ty);
13494  unsigned NextToCheckIndex = 0;
13495  // We walk the record hierarchy breadth-first to ensure that we print
13496  // diagnostics in field nesting order.
13497  while (RecordTypeList.size() > NextToCheckIndex) {
13498  bool IsNested = NextToCheckIndex > 0;
13499  for (const FieldDecl *Field :
13500  RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13501  // First, check every field for constness.
13502  QualType FieldTy = Field->getType();
13503  if (FieldTy.isConstQualified()) {
13504  if (!DiagnosticEmitted) {
13505  S.Diag(Loc, diag::err_typecheck_assign_const)
13506  << Range << NestedConstMember << OEK << VD
13507  << IsNested << Field;
13508  DiagnosticEmitted = true;
13509  }
13510  S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13511  << NestedConstMember << IsNested << Field
13512  << FieldTy << Field->getSourceRange();
13513  }
13514 
13515  // Then we append it to the list to check next in order.
13516  FieldTy = FieldTy.getCanonicalType();
13517  if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13518  if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13519  RecordTypeList.push_back(FieldRecTy);
13520  }
13521  }
13522  ++NextToCheckIndex;
13523  }
13524 }
13525 
13526 /// Emit an error for the case where a record we are trying to assign to has a
13527 /// const-qualified field somewhere in its hierarchy.
13528 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13529  SourceLocation Loc) {
13530  QualType Ty = E->getType();
13531  assert(Ty->isRecordType() && "lvalue was not record?");
13533  const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13534  bool DiagEmitted = false;
13535 
13536  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13537  DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13538  Range, OEK_Member, DiagEmitted);
13539  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13540  DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13541  Range, OEK_Variable, DiagEmitted);
13542  else
13543  DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13544  Range, OEK_LValue, DiagEmitted);
13545  if (!DiagEmitted)
13547 }
13548 
13549 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13550 /// emit an error and return true. If so, return false.
13552  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13553 
13555 
13556  SourceLocation OrigLoc = Loc;
13558  &Loc);
13559  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13561  if (IsLV == Expr::MLV_Valid)
13562  return false;
13563 
13564  unsigned DiagID = 0;
13565  bool NeedType = false;
13566  switch (IsLV) { // C99 6.5.16p2
13568  // Use a specialized diagnostic when we're assigning to an object
13569  // from an enclosing function or block.
13571  if (NCCK == NCCK_Block)
13572  DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13573  else
13574  DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13575  break;
13576  }
13577 
13578  // In ARC, use some specialized diagnostics for occasions where we
13579  // infer 'const'. These are always pseudo-strong variables.
13580  if (S.getLangOpts().ObjCAutoRefCount) {
13581  DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13582  if (declRef && isa<VarDecl>(declRef->getDecl())) {
13583  VarDecl *var = cast<VarDecl>(declRef->getDecl());
13584 
13585  // Use the normal diagnostic if it's pseudo-__strong but the
13586  // user actually wrote 'const'.
13587  if (var->isARCPseudoStrong() &&
13588  (!var->getTypeSourceInfo() ||
13589  !var->getTypeSourceInfo()->getType().isConstQualified())) {
13590  // There are three pseudo-strong cases:
13591  // - self
13592  ObjCMethodDecl *method = S.getCurMethodDecl();
13593  if (method && var == method->getSelfDecl()) {
13594  DiagID = method->isClassMethod()
13595  ? diag::err_typecheck_arc_assign_self_class_method
13596  : diag::err_typecheck_arc_assign_self;
13597 
13598  // - Objective-C externally_retained attribute.
13599  } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13600  isa<ParmVarDecl>(var)) {
13601  DiagID = diag::err_typecheck_arc_assign_externally_retained;
13602 
13603  // - fast enumeration variables
13604  } else {
13605  DiagID = diag::err_typecheck_arr_assign_enumeration;
13606  }
13607 
13608  SourceRange Assign;
13609  if (Loc != OrigLoc)
13610  Assign = SourceRange(OrigLoc, OrigLoc);
13611  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13612  // We need to preserve the AST regardless, so migration tool
13613  // can do its job.
13614  return false;
13615  }
13616  }
13617  }
13618 
13619  // If none of the special cases above are triggered, then this is a
13620  // simple const assignment.
13621  if (DiagID == 0) {
13623  return true;
13624  }
13625 
13626  break;
13629  return true;
13632  return true;
13633  case Expr::MLV_ArrayType:
13635  DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13636  NeedType = true;
13637  break;
13639  DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13640  NeedType = true;
13641  break;
13642  case Expr::MLV_LValueCast:
13643  DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13644  break;
13645  case Expr::MLV_Valid:
13646  llvm_unreachable("did not take early return for MLV_Valid");
13650  DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13651  break;
13654  return S.RequireCompleteType(Loc, E->getType(),
13655  diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13657  DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13658  break;
13660  llvm_unreachable("readonly properties should be processed differently");
13662  DiagID = diag::err_readonly_message_assignment;
13663  break;
13665  DiagID = diag::err_no_subobject_property_setting;
13666  break;
13667  }
13668 
13669  SourceRange Assign;
13670  if (Loc != OrigLoc)
13671  Assign = SourceRange(OrigLoc, OrigLoc);
13672  if (NeedType)
13673  S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13674  else
13675  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13676  return true;
13677 }
13678 
13679 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13681  Sema &Sema) {
13683  return;
13684  if (Sema.isUnevaluatedContext())
13685  return;
13686  if (Loc.isInvalid() || Loc.isMacroID())
13687  return;
13688  if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13689  return;
13690 
13691  // C / C++ fields
13692  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13693  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13694  if (ML && MR) {
13695  if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13696  return;
13697  const ValueDecl *LHSDecl =
13698  cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13699  const ValueDecl *RHSDecl =
13700  cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13701  if (LHSDecl != RHSDecl)
13702  return;
13703  if (LHSDecl->getType().isVolatileQualified())
13704  return;
13705  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13706  if (RefTy->getPointeeType().isVolatileQualified())
13707  return;
13708 
13709  Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13710  }
13711 
13712  // Objective-C instance variables
13713  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13714  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13715  if (OL && OR && OL->getDecl() == OR->getDecl()) {
13716  DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13717  DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13718  if (RL && RR && RL->getDecl() == RR->getDecl())
13719  Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13720  }
13721 }
13722 
13723 // C99 6.5.16.1
13726  QualType CompoundType,
13727  BinaryOperatorKind Opc) {
13728  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13729 
13730  // Verify that LHS is a modifiable lvalue, and emit error if not.
13731  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13732  return QualType();
13733 
13734  QualType LHSType = LHSExpr->getType();
13735  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13736  CompoundType;
13737  // OpenCL v1.2 s6.1.1.1 p2:
13738  // The half data type can only be used to declare a pointer to a buffer that
13739  // contains half values
13740  if (getLangOpts().OpenCL &&
13741  !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13742  LHSType->isHalfType()) {
13743  Diag(Loc, diag::err_opencl_half_load_store) << 1
13744  << LHSType.getUnqualifiedType();
13745  return QualType();
13746  }
13747 
13748  // WebAssembly tables can't be used on RHS of an assignment expression.
13749  if (RHSType->isWebAssemblyTableType()) {
13750  Diag(Loc, diag::err_wasm_table_art) << 0;
13751  return QualType();
13752  }
13753 
13754  AssignConvertType ConvTy;
13755  if (CompoundType.isNull()) {
13756  Expr *RHSCheck = RHS.get();
13757 
13758  CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13759 
13760  QualType LHSTy(LHSType);
13761  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13762  if (RHS.isInvalid())
13763  return QualType();
13764  // Special case of NSObject attributes on c-style pointer types.
13765  if (ConvTy == IncompatiblePointer &&
13766  ((Context.isObjCNSObjectType(LHSType) &&
13767  RHSType->isObjCObjectPointerType()) ||
13768  (Context.isObjCNSObjectType(RHSType) &&
13769  LHSType->isObjCObjectPointerType())))
13770  ConvTy = Compatible;
13771 
13772  if (ConvTy == Compatible &&
13773  LHSType->isObjCObjectType())
13774  Diag(Loc, diag::err_objc_object_assignment)
13775  << LHSType;
13776 
13777  // If the RHS is a unary plus or minus, check to see if they = and + are
13778  // right next to each other. If so, the user may have typo'd "x =+ 4"
13779  // instead of "x += 4".
13780  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13781  RHSCheck = ICE->getSubExpr();
13782  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13783  if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13784  Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13785  // Only if the two operators are exactly adjacent.
13786  Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13787  // And there is a space or other character before the subexpr of the
13788  // unary +/-. We don't want to warn on "x=-1".
13789  Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13790  UO->getSubExpr()->getBeginLoc().isFileID()) {
13791  Diag(Loc, diag::warn_not_compound_assign)
13792  << (UO->getOpcode() == UO_Plus ? "+" : "-")
13793  << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13794  }
13795  }
13796 
13797  if (ConvTy == Compatible) {
13798  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13799  // Warn about retain cycles where a block captures the LHS, but
13800  // not if the LHS is a simple variable into which the block is
13801  // being stored...unless that variable can be captured by reference!
13802  const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13803  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13804  if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13805  ObjC().checkRetainCycles(LHSExpr, RHS.get());
13806  }
13807 
13808  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13809  LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13810  // It is safe to assign a weak reference into a strong variable.
13811  // Although this code can still have problems:
13812  // id x = self.weakProp;
13813  // id y = self.weakProp;
13814  // we do not warn to warn spuriously when 'x' and 'y' are on separate
13815  // paths through the function. This should be revisited if
13816  // -Wrepeated-use-of-weak is made flow-sensitive.
13817  // For ObjCWeak only, we do not warn if the assign is to a non-weak
13818  // variable, which will be valid for the current autorelease scope.
13819  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13820  RHS.get()->getBeginLoc()))
13821  getCurFunction()->markSafeWeakUse(RHS.get());
13822 
13823  } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13824  checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13825  }
13826  }
13827  } else {
13828  // Compound assignment "x += y"
13829  ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13830  }
13831 
13832  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13833  RHS.get(), AA_Assigning))
13834  return QualType();
13835 
13836  CheckForNullPointerDereference(*this, LHSExpr);
13837 
13838  if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13839  if (CompoundType.isNull()) {
13840  // C++2a [expr.ass]p5:
13841  // A simple-assignment whose left operand is of a volatile-qualified
13842  // type is deprecated unless the assignment is either a discarded-value
13843  // expression or an unevaluated operand
13844  ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13845  }
13846  }
13847 
13848  // C11 6.5.16p3: The type of an assignment expression is the type of the
13849  // left operand would have after lvalue conversion.
13850  // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13851  // qualified type, the value has the unqualified version of the type of the
13852  // lvalue; additionally, if the lvalue has atomic type, the value has the
13853  // non-atomic version of the type of the lvalue.
13854  // C++ 5.17p1: the type of the assignment expression is that of its left
13855  // operand.
13856  return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13857 }
13858 
13859 // Scenarios to ignore if expression E is:
13860 // 1. an explicit cast expression into void
13861 // 2. a function call expression that returns void
13862 static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13863  E = E->IgnoreParens();
13864 
13865  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13866  if (CE->getCastKind() == CK_ToVoid) {
13867  return true;
13868  }
13869 
13870  // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13871  if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13872  CE->getSubExpr()->getType()->isDependentType()) {
13873  return true;
13874  }
13875  }
13876 
13877  if (const auto *CE = dyn_cast<CallExpr>(E))
13878  return CE->getCallReturnType(Context)->isVoidType();
13879  return false;
13880 }
13881 
13882 // Look for instances where it is likely the comma operator is confused with
13883 // another operator. There is an explicit list of acceptable expressions for
13884 // the left hand side of the comma operator, otherwise emit a warning.
13886  // No warnings in macros
13887  if (Loc.isMacroID())
13888  return;
13889 
13890  // Don't warn in template instantiations.
13891  if (inTemplateInstantiation())
13892  return;
13893 
13894  // Scope isn't fine-grained enough to explicitly list the specific cases, so
13895  // instead, skip more than needed, then call back into here with the
13896  // CommaVisitor in SemaStmt.cpp.
13897  // The listed locations are the initialization and increment portions
13898  // of a for loop. The additional checks are on the condition of
13899  // if statements, do/while loops, and for loops.
13900  // Differences in scope flags for C89 mode requires the extra logic.
13901  const unsigned ForIncrementFlags =
13902  getLangOpts().C99 || getLangOpts().CPlusPlus
13905  const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13906  const unsigned ScopeFlags = getCurScope()->getFlags();
13907  if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13908  (ScopeFlags & ForInitFlags) == ForInitFlags)
13909  return;
13910 
13911  // If there are multiple comma operators used together, get the RHS of the
13912  // of the comma operator as the LHS.
13913  while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13914  if (BO->getOpcode() != BO_Comma)
13915  break;
13916  LHS = BO->getRHS();
13917  }
13918 
13919  // Only allow some expressions on LHS to not warn.
13920  if (IgnoreCommaOperand(LHS, Context))
13921  return;
13922 
13923  Diag(Loc, diag::warn_comma_operator);
13924  Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13925  << LHS->getSourceRange()
13927  LangOpts.CPlusPlus ? "static_cast<void>("
13928  : "(void)(")
13929  << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13930  ")");
13931 }
13932 
13933 // C99 6.5.17
13935  SourceLocation Loc) {
13936  LHS = S.CheckPlaceholderExpr(LHS.get());
13937  RHS = S.CheckPlaceholderExpr(RHS.get());
13938  if (LHS.isInvalid() || RHS.isInvalid())
13939  return QualType();
13940 
13941  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13942  // operands, but not unary promotions.
13943  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13944 
13945  // So we treat the LHS as a ignored value, and in C++ we allow the
13946  // containing site to determine what should be done with the RHS.
13947  LHS = S.IgnoredValueConversions(LHS.get());
13948  if (LHS.isInvalid())
13949  return QualType();
13950 
13951  S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13952 
13953  if (!S.getLangOpts().CPlusPlus) {
13955  if (RHS.isInvalid())
13956  return QualType();
13957  if (!RHS.get()->getType()->isVoidType())
13958  S.RequireCompleteType(Loc, RHS.get()->getType(),
13959  diag::err_incomplete_type);
13960  }
13961 
13962  if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13963  S.DiagnoseCommaOperator(LHS.get(), Loc);
13964 
13965  return RHS.get()->getType();
13966 }
13967 
13968 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13969 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13971  ExprValueKind &VK,
13972  ExprObjectKind &OK,
13973  SourceLocation OpLoc, bool IsInc,
13974  bool IsPrefix) {
13975  QualType ResType = Op->getType();
13976  // Atomic types can be used for increment / decrement where the non-atomic
13977  // versions can, so ignore the _Atomic() specifier for the purpose of
13978  // checking.
13979  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13980  ResType = ResAtomicType->getValueType();
13981 
13982  assert(!ResType.isNull() && "no type for increment/decrement expression");
13983 
13984  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13985  // Decrement of bool is not allowed.
13986  if (!IsInc) {
13987  S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13988  return QualType();
13989  }
13990  // Increment of bool sets it to true, but is deprecated.
13991  S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13992  : diag::warn_increment_bool)
13993  << Op->getSourceRange();
13994  } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13995  // Error on enum increments and decrements in C++ mode
13996  S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13997  return QualType();
13998  } else if (ResType->isRealType()) {
13999  // OK!
14000  } else if (ResType->isPointerType()) {
14001  // C99 6.5.2.4p2, 6.5.6p2
14002  if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14003  return QualType();
14004  } else if (ResType->isObjCObjectPointerType()) {
14005  // On modern runtimes, ObjC pointer arithmetic is forbidden.
14006  // Otherwise, we just need a complete type.
14007  if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14008  checkArithmeticOnObjCPointer(S, OpLoc, Op))
14009  return QualType();
14010  } else if (ResType->isAnyComplexType()) {
14011  // C99 does not support ++/-- on complex types, we allow as an extension.
14012  S.Diag(OpLoc, diag::ext_increment_complex)
14013  << IsInc << Op->getSourceRange();
14014  } else if (ResType->isPlaceholderType()) {
14015  ExprResult PR = S.CheckPlaceholderExpr(Op);
14016  if (PR.isInvalid()) return QualType();
14017  return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14018  IsInc, IsPrefix);
14019  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14020  // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14021  } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14022  (ResType->castAs<VectorType>()->getVectorKind() !=
14024  // The z vector extensions allow ++ and -- for non-bool vectors.
14025  } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14026  ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14027  // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14028  } else {
14029  S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14030  << ResType << int(IsInc) << Op->getSourceRange();
14031  return QualType();
14032  }
14033  // At this point, we know we have a real, complex or pointer type.
14034  // Now make sure the operand is a modifiable lvalue.
14035  if (CheckForModifiableLvalue(Op, OpLoc, S))
14036  return QualType();
14037  if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14038  // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14039  // An operand with volatile-qualified type is deprecated
14040  S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14041  << IsInc << ResType;
14042  }
14043  // In C++, a prefix increment is the same type as the operand. Otherwise
14044  // (in C or with postfix), the increment is the unqualified type of the
14045  // operand.
14046  if (IsPrefix && S.getLangOpts().CPlusPlus) {
14047  VK = VK_LValue;
14048  OK = Op->getObjectKind();
14049  return ResType;
14050  } else {
14051  VK = VK_PRValue;
14052  return ResType.getUnqualifiedType();
14053  }
14054 }
14055 
14056 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14057 /// This routine allows us to typecheck complex/recursive expressions
14058 /// where the declaration is needed for type checking. We only need to
14059 /// handle cases when the expression references a function designator
14060 /// or is an lvalue. Here are some examples:
14061 /// - &(x) => x
14062 /// - &*****f => f for f a function designator.
14063 /// - &s.xx => s
14064 /// - &s.zz[1].yy -> s, if zz is an array
14065 /// - *(x + 1) -> x, if x is an array
14066 /// - &"123"[2] -> 0
14067 /// - & __real__ x -> x
14068 ///
14069 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14070 /// members.
14072  switch (E->getStmtClass()) {
14073  case Stmt::DeclRefExprClass:
14074  return cast<DeclRefExpr>(E)->getDecl();
14075  case Stmt::MemberExprClass:
14076  // If this is an arrow operator, the address is an offset from
14077  // the base's value, so the object the base refers to is
14078  // irrelevant.
14079  if (cast<MemberExpr>(E)->isArrow())
14080  return nullptr;
14081  // Otherwise, the expression refers to a part of the base
14082  return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14083  case Stmt::ArraySubscriptExprClass: {
14084  // FIXME: This code shouldn't be necessary! We should catch the implicit
14085  // promotion of register arrays earlier.
14086  Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14087  if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14088  if (ICE->getSubExpr()->getType()->isArrayType())
14089  return getPrimaryDecl(ICE->getSubExpr());
14090  }
14091  return nullptr;
14092  }
14093  case Stmt::UnaryOperatorClass: {
14094  UnaryOperator *UO = cast<UnaryOperator>(E);
14095 
14096  switch(UO->getOpcode()) {
14097  case UO_Real:
14098  case UO_Imag:
14099  case UO_Extension:
14100  return getPrimaryDecl(UO->getSubExpr());
14101  default:
14102  return nullptr;
14103  }
14104  }
14105  case Stmt::ParenExprClass:
14106  return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14107  case Stmt::ImplicitCastExprClass:
14108  // If the result of an implicit cast is an l-value, we care about
14109  // the sub-expression; otherwise, the result here doesn't matter.
14110  return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14111  case Stmt::CXXUuidofExprClass:
14112  return cast<CXXUuidofExpr>(E)->getGuidDecl();
14113  default:
14114  return nullptr;
14115  }
14116 }
14117 
14118 namespace {
14119 enum {
14120  AO_Bit_Field = 0,
14121  AO_Vector_Element = 1,
14122  AO_Property_Expansion = 2,
14123  AO_Register_Variable = 3,
14124  AO_Matrix_Element = 4,
14125  AO_No_Error = 5
14126 };
14127 }
14128 /// Diagnose invalid operand for address of operations.
14129 ///
14130 /// \param Type The type of operand which cannot have its address taken.
14132  Expr *E, unsigned Type) {
14133  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14134 }
14135 
14137  const Expr *Op,
14138  const CXXMethodDecl *MD) {
14139  const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14140 
14141  if (Op != DRE)
14142  return Diag(OpLoc, diag::err_parens_pointer_member_function)
14143  << Op->getSourceRange();
14144 
14145  // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14146  if (isa<CXXDestructorDecl>(MD))
14147  return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14148  << DRE->getSourceRange();
14149 
14150  if (DRE->getQualifier())
14151  return false;
14152 
14153  if (MD->getParent()->getName().empty())
14154  return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14155  << DRE->getSourceRange();
14156 
14157  SmallString<32> Str;
14158  StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14159  return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14160  << DRE->getSourceRange()
14161  << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14162 }
14163 
14164 /// CheckAddressOfOperand - The operand of & must be either a function
14165 /// designator or an lvalue designating an object. If it is an lvalue, the
14166 /// object cannot be declared with storage class register or be a bit field.
14167 /// Note: The usual conversions are *not* applied to the operand of the &
14168 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14169 /// In C++, the operand might be an overloaded function name, in which case
14170 /// we allow the '&' but retain the overloaded-function type.
14172  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14173  if (PTy->getKind() == BuiltinType::Overload) {
14174  Expr *E = OrigOp.get()->IgnoreParens();
14175  if (!isa<OverloadExpr>(E)) {
14176  assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14177  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14178  << OrigOp.get()->getSourceRange();
14179  return QualType();
14180  }
14181 
14182  OverloadExpr *Ovl = cast<OverloadExpr>(E);
14183  if (isa<UnresolvedMemberExpr>(Ovl))
14184  if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14185  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14186  << OrigOp.get()->getSourceRange();
14187  return QualType();
14188  }
14189 
14190  return Context.OverloadTy;
14191  }
14192 
14193  if (PTy->getKind() == BuiltinType::UnknownAny)
14194  return Context.UnknownAnyTy;
14195 
14196  if (PTy->getKind() == BuiltinType::BoundMember) {
14197  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14198  << OrigOp.get()->getSourceRange();
14199  return QualType();
14200  }
14201 
14202  OrigOp = CheckPlaceholderExpr(OrigOp.get());
14203  if (OrigOp.isInvalid()) return QualType();
14204  }
14205 
14206  if (OrigOp.get()->isTypeDependent())
14207  return Context.DependentTy;
14208 
14209  assert(!OrigOp.get()->hasPlaceholderType());
14210 
14211  // Make sure to ignore parentheses in subsequent checks
14212  Expr *op = OrigOp.get()->IgnoreParens();
14213 
14214  // In OpenCL captures for blocks called as lambda functions
14215  // are located in the private address space. Blocks used in
14216  // enqueue_kernel can be located in a different address space
14217  // depending on a vendor implementation. Thus preventing
14218  // taking an address of the capture to avoid invalid AS casts.
14219  if (LangOpts.OpenCL) {
14220  auto* VarRef = dyn_cast<DeclRefExpr>(op);
14221  if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14222  Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14223  return QualType();
14224  }
14225  }
14226 
14227  if (getLangOpts().C99) {
14228  // Implement C99-only parts of addressof rules.
14229  if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14230  if (uOp->getOpcode() == UO_Deref)
14231  // Per C99 6.5.3.2, the address of a deref always returns a valid result
14232  // (assuming the deref expression is valid).
14233  return uOp->getSubExpr()->getType();
14234  }
14235  // Technically, there should be a check for array subscript
14236  // expressions here, but the result of one is always an lvalue anyway.
14237  }
14238  ValueDecl *dcl = getPrimaryDecl(op);
14239 
14240  if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14241  if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14242  op->getBeginLoc()))
14243  return QualType();
14244 
14245  Expr::LValueClassification lval = op->ClassifyLValue(Context);
14246  unsigned AddressOfError = AO_No_Error;
14247 
14248  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14249  bool sfinae = (bool)isSFINAEContext();
14250  Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14251  : diag::ext_typecheck_addrof_temporary)
14252  << op->getType() << op->getSourceRange();
14253  if (sfinae)
14254  return QualType();
14255  // Materialize the temporary as an lvalue so that we can take its address.
14256  OrigOp = op =
14257  CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14258  } else if (isa<ObjCSelectorExpr>(op)) {
14259  return Context.getPointerType(op->getType());
14260  } else if (lval == Expr::LV_MemberFunction) {
14261  // If it's an instance method, make a member pointer.
14262  // The expression must have exactly the form &A::foo.
14263 
14264  // If the underlying expression isn't a decl ref, give up.
14265  if (!isa<DeclRefExpr>(op)) {
14266  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14267  << OrigOp.get()->getSourceRange();
14268  return QualType();
14269  }
14270  DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14271  CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14272 
14273  CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14274 
14275  QualType MPTy = Context.getMemberPointerType(
14276  op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14277  // Under the MS ABI, lock down the inheritance model now.
14278  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14279  (void)isCompleteType(OpLoc, MPTy);
14280  return MPTy;
14281  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14282  // C99 6.5.3.2p1
14283  // The operand must be either an l-value or a function designator
14284  if (!op->getType()->isFunctionType()) {
14285  // Use a special diagnostic for loads from property references.
14286  if (isa<PseudoObjectExpr>(op)) {
14287  AddressOfError = AO_Property_Expansion;
14288  } else {
14289  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14290  << op->getType() << op->getSourceRange();
14291  return QualType();
14292  }
14293  } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14294  if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14295  CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14296  }
14297 
14298  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14299  // The operand cannot be a bit-field
14300  AddressOfError = AO_Bit_Field;
14301  } else if (op->getObjectKind() == OK_VectorComponent) {
14302  // The operand cannot be an element of a vector
14303  AddressOfError = AO_Vector_Element;
14304  } else if (op->getObjectKind() == OK_MatrixComponent) {
14305  // The operand cannot be an element of a matrix.
14306  AddressOfError = AO_Matrix_Element;
14307  } else if (dcl) { // C99 6.5.3.2p1
14308  // We have an lvalue with a decl. Make sure the decl is not declared
14309  // with the register storage-class specifier.
14310  if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14311  // in C++ it is not error to take address of a register
14312  // variable (c++03 7.1.1P3)
14313  if (vd->getStorageClass() == SC_Register &&
14314  !getLangOpts().CPlusPlus) {
14315  AddressOfError = AO_Register_Variable;
14316  }
14317  } else if (isa<MSPropertyDecl>(dcl)) {
14318  AddressOfError = AO_Property_Expansion;
14319  } else if (isa<FunctionTemplateDecl>(dcl)) {
14320  return Context.OverloadTy;
14321  } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14322  // Okay: we can take the address of a field.
14323  // Could be a pointer to member, though, if there is an explicit
14324  // scope qualifier for the class.
14325  if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14326  DeclContext *Ctx = dcl->getDeclContext();
14327  if (Ctx && Ctx->isRecord()) {
14328  if (dcl->getType()->isReferenceType()) {
14329  Diag(OpLoc,
14330  diag::err_cannot_form_pointer_to_member_of_reference_type)
14331  << dcl->getDeclName() << dcl->getType();
14332  return QualType();
14333  }
14334 
14335  // C++11 [expr.unary.op] p4:
14336  // A pointer to member is only formed when an explicit & is used and
14337  // its operand is a qualified-id not enclosed in parentheses.
14338  if (isa<ParenExpr>(OrigOp.get())) {
14339  SourceLocation LeftParenLoc = OrigOp.get()->getBeginLoc(),
14340  RightParenLoc = OrigOp.get()->getEndLoc();
14341 
14342  Diag(LeftParenLoc,
14343  diag::err_form_ptr_to_member_from_parenthesized_expr)
14344  << SourceRange(OpLoc, RightParenLoc)
14345  << FixItHint::CreateRemoval(LeftParenLoc)
14346  << FixItHint::CreateRemoval(RightParenLoc);
14347 
14348  // Continuing might lead to better error recovery.
14349  }
14350 
14351  while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14352  Ctx = Ctx->getParent();
14353 
14354  QualType MPTy = Context.getMemberPointerType(
14355  op->getType(),
14356  Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14357  // Under the MS ABI, lock down the inheritance model now.
14358  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14359  (void)isCompleteType(OpLoc, MPTy);
14360  return MPTy;
14361  }
14362  }
14365  llvm_unreachable("Unknown/unexpected decl type");
14366  }
14367 
14368  if (AddressOfError != AO_No_Error) {
14369  diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14370  return QualType();
14371  }
14372 
14373  if (lval == Expr::LV_IncompleteVoidType) {
14374  // Taking the address of a void variable is technically illegal, but we
14375  // allow it in cases which are otherwise valid.
14376  // Example: "extern void x; void* y = &x;".
14377  Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14378  }
14379 
14380  // If the operand has type "type", the result has type "pointer to type".
14381  if (op->getType()->isObjCObjectType())
14382  return Context.getObjCObjectPointerType(op->getType());
14383 
14384  // Cannot take the address of WebAssembly references or tables.
14385  if (Context.getTargetInfo().getTriple().isWasm()) {
14386  QualType OpTy = op->getType();
14387  if (OpTy.isWebAssemblyReferenceType()) {
14388  Diag(OpLoc, diag::err_wasm_ca_reference)
14389  << 1 << OrigOp.get()->getSourceRange();
14390  return QualType();
14391  }
14392  if (OpTy->isWebAssemblyTableType()) {
14393  Diag(OpLoc, diag::err_wasm_table_pr)
14394  << 1 << OrigOp.get()->getSourceRange();
14395  return QualType();
14396  }
14397  }
14398 
14399  CheckAddressOfPackedMember(op);
14400 
14401  return Context.getPointerType(op->getType());
14402 }
14403 
14404 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14405  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14406  if (!DRE)
14407  return;
14408  const Decl *D = DRE->getDecl();
14409  if (!D)
14410  return;
14411  const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14412  if (!Param)
14413  return;
14414  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14415  if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14416  return;
14417  if (FunctionScopeInfo *FD = S.getCurFunction())
14418  FD->ModifiedNonNullParams.insert(Param);
14419 }
14420 
14421 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14423  SourceLocation OpLoc,
14424  bool IsAfterAmp = false) {
14425  ExprResult ConvResult = S.UsualUnaryConversions(Op);
14426  if (ConvResult.isInvalid())
14427  return QualType();
14428  Op = ConvResult.get();
14429  QualType OpTy = Op->getType();
14430  QualType Result;
14431 
14432  if (isa<CXXReinterpretCastExpr>(Op)) {
14433  QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14434  S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14435  Op->getSourceRange());
14436  }
14437 
14438  if (const PointerType *PT = OpTy->getAs<PointerType>())
14439  {
14440  Result = PT->getPointeeType();
14441  }
14442  else if (const ObjCObjectPointerType *OPT =
14443  OpTy->getAs<ObjCObjectPointerType>())
14444  Result = OPT->getPointeeType();
14445  else {
14446  ExprResult PR = S.CheckPlaceholderExpr(Op);
14447  if (PR.isInvalid()) return QualType();
14448  if (PR.get() != Op)
14449  return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14450  }
14451 
14452  if (Result.isNull()) {
14453  S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14454  << OpTy << Op->getSourceRange();
14455  return QualType();
14456  }
14457 
14458  if (Result->isVoidType()) {
14459  // C++ [expr.unary.op]p1:
14460  // [...] the expression to which [the unary * operator] is applied shall
14461  // be a pointer to an object type, or a pointer to a function type
14462  LangOptions LO = S.getLangOpts();
14463  if (LO.CPlusPlus)
14464  S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14465  << OpTy << Op->getSourceRange();
14466  else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14467  S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14468  << OpTy << Op->getSourceRange();
14469  }
14470 
14471  // Dereferences are usually l-values...
14472  VK = VK_LValue;
14473 
14474  // ...except that certain expressions are never l-values in C.
14475  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14476  VK = VK_PRValue;
14477 
14478  return Result;
14479 }
14480 
14481 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14482  BinaryOperatorKind Opc;
14483  switch (Kind) {
14484  default: llvm_unreachable("Unknown binop!");
14485  case tok::periodstar: Opc = BO_PtrMemD; break;
14486  case tok::arrowstar: Opc = BO_PtrMemI; break;
14487  case tok::star: Opc = BO_Mul; break;
14488  case tok::slash: Opc = BO_Div; break;
14489  case tok::percent: Opc = BO_Rem; break;
14490  case tok::plus: Opc = BO_Add; break;
14491  case tok::minus: Opc = BO_Sub; break;
14492  case tok::lessless: Opc = BO_Shl; break;
14493  case tok::greatergreater: Opc = BO_Shr; break;
14494  case tok::lessequal: Opc = BO_LE; break;
14495  case tok::less: Opc = BO_LT; break;
14496  case tok::greaterequal: Opc = BO_GE; break;
14497  case tok::greater: Opc = BO_GT; break;
14498  case tok::exclaimequal: Opc = BO_NE; break;
14499  case tok::equalequal: Opc = BO_EQ; break;
14500  case tok::spaceship: Opc = BO_Cmp; break;
14501  case tok::amp: Opc = BO_And; break;
14502  case tok::caret: Opc = BO_Xor; break;
14503  case tok::pipe: Opc = BO_Or; break;
14504  case tok::ampamp: Opc = BO_LAnd; break;
14505  case tok::pipepipe: Opc = BO_LOr; break;
14506  case tok::equal: Opc = BO_Assign; break;
14507  case tok::starequal: Opc = BO_MulAssign; break;
14508  case tok::slashequal: Opc = BO_DivAssign; break;
14509  case tok::percentequal: Opc = BO_RemAssign; break;
14510  case tok::plusequal: Opc = BO_AddAssign; break;
14511  case tok::minusequal: Opc = BO_SubAssign; break;
14512  case tok::lesslessequal: Opc = BO_ShlAssign; break;
14513  case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14514  case tok::ampequal: Opc = BO_AndAssign; break;
14515  case tok::caretequal: Opc = BO_XorAssign; break;
14516  case tok::pipeequal: Opc = BO_OrAssign; break;
14517  case tok::comma: Opc = BO_Comma; break;
14518  }
14519  return Opc;
14520 }
14521 
14523  tok::TokenKind Kind) {
14524  UnaryOperatorKind Opc;
14525  switch (Kind) {
14526  default: llvm_unreachable("Unknown unary op!");
14527  case tok::plusplus: Opc = UO_PreInc; break;
14528  case tok::minusminus: Opc = UO_PreDec; break;
14529  case tok::amp: Opc = UO_AddrOf; break;
14530  case tok::star: Opc = UO_Deref; break;
14531  case tok::plus: Opc = UO_Plus; break;
14532  case tok::minus: Opc = UO_Minus; break;
14533  case tok::tilde: Opc = UO_Not; break;
14534  case tok::exclaim: Opc = UO_LNot; break;
14535  case tok::kw___real: Opc = UO_Real; break;
14536  case tok::kw___imag: Opc = UO_Imag; break;
14537  case tok::kw___extension__: Opc = UO_Extension; break;
14538  }
14539  return Opc;
14540 }
14541 
14542 const FieldDecl *
14544  // Explore the case for adding 'this->' to the LHS of a self assignment, very
14545  // common for setters.
14546  // struct A {
14547  // int X;
14548  // -void setX(int X) { X = X; }
14549  // +void setX(int X) { this->X = X; }
14550  // };
14551 
14552  // Only consider parameters for self assignment fixes.
14553  if (!isa<ParmVarDecl>(SelfAssigned))
14554  return nullptr;
14555  const auto *Method =
14556  dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14557  if (!Method)
14558  return nullptr;
14559 
14560  const CXXRecordDecl *Parent = Method->getParent();
14561  // In theory this is fixable if the lambda explicitly captures this, but
14562  // that's added complexity that's rarely going to be used.
14563  if (Parent->isLambda())
14564  return nullptr;
14565 
14566  // FIXME: Use an actual Lookup operation instead of just traversing fields
14567  // in order to get base class fields.
14568  auto Field =
14569  llvm::find_if(Parent->fields(),
14570  [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14571  return F->getDeclName() == Name;
14572  });
14573  return (Field != Parent->field_end()) ? *Field : nullptr;
14574 }
14575 
14576 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14577 /// This warning suppressed in the event of macro expansions.
14578 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14579  SourceLocation OpLoc, bool IsBuiltin) {
14580  if (S.inTemplateInstantiation())
14581  return;
14582  if (S.isUnevaluatedContext())
14583  return;
14584  if (OpLoc.isInvalid() || OpLoc.isMacroID())
14585  return;
14586  LHSExpr = LHSExpr->IgnoreParenImpCasts();
14587  RHSExpr = RHSExpr->IgnoreParenImpCasts();
14588  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14589  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14590  if (!LHSDeclRef || !RHSDeclRef ||
14591  LHSDeclRef->getLocation().isMacroID() ||
14592  RHSDeclRef->getLocation().isMacroID())
14593  return;
14594  const ValueDecl *LHSDecl =
14595  cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14596  const ValueDecl *RHSDecl =
14597  cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14598  if (LHSDecl != RHSDecl)
14599  return;
14600  if (LHSDecl->getType().isVolatileQualified())
14601  return;
14602  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14603  if (RefTy->getPointeeType().isVolatileQualified())
14604  return;
14605 
14606  auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14607  : diag::warn_self_assignment_overloaded)
14608  << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14609  << RHSExpr->getSourceRange();
14610  if (const FieldDecl *SelfAssignField =
14612  Diag << 1 << SelfAssignField
14613  << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14614  else
14615  Diag << 0;
14616 }
14617 
14618 /// Check if a bitwise-& is performed on an Objective-C pointer. This
14619 /// is usually indicative of introspection within the Objective-C pointer.
14621  SourceLocation OpLoc) {
14622  if (!S.getLangOpts().ObjC)
14623  return;
14624 
14625  const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14626  const Expr *LHS = L.get();
14627  const Expr *RHS = R.get();
14628 
14630  ObjCPointerExpr = LHS;
14631  OtherExpr = RHS;
14632  }
14633  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14634  ObjCPointerExpr = RHS;
14635  OtherExpr = LHS;
14636  }
14637 
14638  // This warning is deliberately made very specific to reduce false
14639  // positives with logic that uses '&' for hashing. This logic mainly
14640  // looks for code trying to introspect into tagged pointers, which
14641  // code should generally never do.
14642  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14643  unsigned Diag = diag::warn_objc_pointer_masking;
14644  // Determine if we are introspecting the result of performSelectorXXX.
14645  const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14646  // Special case messages to -performSelector and friends, which
14647  // can return non-pointer values boxed in a pointer value.
14648  // Some clients may wish to silence warnings in this subcase.
14649  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14650  Selector S = ME->getSelector();
14651  StringRef SelArg0 = S.getNameForSlot(0);
14652  if (SelArg0.starts_with("performSelector"))
14653  Diag = diag::warn_objc_pointer_masking_performSelector;
14654  }
14655 
14656  S.Diag(OpLoc, Diag)
14657  << ObjCPointerExpr->getSourceRange();
14658  }
14659 }
14660 
14662  if (!E)
14663  return nullptr;
14664  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14665  return DRE->getDecl();
14666  if (auto *ME = dyn_cast<MemberExpr>(E))
14667  return ME->getMemberDecl();
14668  if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14669  return IRE->getDecl();
14670  return nullptr;
14671 }
14672 
14673 // This helper function promotes a binary operator's operands (which are of a
14674 // half vector type) to a vector of floats and then truncates the result to
14675 // a vector of either half or short.
14677  BinaryOperatorKind Opc, QualType ResultTy,
14679  bool IsCompAssign, SourceLocation OpLoc,
14680  FPOptionsOverride FPFeatures) {
14681  auto &Context = S.getASTContext();
14682  assert((isVector(ResultTy, Context.HalfTy) ||
14683  isVector(ResultTy, Context.ShortTy)) &&
14684  "Result must be a vector of half or short");
14685  assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14686  isVector(RHS.get()->getType(), Context.HalfTy) &&
14687  "both operands expected to be a half vector");
14688 
14689  RHS = convertVector(RHS.get(), Context.FloatTy, S);
14690  QualType BinOpResTy = RHS.get()->getType();
14691 
14692  // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14693  // change BinOpResTy to a vector of ints.
14694  if (isVector(ResultTy, Context.ShortTy))
14695  BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14696 
14697  if (IsCompAssign)
14698  return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14699  ResultTy, VK, OK, OpLoc, FPFeatures,
14700  BinOpResTy, BinOpResTy);
14701 
14702  LHS = convertVector(LHS.get(), Context.FloatTy, S);
14703  auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14704  BinOpResTy, VK, OK, OpLoc, FPFeatures);
14705  return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14706 }
14707 
14708 static std::pair<ExprResult, ExprResult>
14710  Expr *RHSExpr) {
14711  ExprResult LHS = LHSExpr, RHS = RHSExpr;
14712  if (!S.Context.isDependenceAllowed()) {
14713  // C cannot handle TypoExpr nodes on either side of a binop because it
14714  // doesn't handle dependent types properly, so make sure any TypoExprs have
14715  // been dealt with before checking the operands.
14716  LHS = S.CorrectDelayedTyposInExpr(LHS);
14717  RHS = S.CorrectDelayedTyposInExpr(
14718  RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14719  [Opc, LHS](Expr *E) {
14720  if (Opc != BO_Assign)
14721  return ExprResult(E);
14722  // Avoid correcting the RHS to the same Expr as the LHS.
14723  Decl *D = getDeclFromExpr(E);
14724  return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14725  });
14726  }
14727  return std::make_pair(LHS, RHS);
14728 }
14729 
14730 /// Returns true if conversion between vectors of halfs and vectors of floats
14731 /// is needed.
14732 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14733  Expr *E0, Expr *E1 = nullptr) {
14734  if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14736  return false;
14737 
14738  auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14739  QualType Ty = E->IgnoreImplicit()->getType();
14740 
14741  // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14742  // to vectors of floats. Although the element type of the vectors is __fp16,
14743  // the vectors shouldn't be treated as storage-only types. See the
14744  // discussion here: https://reviews.llvm.org/rG825235c140e7
14745  if (const VectorType *VT = Ty->getAs<VectorType>()) {
14746  if (VT->getVectorKind() == VectorKind::Neon)
14747  return false;
14748  return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14749  }
14750  return false;
14751  };
14752 
14753  return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14754 }
14755 
14756 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14757 /// operator @p Opc at location @c TokLoc. This routine only supports
14758 /// built-in operations; ActOnBinOp handles overloaded operators.
14760  BinaryOperatorKind Opc,
14761  Expr *LHSExpr, Expr *RHSExpr) {
14762  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14763  // The syntax only allows initializer lists on the RHS of assignment,
14764  // so we don't need to worry about accepting invalid code for
14765  // non-assignment operators.
14766  // C++11 5.17p9:
14767  // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14768  // of x = {} is x = T().
14770  RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14771  InitializedEntity Entity =
14773  InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14774  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14775  if (Init.isInvalid())
14776  return Init;
14777  RHSExpr = Init.get();
14778  }
14779 
14780  ExprResult LHS = LHSExpr, RHS = RHSExpr;
14781  QualType ResultTy; // Result type of the binary operator.
14782  // The following two variables are used for compound assignment operators
14783  QualType CompLHSTy; // Type of LHS after promotions for computation
14784  QualType CompResultTy; // Type of computation result
14787  bool ConvertHalfVec = false;
14788 
14789  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14790  if (!LHS.isUsable() || !RHS.isUsable())
14791  return ExprError();
14792 
14793  if (getLangOpts().OpenCL) {
14794  QualType LHSTy = LHSExpr->getType();
14795  QualType RHSTy = RHSExpr->getType();
14796  // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14797  // the ATOMIC_VAR_INIT macro.
14798  if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14799  SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14800  if (BO_Assign == Opc)
14801  Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14802  else
14803  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14804  return ExprError();
14805  }
14806 
14807  // OpenCL special types - image, sampler, pipe, and blocks are to be used
14808  // only with a builtin functions and therefore should be disallowed here.
14809  if (LHSTy->isImageType() || RHSTy->isImageType() ||
14810  LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14811  LHSTy->isPipeType() || RHSTy->isPipeType() ||
14812  LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14813  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14814  return ExprError();
14815  }
14816  }
14817 
14818  checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14819  checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14820 
14821  switch (Opc) {
14822  case BO_Assign:
14823  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14824  if (getLangOpts().CPlusPlus &&
14825  LHS.get()->getObjectKind() != OK_ObjCProperty) {
14826  VK = LHS.get()->getValueKind();
14827  OK = LHS.get()->getObjectKind();
14828  }
14829  if (!ResultTy.isNull()) {
14830  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14831  DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14832 
14833  // Avoid copying a block to the heap if the block is assigned to a local
14834  // auto variable that is declared in the same scope as the block. This
14835  // optimization is unsafe if the local variable is declared in an outer
14836  // scope. For example:
14837  //
14838  // BlockTy b;
14839  // {
14840  // b = ^{...};
14841  // }
14842  // // It is unsafe to invoke the block here if it wasn't copied to the
14843  // // heap.
14844  // b();
14845 
14846  if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14847  if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14848  if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14849  if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14850  BE->getBlockDecl()->setCanAvoidCopyToHeap();
14851 
14853  checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14854  NTCUC_Assignment, NTCUK_Copy);
14855  }
14856  RecordModifiableNonNullParam(*this, LHS.get());
14857  break;
14858  case BO_PtrMemD:
14859  case BO_PtrMemI:
14860  ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14861  Opc == BO_PtrMemI);
14862  break;
14863  case BO_Mul:
14864  case BO_Div:
14865  ConvertHalfVec = true;
14866  ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14867  Opc == BO_Div);
14868  break;
14869  case BO_Rem:
14870  ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14871  break;
14872  case BO_Add:
14873  ConvertHalfVec = true;
14874  ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14875  break;
14876  case BO_Sub:
14877  ConvertHalfVec = true;
14878  ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14879  break;
14880  case BO_Shl:
14881  case BO_Shr:
14882  ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14883  break;
14884  case BO_LE:
14885  case BO_LT:
14886  case BO_GE:
14887  case BO_GT:
14888  ConvertHalfVec = true;
14889  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14890 
14891  if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14892  BI && BI->isComparisonOp())
14893  Diag(OpLoc, diag::warn_consecutive_comparison);
14894 
14895  break;
14896  case BO_EQ:
14897  case BO_NE:
14898  ConvertHalfVec = true;
14899  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14900  break;
14901  case BO_Cmp:
14902  ConvertHalfVec = true;
14903  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14904  assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14905  break;
14906  case BO_And:
14907  checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14908  [[fallthrough]];
14909  case BO_Xor:
14910  case BO_Or:
14911  ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14912  break;
14913  case BO_LAnd:
14914  case BO_LOr:
14915  ConvertHalfVec = true;
14916  ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14917  break;
14918  case BO_MulAssign:
14919  case BO_DivAssign:
14920  ConvertHalfVec = true;
14921  CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14922  Opc == BO_DivAssign);
14923  CompLHSTy = CompResultTy;
14924  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14925  ResultTy =
14926  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14927  break;
14928  case BO_RemAssign:
14929  CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14930  CompLHSTy = CompResultTy;
14931  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14932  ResultTy =
14933  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14934  break;
14935  case BO_AddAssign:
14936  ConvertHalfVec = true;
14937  CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14938  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14939  ResultTy =
14940  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14941  break;
14942  case BO_SubAssign:
14943  ConvertHalfVec = true;
14944  CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14945  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14946  ResultTy =
14947  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14948  break;
14949  case BO_ShlAssign:
14950  case BO_ShrAssign:
14951  CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14952  CompLHSTy = CompResultTy;
14953  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14954  ResultTy =
14955  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14956  break;
14957  case BO_AndAssign:
14958  case BO_OrAssign: // fallthrough
14959  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14960  [[fallthrough]];
14961  case BO_XorAssign:
14962  CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14963  CompLHSTy = CompResultTy;
14964  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14965  ResultTy =
14966  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14967  break;
14968  case BO_Comma:
14969  ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14970  if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14971  VK = RHS.get()->getValueKind();
14972  OK = RHS.get()->getObjectKind();
14973  }
14974  break;
14975  }
14976  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14977  return ExprError();
14978 
14979  // Some of the binary operations require promoting operands of half vector to
14980  // float vectors and truncating the result back to half vector. For now, we do
14981  // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14982  // arm64).
14983  assert(
14984  (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14985  isVector(LHS.get()->getType(), Context.HalfTy)) &&
14986  "both sides are half vectors or neither sides are");
14987  ConvertHalfVec =
14988  needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14989 
14990  // Check for array bounds violations for both sides of the BinaryOperator
14991  CheckArrayAccess(LHS.get());
14992  CheckArrayAccess(RHS.get());
14993 
14994  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14995  NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14996  &Context.Idents.get("object_setClass"),
14997  SourceLocation(), LookupOrdinaryName);
14998  if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14999  SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15000  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15002  "object_setClass(")
15003  << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15004  ",")
15005  << FixItHint::CreateInsertion(RHSLocEnd, ")");
15006  }
15007  else
15008  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15009  }
15010  else if (const ObjCIvarRefExpr *OIRE =
15011  dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15012  DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15013 
15014  // Opc is not a compound assignment if CompResultTy is null.
15015  if (CompResultTy.isNull()) {
15016  if (ConvertHalfVec)
15017  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15018  OpLoc, CurFPFeatureOverrides());
15019  return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15020  VK, OK, OpLoc, CurFPFeatureOverrides());
15021  }
15022 
15023  // Handle compound assignments.
15024  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15025  OK_ObjCProperty) {
15026  VK = VK_LValue;
15027  OK = LHS.get()->getObjectKind();
15028  }
15029 
15030  // The LHS is not converted to the result type for fixed-point compound
15031  // assignment as the common type is computed on demand. Reset the CompLHSTy
15032  // to the LHS type we would have gotten after unary conversions.
15033  if (CompResultTy->isFixedPointType())
15034  CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15035 
15036  if (ConvertHalfVec)
15037  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15038  OpLoc, CurFPFeatureOverrides());
15039 
15041  Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15042  CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15043 }
15044 
15045 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15046 /// operators are mixed in a way that suggests that the programmer forgot that
15047 /// comparison operators have higher precedence. The most typical example of
15048 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15050  SourceLocation OpLoc, Expr *LHSExpr,
15051  Expr *RHSExpr) {
15052  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15053  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15054 
15055  // Check that one of the sides is a comparison operator and the other isn't.
15056  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15057  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15058  if (isLeftComp == isRightComp)
15059  return;
15060 
15061  // Bitwise operations are sometimes used as eager logical ops.
15062  // Don't diagnose this.
15063  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15064  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15065  if (isLeftBitwise || isRightBitwise)
15066  return;
15067 
15068  SourceRange DiagRange = isLeftComp
15069  ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15070  : SourceRange(OpLoc, RHSExpr->getEndLoc());
15071  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15072  SourceRange ParensRange =
15073  isLeftComp
15074  ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15075  : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15076 
15077  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15078  << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15079  SuggestParentheses(Self, OpLoc,
15080  Self.PDiag(diag::note_precedence_silence) << OpStr,
15081  (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15082  SuggestParentheses(Self, OpLoc,
15083  Self.PDiag(diag::note_precedence_bitwise_first)
15085  ParensRange);
15086 }
15087 
15088 /// It accepts a '&&' expr that is inside a '||' one.
15089 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15090 /// in parentheses.
15091 static void
15093  BinaryOperator *Bop) {
15094  assert(Bop->getOpcode() == BO_LAnd);
15095  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15096  << Bop->getSourceRange() << OpLoc;
15097  SuggestParentheses(Self, Bop->getOperatorLoc(),
15098  Self.PDiag(diag::note_precedence_silence)
15099  << Bop->getOpcodeStr(),
15100  Bop->getSourceRange());
15101 }
15102 
15103 /// Look for '&&' in the left hand of a '||' expr.
15105  Expr *LHSExpr, Expr *RHSExpr) {
15106  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15107  if (Bop->getOpcode() == BO_LAnd) {
15108  // If it's "string_literal && a || b" don't warn since the precedence
15109  // doesn't matter.
15110  if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15111  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15112  } else if (Bop->getOpcode() == BO_LOr) {
15113  if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15114  // If it's "a || b && string_literal || c" we didn't warn earlier for
15115  // "a || b && string_literal", but warn now.
15116  if (RBop->getOpcode() == BO_LAnd &&
15117  isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15118  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15119  }
15120  }
15121  }
15122 }
15123 
15124 /// Look for '&&' in the right hand of a '||' expr.
15126  Expr *LHSExpr, Expr *RHSExpr) {
15127  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15128  if (Bop->getOpcode() == BO_LAnd) {
15129  // If it's "a || b && string_literal" don't warn since the precedence
15130  // doesn't matter.
15131  if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15132  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15133  }
15134  }
15135 }
15136 
15137 /// Look for bitwise op in the left or right hand of a bitwise op with
15138 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15139 /// the '&' expression in parentheses.
15141  SourceLocation OpLoc, Expr *SubExpr) {
15142  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15143  if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15144  S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15145  << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15146  << Bop->getSourceRange() << OpLoc;
15147  SuggestParentheses(S, Bop->getOperatorLoc(),
15148  S.PDiag(diag::note_precedence_silence)
15149  << Bop->getOpcodeStr(),
15150  Bop->getSourceRange());
15151  }
15152  }
15153 }
15154 
15156  Expr *SubExpr, StringRef Shift) {
15157  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15158  if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15159  StringRef Op = Bop->getOpcodeStr();
15160  S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15161  << Bop->getSourceRange() << OpLoc << Shift << Op;
15162  SuggestParentheses(S, Bop->getOperatorLoc(),
15163  S.PDiag(diag::note_precedence_silence) << Op,
15164  Bop->getSourceRange());
15165  }
15166  }
15167 }
15168 
15170  Expr *LHSExpr, Expr *RHSExpr) {
15171  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15172  if (!OCE)
15173  return;
15174 
15175  FunctionDecl *FD = OCE->getDirectCallee();
15176  if (!FD || !FD->isOverloadedOperator())
15177  return;
15178 
15180  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15181  return;
15182 
15183  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15184  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15185  << (Kind == OO_LessLess);
15187  S.PDiag(diag::note_precedence_silence)
15188  << (Kind == OO_LessLess ? "<<" : ">>"),
15189  OCE->getSourceRange());
15191  S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15192  SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15193 }
15194 
15195 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15196 /// precedence.
15198  SourceLocation OpLoc, Expr *LHSExpr,
15199  Expr *RHSExpr){
15200  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15201  if (BinaryOperator::isBitwiseOp(Opc))
15202  DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15203 
15204  // Diagnose "arg1 & arg2 | arg3"
15205  if ((Opc == BO_Or || Opc == BO_Xor) &&
15206  !OpLoc.isMacroID()/* Don't warn in macros. */) {
15207  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15208  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15209  }
15210 
15211  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15212  // We don't warn for 'assert(a || b && "bad")' since this is safe.
15213  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15214  DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15215  DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15216  }
15217 
15218  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15219  || Opc == BO_Shr) {
15220  StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15221  DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15222  DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15223  }
15224 
15225  // Warn on overloaded shift operators and comparisons, such as:
15226  // cout << 5 == 4;
15228  DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15229 }
15230 
15231 // Binary Operators. 'Tok' is the token for the operator.
15234  Expr *LHSExpr, Expr *RHSExpr) {
15235  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15236  assert(LHSExpr && "ActOnBinOp(): missing left expression");
15237  assert(RHSExpr && "ActOnBinOp(): missing right expression");
15238 
15239  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15240  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15241 
15242  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15243 }
15244 
15246  UnresolvedSetImpl &Functions) {
15248  if (OverOp != OO_None && OverOp != OO_Equal)
15249  LookupOverloadedOperatorName(OverOp, S, Functions);
15250 
15251  // In C++20 onwards, we may have a second operator to look up.
15252  if (getLangOpts().CPlusPlus20) {
15254  LookupOverloadedOperatorName(ExtraOp, S, Functions);
15255  }
15256 }
15257 
15258 /// Build an overloaded binary operator expression in the given scope.
15260  BinaryOperatorKind Opc,
15261  Expr *LHS, Expr *RHS) {
15262  switch (Opc) {
15263  case BO_Assign:
15264  // In the non-overloaded case, we warn about self-assignment (x = x) for
15265  // both simple assignment and certain compound assignments where algebra
15266  // tells us the operation yields a constant result. When the operator is
15267  // overloaded, we can't do the latter because we don't want to assume that
15268  // those algebraic identities still apply; for example, a path-building
15269  // library might use operator/= to append paths. But it's still reasonable
15270  // to assume that simple assignment is just moving/copying values around
15271  // and so self-assignment is likely a bug.
15272  DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15273  [[fallthrough]];
15274  case BO_DivAssign:
15275  case BO_RemAssign:
15276  case BO_SubAssign:
15277  case BO_AndAssign:
15278  case BO_OrAssign:
15279  case BO_XorAssign:
15280  CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15281  break;
15282  default:
15283  break;
15284  }
15285 
15286  // Find all of the overloaded operators visible from this point.
15287  UnresolvedSet<16> Functions;
15288  S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15289 
15290  // Build the (potentially-overloaded, potentially-dependent)
15291  // binary operation.
15292  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15293 }
15294 
15296  BinaryOperatorKind Opc,
15297  Expr *LHSExpr, Expr *RHSExpr) {
15298  ExprResult LHS, RHS;
15299  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15300  if (!LHS.isUsable() || !RHS.isUsable())
15301  return ExprError();
15302  LHSExpr = LHS.get();
15303  RHSExpr = RHS.get();
15304 
15305  // We want to end up calling one of SemaPseudoObject::checkAssignment
15306  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15307  // both expressions are overloadable or either is type-dependent),
15308  // or CreateBuiltinBinOp (in any other case). We also want to get
15309  // any placeholder types out of the way.
15310 
15311  // Handle pseudo-objects in the LHS.
15312  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15313  // Assignments with a pseudo-object l-value need special analysis.
15314  if (pty->getKind() == BuiltinType::PseudoObject &&
15316  return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15317 
15318  // Don't resolve overloads if the other type is overloadable.
15319  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15320  // We can't actually test that if we still have a placeholder,
15321  // though. Fortunately, none of the exceptions we see in that
15322  // code below are valid when the LHS is an overload set. Note
15323  // that an overload set can be dependently-typed, but it never
15324  // instantiates to having an overloadable type.
15325  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15326  if (resolvedRHS.isInvalid()) return ExprError();
15327  RHSExpr = resolvedRHS.get();
15328 
15329  if (RHSExpr->isTypeDependent() ||
15330  RHSExpr->getType()->isOverloadableType())
15331  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15332  }
15333 
15334  // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15335  // template, diagnose the missing 'template' keyword instead of diagnosing
15336  // an invalid use of a bound member function.
15337  //
15338  // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15339  // to C++1z [over.over]/1.4, but we already checked for that case above.
15340  if (Opc == BO_LT && inTemplateInstantiation() &&
15341  (pty->getKind() == BuiltinType::BoundMember ||
15342  pty->getKind() == BuiltinType::Overload)) {
15343  auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15344  if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15345  llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15346  return isa<FunctionTemplateDecl>(ND);
15347  })) {
15348  Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15349  : OE->getNameLoc(),
15350  diag::err_template_kw_missing)
15351  << OE->getName().getAsString() << "";
15352  return ExprError();
15353  }
15354  }
15355 
15356  ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15357  if (LHS.isInvalid()) return ExprError();
15358  LHSExpr = LHS.get();
15359  }
15360 
15361  // Handle pseudo-objects in the RHS.
15362  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15363  // An overload in the RHS can potentially be resolved by the type
15364  // being assigned to.
15365  if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15366  if (getLangOpts().CPlusPlus &&
15367  (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15368  LHSExpr->getType()->isOverloadableType()))
15369  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15370 
15371  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15372  }
15373 
15374  // Don't resolve overloads if the other type is overloadable.
15375  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15376  LHSExpr->getType()->isOverloadableType())
15377  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15378 
15379  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15380  if (!resolvedRHS.isUsable()) return ExprError();
15381  RHSExpr = resolvedRHS.get();
15382  }
15383 
15384  if (getLangOpts().CPlusPlus) {
15385  // Otherwise, build an overloaded op if either expression is type-dependent
15386  // or has an overloadable type.
15387  if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15388  LHSExpr->getType()->isOverloadableType() ||
15389  RHSExpr->getType()->isOverloadableType())
15390  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15391  }
15392 
15393  if (getLangOpts().RecoveryAST &&
15394  (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15395  assert(!getLangOpts().CPlusPlus);
15396  assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15397  "Should only occur in error-recovery path.");
15399  // C [6.15.16] p3:
15400  // An assignment expression has the value of the left operand after the
15401  // assignment, but is not an lvalue.
15403  Context, LHSExpr, RHSExpr, Opc,
15405  OpLoc, CurFPFeatureOverrides());
15406  QualType ResultType;
15407  switch (Opc) {
15408  case BO_Assign:
15409  ResultType = LHSExpr->getType().getUnqualifiedType();
15410  break;
15411  case BO_LT:
15412  case BO_GT:
15413  case BO_LE:
15414  case BO_GE:
15415  case BO_EQ:
15416  case BO_NE:
15417  case BO_LAnd:
15418  case BO_LOr:
15419  // These operators have a fixed result type regardless of operands.
15420  ResultType = Context.IntTy;
15421  break;
15422  case BO_Comma:
15423  ResultType = RHSExpr->getType();
15424  break;
15425  default:
15426  ResultType = Context.DependentTy;
15427  break;
15428  }
15429  return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15430  VK_PRValue, OK_Ordinary, OpLoc,
15431  CurFPFeatureOverrides());
15432  }
15433 
15434  // Build a built-in binary operation.
15435  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15436 }
15437 
15439  if (T.isNull() || T->isDependentType())
15440  return false;
15441 
15442  if (!Ctx.isPromotableIntegerType(T))
15443  return true;
15444 
15445  return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15446 }
15447 
15449  UnaryOperatorKind Opc, Expr *InputExpr,
15450  bool IsAfterAmp) {
15451  ExprResult Input = InputExpr;
15454  QualType resultType;
15455  bool CanOverflow = false;
15456 
15457  bool ConvertHalfVec = false;
15458  if (getLangOpts().OpenCL || getLangOpts().SYCLIsDevice) {
15459  QualType Ty = InputExpr->getType();
15460  // The only legal unary operation for atomics is '&'.
15461  if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15462  // OpenCL special types - image, sampler, pipe, and blocks are to be used
15463  // only with a builtin functions and therefore should be disallowed here.
15464  (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15465  || Ty->isBlockPointerType())) {
15466  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15467  << InputExpr->getType()
15468  << Input.get()->getSourceRange());
15469  }
15470  }
15471 
15472  if (getLangOpts().HLSL && OpLoc.isValid()) {
15473  if (Opc == UO_AddrOf)
15474  return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15475  if (Opc == UO_Deref)
15476  return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15477  }
15478 
15479  if (InputExpr->isTypeDependent() &&
15480  InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15481  resultType = Context.DependentTy;
15482  } else {
15483  switch (Opc) {
15484  case UO_PreInc:
15485  case UO_PreDec:
15486  case UO_PostInc:
15487  case UO_PostDec:
15488  resultType =
15489  CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15490  Opc == UO_PreInc || Opc == UO_PostInc,
15491  Opc == UO_PreInc || Opc == UO_PreDec);
15492  CanOverflow = isOverflowingIntegerType(Context, resultType);
15493  break;
15494  case UO_AddrOf:
15495  resultType = CheckAddressOfOperand(Input, OpLoc);
15496  CheckAddressOfNoDeref(InputExpr);
15497  RecordModifiableNonNullParam(*this, InputExpr);
15498  break;
15499  case UO_Deref: {
15500  Input = DefaultFunctionArrayLvalueConversion(Input.get());
15501  if (Input.isInvalid())
15502  return ExprError();
15503  resultType =
15504  CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15505  break;
15506  }
15507  case UO_Plus:
15508  case UO_Minus:
15509  CanOverflow = Opc == UO_Minus &&
15510  isOverflowingIntegerType(Context, Input.get()->getType());
15511  Input = UsualUnaryConversions(Input.get());
15512  if (Input.isInvalid())
15513  return ExprError();
15514  // Unary plus and minus require promoting an operand of half vector to a
15515  // float vector and truncating the result back to a half vector. For now,
15516  // we do this only when HalfArgsAndReturns is set (that is, when the
15517  // target is arm or arm64).
15518  ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15519 
15520  // If the operand is a half vector, promote it to a float vector.
15521  if (ConvertHalfVec)
15522  Input = convertVector(Input.get(), Context.FloatTy, *this);
15523  resultType = Input.get()->getType();
15524  if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15525  break;
15526  else if (resultType->isVectorType() &&
15527  // The z vector extensions don't allow + or - with bool vectors.
15528  (!Context.getLangOpts().ZVector ||
15529  resultType->castAs<VectorType>()->getVectorKind() !=
15531  break;
15532  else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15533  break;
15534  else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15535  Opc == UO_Plus && resultType->isPointerType())
15536  break;
15537 
15538  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15539  << resultType << Input.get()->getSourceRange());
15540 
15541  case UO_Not: // bitwise complement
15542  Input = UsualUnaryConversions(Input.get());
15543  if (Input.isInvalid())
15544  return ExprError();
15545  resultType = Input.get()->getType();
15546  // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15547  if (resultType->isComplexType() || resultType->isComplexIntegerType())
15548  // C99 does not support '~' for complex conjugation.
15549  Diag(OpLoc, diag::ext_integer_complement_complex)
15550  << resultType << Input.get()->getSourceRange();
15551  else if (resultType->hasIntegerRepresentation())
15552  break;
15553  else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15554  // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15555  // on vector float types.
15556  QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15557  if (!T->isIntegerType())
15558  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15559  << resultType << Input.get()->getSourceRange());
15560  } else {
15561  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15562  << resultType << Input.get()->getSourceRange());
15563  }
15564  break;
15565 
15566  case UO_LNot: // logical negation
15567  // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15568  Input = DefaultFunctionArrayLvalueConversion(Input.get());
15569  if (Input.isInvalid())
15570  return ExprError();
15571  resultType = Input.get()->getType();
15572 
15573  // Though we still have to promote half FP to float...
15574  if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15575  Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15576  .get();
15577  resultType = Context.FloatTy;
15578  }
15579 
15580  // WebAsembly tables can't be used in unary expressions.
15581  if (resultType->isPointerType() &&
15582  resultType->getPointeeType().isWebAssemblyReferenceType()) {
15583  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15584  << resultType << Input.get()->getSourceRange());
15585  }
15586 
15587  if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15588  // C99 6.5.3.3p1: ok, fallthrough;
15589  if (Context.getLangOpts().CPlusPlus) {
15590  // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15591  // operand contextually converted to bool.
15592  Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15593  ScalarTypeToBooleanCastKind(resultType));
15594  } else if (Context.getLangOpts().OpenCL &&
15595  Context.getLangOpts().OpenCLVersion < 120) {
15596  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15597  // operate on scalar float types.
15598  if (!resultType->isIntegerType() && !resultType->isPointerType())
15599  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15600  << resultType << Input.get()->getSourceRange());
15601  }
15602  } else if (resultType->isExtVectorType()) {
15603  if (Context.getLangOpts().OpenCL &&
15604  Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15605  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15606  // operate on vector float types.
15607  QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15608  if (!T->isIntegerType())
15609  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15610  << resultType << Input.get()->getSourceRange());
15611  }
15612  // Vector logical not returns the signed variant of the operand type.
15613  resultType = GetSignedVectorType(resultType);
15614  break;
15615  } else if (Context.getLangOpts().CPlusPlus &&
15616  resultType->isVectorType()) {
15617  const VectorType *VTy = resultType->castAs<VectorType>();
15618  if (VTy->getVectorKind() != VectorKind::Generic)
15619  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15620  << resultType << Input.get()->getSourceRange());
15621 
15622  // Vector logical not returns the signed variant of the operand type.
15623  resultType = GetSignedVectorType(resultType);
15624  break;
15625  } else {
15626  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15627  << resultType << Input.get()->getSourceRange());
15628  }
15629 
15630  // LNot always has type int. C99 6.5.3.3p5.
15631  // In C++, it's bool. C++ 5.3.1p8
15632  resultType = Context.getLogicalOperationType();
15633  break;
15634  case UO_Real:
15635  case UO_Imag:
15636  resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15637  // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15638  // ordinary complex l-values to ordinary l-values and all other values to
15639  // r-values.
15640  if (Input.isInvalid())
15641  return ExprError();
15642  if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15643  if (Input.get()->isGLValue() &&
15644  Input.get()->getObjectKind() == OK_Ordinary)
15645  VK = Input.get()->getValueKind();
15646  } else if (!getLangOpts().CPlusPlus) {
15647  // In C, a volatile scalar is read by __imag. In C++, it is not.
15648  Input = DefaultLvalueConversion(Input.get());
15649  }
15650  break;
15651  case UO_Extension:
15652  resultType = Input.get()->getType();
15653  VK = Input.get()->getValueKind();
15654  OK = Input.get()->getObjectKind();
15655  break;
15656  case UO_Coawait:
15657  // It's unnecessary to represent the pass-through operator co_await in the
15658  // AST; just return the input expression instead.
15659  assert(!Input.get()->getType()->isDependentType() &&
15660  "the co_await expression must be non-dependant before "
15661  "building operator co_await");
15662  return Input;
15663  }
15664  }
15665  if (resultType.isNull() || Input.isInvalid())
15666  return ExprError();
15667 
15668  // Check for array bounds violations in the operand of the UnaryOperator,
15669  // except for the '*' and '&' operators that have to be handled specially
15670  // by CheckArrayAccess (as there are special cases like &array[arraysize]
15671  // that are explicitly defined as valid by the standard).
15672  if (Opc != UO_AddrOf && Opc != UO_Deref)
15673  CheckArrayAccess(Input.get());
15674 
15675  auto *UO =
15676  UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15677  OpLoc, CanOverflow, CurFPFeatureOverrides());
15678 
15679  if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15680  !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15681  !isUnevaluatedContext())
15682  ExprEvalContexts.back().PossibleDerefs.insert(UO);
15683 
15684  // Convert the result back to a half vector.
15685  if (ConvertHalfVec)
15686  return convertVector(UO, Context.HalfTy, *this);
15687  return UO;
15688 }
15689 
15690 /// Determine whether the given expression is a qualified member
15691 /// access expression, of a form that could be turned into a pointer to member
15692 /// with the address-of operator.
15694  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15695  if (!DRE->getQualifier())
15696  return false;
15697 
15698  ValueDecl *VD = DRE->getDecl();
15699  if (!VD->isCXXClassMember())
15700  return false;
15701 
15702  if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15703  return true;
15704  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15705  return Method->isImplicitObjectMemberFunction();
15706 
15707  return false;
15708  }
15709 
15710  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15711  if (!ULE->getQualifier())
15712  return false;
15713 
15714  for (NamedDecl *D : ULE->decls()) {
15715  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15716  if (Method->isImplicitObjectMemberFunction())
15717  return true;
15718  } else {
15719  // Overload set does not contain methods.
15720  break;
15721  }
15722  }
15723 
15724  return false;
15725  }
15726 
15727  return false;
15728 }
15729 
15731  UnaryOperatorKind Opc, Expr *Input,
15732  bool IsAfterAmp) {
15733  // First things first: handle placeholders so that the
15734  // overloaded-operator check considers the right type.
15735  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15736  // Increment and decrement of pseudo-object references.
15737  if (pty->getKind() == BuiltinType::PseudoObject &&
15739  return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15740 
15741  // extension is always a builtin operator.
15742  if (Opc == UO_Extension)
15743  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15744 
15745  // & gets special logic for several kinds of placeholder.
15746  // The builtin code knows what to do.
15747  if (Opc == UO_AddrOf &&
15748  (pty->getKind() == BuiltinType::Overload ||
15749  pty->getKind() == BuiltinType::UnknownAny ||
15750  pty->getKind() == BuiltinType::BoundMember))
15751  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15752 
15753  // Anything else needs to be handled now.
15754  ExprResult Result = CheckPlaceholderExpr(Input);
15755  if (Result.isInvalid()) return ExprError();
15756  Input = Result.get();
15757  }
15758 
15759  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15761  !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15762  // Find all of the overloaded operators visible from this point.
15763  UnresolvedSet<16> Functions;
15765  if (S && OverOp != OO_None)
15766  LookupOverloadedOperatorName(OverOp, S, Functions);
15767 
15768  return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15769  }
15770 
15771  return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15772 }
15773 
15774 // Unary Operators. 'Tok' is the token for the operator.
15776  Expr *Input, bool IsAfterAmp) {
15777  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15778  IsAfterAmp);
15779 }
15780 
15781 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15783  LabelDecl *TheDecl) {
15784  TheDecl->markUsed(Context);
15785  // Create the AST node. The address of a label always has type 'void*'.
15786  auto *Res = new (Context) AddrLabelExpr(
15787  OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15788 
15789  if (getCurFunction())
15790  getCurFunction()->AddrLabels.push_back(Res);
15791 
15792  return Res;
15793 }
15794 
15796  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15797  // Make sure we diagnose jumping into a statement expression.
15798  setFunctionHasBranchProtectedScope();
15799 }
15800 
15802  // Note that function is also called by TreeTransform when leaving a
15803  // StmtExpr scope without rebuilding anything.
15804 
15805  DiscardCleanupsInEvaluationContext();
15806  PopExpressionEvaluationContext();
15807 }
15808 
15810  SourceLocation RPLoc) {
15811  return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15812 }
15813 
15815  SourceLocation RPLoc, unsigned TemplateDepth) {
15816  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15817  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15818 
15819  if (hasAnyUnrecoverableErrorsInThisFunction())
15820  DiscardCleanupsInEvaluationContext();
15821  assert(!Cleanup.exprNeedsCleanups() &&
15822  "cleanups within StmtExpr not correctly bound!");
15823  PopExpressionEvaluationContext();
15824 
15825  // FIXME: there are a variety of strange constraints to enforce here, for
15826  // example, it is not possible to goto into a stmt expression apparently.
15827  // More semantic analysis is needed.
15828 
15829  // If there are sub-stmts in the compound stmt, take the type of the last one
15830  // as the type of the stmtexpr.
15831  QualType Ty = Context.VoidTy;
15832  bool StmtExprMayBindToTemp = false;
15833  if (!Compound->body_empty()) {
15834  // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15835  if (const auto *LastStmt =
15836  dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15837  if (const Expr *Value = LastStmt->getExprStmt()) {
15838  StmtExprMayBindToTemp = true;
15839  Ty = Value->getType();
15840  }
15841  }
15842  }
15843 
15844  // FIXME: Check that expression type is complete/non-abstract; statement
15845  // expressions are not lvalues.
15846  Expr *ResStmtExpr =
15847  new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15848  if (StmtExprMayBindToTemp)
15849  return MaybeBindToTemporary(ResStmtExpr);
15850  return ResStmtExpr;
15851 }
15852 
15854  if (ER.isInvalid())
15855  return ExprError();
15856 
15857  // Do function/array conversion on the last expression, but not
15858  // lvalue-to-rvalue. However, initialize an unqualified type.
15859  ER = DefaultFunctionArrayConversion(ER.get());
15860  if (ER.isInvalid())
15861  return ExprError();
15862  Expr *E = ER.get();
15863 
15864  if (E->isTypeDependent())
15865  return E;
15866 
15867  // In ARC, if the final expression ends in a consume, splice
15868  // the consume out and bind it later. In the alternate case
15869  // (when dealing with a retainable type), the result
15870  // initialization will create a produce. In both cases the
15871  // result will be +1, and we'll need to balance that out with
15872  // a bind.
15873  auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15874  if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15875  return Cast->getSubExpr();
15876 
15877  // FIXME: Provide a better location for the initialization.
15878  return PerformCopyInitialization(
15880  E->getBeginLoc(), E->getType().getUnqualifiedType()),
15881  SourceLocation(), E);
15882 }
15883 
15885  TypeSourceInfo *TInfo,
15886  ArrayRef<OffsetOfComponent> Components,
15887  SourceLocation RParenLoc) {
15888  QualType ArgTy = TInfo->getType();
15889  bool Dependent = ArgTy->isDependentType();
15890  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15891 
15892  // We must have at least one component that refers to the type, and the first
15893  // one is known to be a field designator. Verify that the ArgTy represents
15894  // a struct/union/class.
15895  if (!Dependent && !ArgTy->isRecordType())
15896  return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15897  << ArgTy << TypeRange);
15898 
15899  // Type must be complete per C99 7.17p3 because a declaring a variable
15900  // with an incomplete type would be ill-formed.
15901  if (!Dependent
15902  && RequireCompleteType(BuiltinLoc, ArgTy,
15903  diag::err_offsetof_incomplete_type, TypeRange))
15904  return ExprError();
15905 
15906  bool DidWarnAboutNonPOD = false;
15907  QualType CurrentType = ArgTy;
15909  SmallVector<Expr*, 4> Exprs;
15910  for (const OffsetOfComponent &OC : Components) {
15911  if (OC.isBrackets) {
15912  // Offset of an array sub-field. TODO: Should we allow vector elements?
15913  if (!CurrentType->isDependentType()) {
15914  const ArrayType *AT = Context.getAsArrayType(CurrentType);
15915  if(!AT)
15916  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15917  << CurrentType);
15918  CurrentType = AT->getElementType();
15919  } else
15920  CurrentType = Context.DependentTy;
15921 
15922  ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15923  if (IdxRval.isInvalid())
15924  return ExprError();
15925  Expr *Idx = IdxRval.get();
15926 
15927  // The expression must be an integral expression.
15928  // FIXME: An integral constant expression?
15929  if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15930  !Idx->getType()->isIntegerType())
15931  return ExprError(
15932  Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15933  << Idx->getSourceRange());
15934 
15935  // Record this array index.
15936  Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15937  Exprs.push_back(Idx);
15938  continue;
15939  }
15940 
15941  // Offset of a field.
15942  if (CurrentType->isDependentType()) {
15943  // We have the offset of a field, but we can't look into the dependent
15944  // type. Just record the identifier of the field.
15945  Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15946  CurrentType = Context.DependentTy;
15947  continue;
15948  }
15949 
15950  // We need to have a complete type to look into.
15951  if (RequireCompleteType(OC.LocStart, CurrentType,
15952  diag::err_offsetof_incomplete_type))
15953  return ExprError();
15954 
15955  // Look for the designated field.
15956  const RecordType *RC = CurrentType->getAs<RecordType>();
15957  if (!RC)
15958  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15959  << CurrentType);
15960  RecordDecl *RD = RC->getDecl();
15961 
15962  // C++ [lib.support.types]p5:
15963  // The macro offsetof accepts a restricted set of type arguments in this
15964  // International Standard. type shall be a POD structure or a POD union
15965  // (clause 9).
15966  // C++11 [support.types]p4:
15967  // If type is not a standard-layout class (Clause 9), the results are
15968  // undefined.
15969  if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15970  bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15971  unsigned DiagID =
15972  LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15973  : diag::ext_offsetof_non_pod_type;
15974 
15975  if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
15976  Diag(BuiltinLoc, DiagID)
15977  << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
15978  DidWarnAboutNonPOD = true;
15979  }
15980  }
15981 
15982  // Look for the field.
15983  LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15984  LookupQualifiedName(R, RD);
15985  FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15986  IndirectFieldDecl *IndirectMemberDecl = nullptr;
15987  if (!MemberDecl) {
15988  if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15989  MemberDecl = IndirectMemberDecl->getAnonField();
15990  }
15991 
15992  if (!MemberDecl) {
15993  // Lookup could be ambiguous when looking up a placeholder variable
15994  // __builtin_offsetof(S, _).
15995  // In that case we would already have emitted a diagnostic
15996  if (!R.isAmbiguous())
15997  Diag(BuiltinLoc, diag::err_no_member)
15998  << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
15999  return ExprError();
16000  }
16001 
16002  // C99 7.17p3:
16003  // (If the specified member is a bit-field, the behavior is undefined.)
16004  //
16005  // We diagnose this as an error.
16006  if (MemberDecl->isBitField()) {
16007  Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16008  << MemberDecl->getDeclName()
16009  << SourceRange(BuiltinLoc, RParenLoc);
16010  Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16011  return ExprError();
16012  }
16013 
16014  RecordDecl *Parent = MemberDecl->getParent();
16015  if (IndirectMemberDecl)
16016  Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16017 
16018  // If the member was found in a base class, introduce OffsetOfNodes for
16019  // the base class indirections.
16020  CXXBasePaths Paths;
16021  if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16022  Paths)) {
16023  if (Paths.getDetectedVirtual()) {
16024  Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16025  << MemberDecl->getDeclName()
16026  << SourceRange(BuiltinLoc, RParenLoc);
16027  return ExprError();
16028  }
16029 
16030  CXXBasePath &Path = Paths.front();
16031  for (const CXXBasePathElement &B : Path)
16032  Comps.push_back(OffsetOfNode(B.Base));
16033  }
16034 
16035  if (IndirectMemberDecl) {
16036  for (auto *FI : IndirectMemberDecl->chain()) {
16037  assert(isa<FieldDecl>(FI));
16038  Comps.push_back(OffsetOfNode(OC.LocStart,
16039  cast<FieldDecl>(FI), OC.LocEnd));
16040  }
16041  } else
16042  Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16043 
16044  CurrentType = MemberDecl->getType().getNonReferenceType();
16045  }
16046 
16047  return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16048  Comps, Exprs, RParenLoc);
16049 }
16050 
16052  SourceLocation BuiltinLoc,
16054  ParsedType ParsedArgTy,
16055  ArrayRef<OffsetOfComponent> Components,
16056  SourceLocation RParenLoc) {
16057 
16058  TypeSourceInfo *ArgTInfo;
16059  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16060  if (ArgTy.isNull())
16061  return ExprError();
16062 
16063  if (!ArgTInfo)
16064  ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16065 
16066  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16067 }
16068 
16069 
16071  Expr *CondExpr,
16072  Expr *LHSExpr, Expr *RHSExpr,
16073  SourceLocation RPLoc) {
16074  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16075 
16078  QualType resType;
16079  bool CondIsTrue = false;
16080  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16081  resType = Context.DependentTy;
16082  } else {
16083  // The conditional expression is required to be a constant expression.
16084  llvm::APSInt condEval(32);
16085  ExprResult CondICE = VerifyIntegerConstantExpression(
16086  CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16087  if (CondICE.isInvalid())
16088  return ExprError();
16089  CondExpr = CondICE.get();
16090  CondIsTrue = condEval.getZExtValue();
16091 
16092  // If the condition is > zero, then the AST type is the same as the LHSExpr.
16093  Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16094 
16095  resType = ActiveExpr->getType();
16096  VK = ActiveExpr->getValueKind();
16097  OK = ActiveExpr->getObjectKind();
16098  }
16099 
16100  return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16101  resType, VK, OK, RPLoc, CondIsTrue);
16102 }
16103 
16104 //===----------------------------------------------------------------------===//
16105 // Clang Extensions.
16106 //===----------------------------------------------------------------------===//
16107 
16108 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16109 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16110  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16111 
16112  if (LangOpts.CPlusPlus) {
16113  MangleNumberingContext *MCtx;
16114  Decl *ManglingContextDecl;
16115  std::tie(MCtx, ManglingContextDecl) =
16116  getCurrentMangleNumberContext(Block->getDeclContext());
16117  if (MCtx) {
16118  unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16119  Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16120  }
16121  }
16122 
16123  PushBlockScope(CurScope, Block);
16124  CurContext->addDecl(Block);
16125  if (CurScope)
16126  PushDeclContext(CurScope, Block);
16127  else
16128  CurContext = Block;
16129 
16130  getCurBlock()->HasImplicitReturnType = true;
16131 
16132  // Enter a new evaluation context to insulate the block from any
16133  // cleanups from the enclosing full-expression.
16134  PushExpressionEvaluationContext(
16135  ExpressionEvaluationContext::PotentiallyEvaluated);
16136 }
16137 
16139  Scope *CurScope) {
16140  assert(ParamInfo.getIdentifier() == nullptr &&
16141  "block-id should have no identifier!");
16142  assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16143  BlockScopeInfo *CurBlock = getCurBlock();
16144 
16145  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16146  QualType T = Sig->getType();
16147 
16148  // FIXME: We should allow unexpanded parameter packs here, but that would,
16149  // in turn, make the block expression contain unexpanded parameter packs.
16150  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16151  // Drop the parameters.
16153  EPI.HasTrailingReturn = false;
16154  EPI.TypeQuals.addConst();
16155  T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16156  Sig = Context.getTrivialTypeSourceInfo(T);
16157  }
16158 
16159  // GetTypeForDeclarator always produces a function type for a block
16160  // literal signature. Furthermore, it is always a FunctionProtoType
16161  // unless the function was written with a typedef.
16162  assert(T->isFunctionType() &&
16163  "GetTypeForDeclarator made a non-function block signature");
16164 
16165  // Look for an explicit signature in that function type.
16166  FunctionProtoTypeLoc ExplicitSignature;
16167 
16168  if ((ExplicitSignature = Sig->getTypeLoc()
16170 
16171  // Check whether that explicit signature was synthesized by
16172  // GetTypeForDeclarator. If so, don't save that as part of the
16173  // written signature.
16174  if (ExplicitSignature.getLocalRangeBegin() ==
16175  ExplicitSignature.getLocalRangeEnd()) {
16176  // This would be much cheaper if we stored TypeLocs instead of
16177  // TypeSourceInfos.
16178  TypeLoc Result = ExplicitSignature.getReturnLoc();
16179  unsigned Size = Result.getFullDataSize();
16180  Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16181  Sig->getTypeLoc().initializeFullCopy(Result, Size);
16182 
16183  ExplicitSignature = FunctionProtoTypeLoc();
16184  }
16185  }
16186 
16187  CurBlock->TheDecl->setSignatureAsWritten(Sig);
16188  CurBlock->FunctionType = T;
16189 
16190  const auto *Fn = T->castAs<FunctionType>();
16191  QualType RetTy = Fn->getReturnType();
16192  bool isVariadic =
16193  (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16194 
16195  CurBlock->TheDecl->setIsVariadic(isVariadic);
16196 
16197  // Context.DependentTy is used as a placeholder for a missing block
16198  // return type. TODO: what should we do with declarators like:
16199  // ^ * { ... }
16200  // If the answer is "apply template argument deduction"....
16201  if (RetTy != Context.DependentTy) {
16202  CurBlock->ReturnType = RetTy;
16203  CurBlock->TheDecl->setBlockMissingReturnType(false);
16204  CurBlock->HasImplicitReturnType = false;
16205  }
16206 
16207  // Push block parameters from the declarator if we had them.
16209  if (ExplicitSignature) {
16210  for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16211  ParmVarDecl *Param = ExplicitSignature.getParam(I);
16212  if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16213  !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16214  // Diagnose this as an extension in C17 and earlier.
16215  if (!getLangOpts().C23)
16216  Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16217  }
16218  Params.push_back(Param);
16219  }
16220 
16221  // Fake up parameter variables if we have a typedef, like
16222  // ^ fntype { ... }
16223  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16224  for (const auto &I : Fn->param_types()) {
16225  ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16226  CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16227  Params.push_back(Param);
16228  }
16229  }
16230 
16231  // Set the parameters on the block decl.
16232  if (!Params.empty()) {
16233  CurBlock->TheDecl->setParams(Params);
16234  CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16235  /*CheckParameterNames=*/false);
16236  }
16237 
16238  // Finally we can process decl attributes.
16239  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16240 
16241  // Put the parameter variables in scope.
16242  for (auto *AI : CurBlock->TheDecl->parameters()) {
16243  AI->setOwningFunction(CurBlock->TheDecl);
16244 
16245  // If this has an identifier, add it to the scope stack.
16246  if (AI->getIdentifier()) {
16247  CheckShadow(CurBlock->TheScope, AI);
16248 
16249  PushOnScopeChains(AI, CurBlock->TheScope);
16250  }
16251 
16252  if (AI->isInvalidDecl())
16253  CurBlock->TheDecl->setInvalidDecl();
16254  }
16255 }
16256 
16257 /// ActOnBlockError - If there is an error parsing a block, this callback
16258 /// is invoked to pop the information about the block from the action impl.
16259 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16260  // Leave the expression-evaluation context.
16261  DiscardCleanupsInEvaluationContext();
16262  PopExpressionEvaluationContext();
16263 
16264  // Pop off CurBlock, handle nested blocks.
16265  PopDeclContext();
16266  PopFunctionScopeInfo();
16267 }
16268 
16269 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16270 /// literal was successfully completed. ^(int x){...}
16272  Stmt *Body, Scope *CurScope) {
16273  // If blocks are disabled, emit an error.
16274  if (!LangOpts.Blocks)
16275  Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16276 
16277  // Leave the expression-evaluation context.
16278  if (hasAnyUnrecoverableErrorsInThisFunction())
16279  DiscardCleanupsInEvaluationContext();
16280  assert(!Cleanup.exprNeedsCleanups() &&
16281  "cleanups within block not correctly bound!");
16282  PopExpressionEvaluationContext();
16283 
16284  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16285  BlockDecl *BD = BSI->TheDecl;
16286 
16287  if (BSI->HasImplicitReturnType)
16288  deduceClosureReturnType(*BSI);
16289 
16290  QualType RetTy = Context.VoidTy;
16291  if (!BSI->ReturnType.isNull())
16292  RetTy = BSI->ReturnType;
16293 
16294  bool NoReturn = BD->hasAttr<NoReturnAttr>();
16295  QualType BlockTy;
16296 
16297  // If the user wrote a function type in some form, try to use that.
16298  if (!BSI->FunctionType.isNull()) {
16299  const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16300 
16301  FunctionType::ExtInfo Ext = FTy->getExtInfo();
16302  if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16303 
16304  // Turn protoless block types into nullary block types.
16305  if (isa<FunctionNoProtoType>(FTy)) {
16307  EPI.ExtInfo = Ext;
16308  BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16309 
16310  // Otherwise, if we don't need to change anything about the function type,
16311  // preserve its sugar structure.
16312  } else if (FTy->getReturnType() == RetTy &&
16313  (!NoReturn || FTy->getNoReturnAttr())) {
16314  BlockTy = BSI->FunctionType;
16315 
16316  // Otherwise, make the minimal modifications to the function type.
16317  } else {
16318  const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16320  EPI.TypeQuals = Qualifiers();
16321  EPI.ExtInfo = Ext;
16322  BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16323  }
16324 
16325  // If we don't have a function type, just build one from nothing.
16326  } else {
16328  EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16329  BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16330  }
16331 
16332  DiagnoseUnusedParameters(BD->parameters());
16333  BlockTy = Context.getBlockPointerType(BlockTy);
16334 
16335  // If needed, diagnose invalid gotos and switches in the block.
16336  if (getCurFunction()->NeedsScopeChecking() &&
16337  !PP.isCodeCompletionEnabled())
16338  DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16339 
16340  BD->setBody(cast<CompoundStmt>(Body));
16341 
16342  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16343  DiagnoseUnguardedAvailabilityViolations(BD);
16344 
16345  // Try to apply the named return value optimization. We have to check again
16346  // if we can do this, though, because blocks keep return statements around
16347  // to deduce an implicit return type.
16348  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16349  !BD->isDependentContext())
16350  computeNRVO(Body, BSI);
16351 
16354  checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16355  NTCUK_Destruct|NTCUK_Copy);
16356 
16357  PopDeclContext();
16358 
16359  // Set the captured variables on the block.
16361  for (Capture &Cap : BSI->Captures) {
16362  if (Cap.isInvalid() || Cap.isThisCapture())
16363  continue;
16364  // Cap.getVariable() is always a VarDecl because
16365  // blocks cannot capture structured bindings or other ValueDecl kinds.
16366  auto *Var = cast<VarDecl>(Cap.getVariable());
16367  Expr *CopyExpr = nullptr;
16368  if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16369  if (const RecordType *Record =
16370  Cap.getCaptureType()->getAs<RecordType>()) {
16371  // The capture logic needs the destructor, so make sure we mark it.
16372  // Usually this is unnecessary because most local variables have
16373  // their destructors marked at declaration time, but parameters are
16374  // an exception because it's technically only the call site that
16375  // actually requires the destructor.
16376  if (isa<ParmVarDecl>(Var))
16377  FinalizeVarWithDestructor(Var, Record);
16378 
16379  // Enter a separate potentially-evaluated context while building block
16380  // initializers to isolate their cleanups from those of the block
16381  // itself.
16382  // FIXME: Is this appropriate even when the block itself occurs in an
16383  // unevaluated operand?
16385  *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16386 
16387  SourceLocation Loc = Cap.getLocation();
16388 
16389  ExprResult Result = BuildDeclarationNameExpr(
16390  CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16391 
16392  // According to the blocks spec, the capture of a variable from
16393  // the stack requires a const copy constructor. This is not true
16394  // of the copy/move done to move a __block variable to the heap.
16395  if (!Result.isInvalid() &&
16396  !Result.get()->getType().isConstQualified()) {
16397  Result = ImpCastExprToType(Result.get(),
16398  Result.get()->getType().withConst(),
16399  CK_NoOp, VK_LValue);
16400  }
16401 
16402  if (!Result.isInvalid()) {
16403  Result = PerformCopyInitialization(
16404  InitializedEntity::InitializeBlock(Var->getLocation(),
16405  Cap.getCaptureType()),
16406  Loc, Result.get());
16407  }
16408 
16409  // Build a full-expression copy expression if initialization
16410  // succeeded and used a non-trivial constructor. Recover from
16411  // errors by pretending that the copy isn't necessary.
16412  if (!Result.isInvalid() &&
16413  !cast<CXXConstructExpr>(Result.get())->getConstructor()
16414  ->isTrivial()) {
16415  Result = MaybeCreateExprWithCleanups(Result);
16416  CopyExpr = Result.get();
16417  }
16418  }
16419  }
16420 
16421  BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16422  CopyExpr);
16423  Captures.push_back(NewCap);
16424  }
16425  BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16426 
16427  // Pop the block scope now but keep it alive to the end of this function.
16428  AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16429  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16430 
16431  BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16432 
16433  // If the block isn't obviously global, i.e. it captures anything at
16434  // all, then we need to do a few things in the surrounding context:
16435  if (Result->getBlockDecl()->hasCaptures()) {
16436  // First, this expression has a new cleanup object.
16437  ExprCleanupObjects.push_back(Result->getBlockDecl());
16438  Cleanup.setExprNeedsCleanups(true);
16439 
16440  // It also gets a branch-protected scope if any of the captured
16441  // variables needs destruction.
16442  for (const auto &CI : Result->getBlockDecl()->captures()) {
16443  const VarDecl *var = CI.getVariable();
16444  if (var->getType().isDestructedType() != QualType::DK_none) {
16445  setFunctionHasBranchProtectedScope();
16446  break;
16447  }
16448  }
16449  }
16450 
16451  if (getCurFunction())
16452  getCurFunction()->addBlock(BD);
16453 
16454  if (BD->isInvalidDecl())
16455  return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16456  {Result}, Result->getType());
16457  return Result;
16458 }
16459 
16461  SourceLocation RPLoc) {
16462  TypeSourceInfo *TInfo;
16463  GetTypeFromParser(Ty, &TInfo);
16464  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16465 }
16466 
16468  Expr *E, TypeSourceInfo *TInfo,
16469  SourceLocation RPLoc) {
16470  Expr *OrigExpr = E;
16471  bool IsMS = false;
16472 
16473  // CUDA device code does not support varargs.
16474  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16475  if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16476  CUDAFunctionTarget T = CUDA().IdentifyTarget(F);
16479  return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16480  }
16481  }
16482 
16483  // NVPTX does not support va_arg expression.
16484  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16485  Context.getTargetInfo().getTriple().isNVPTX())
16486  targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16487 
16488  // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16489  // as Microsoft ABI on an actual Microsoft platform, where
16490  // __builtin_ms_va_list and __builtin_va_list are the same.)
16491  if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16493  QualType MSVaListType = Context.getBuiltinMSVaListType();
16494  if (Context.hasSameType(MSVaListType, E->getType())) {
16495  if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16496  return ExprError();
16497  IsMS = true;
16498  }
16499  }
16500 
16501  // Get the va_list type
16502  QualType VaListType = Context.getBuiltinVaListType();
16503  if (!IsMS) {
16504  if (VaListType->isArrayType()) {
16505  // Deal with implicit array decay; for example, on x86-64,
16506  // va_list is an array, but it's supposed to decay to
16507  // a pointer for va_arg.
16508  VaListType = Context.getArrayDecayedType(VaListType);
16509  // Make sure the input expression also decays appropriately.
16510  ExprResult Result = UsualUnaryConversions(E);
16511  if (Result.isInvalid())
16512  return ExprError();
16513  E = Result.get();
16514  } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16515  // If va_list is a record type and we are compiling in C++ mode,
16516  // check the argument using reference binding.
16518  Context, Context.getLValueReferenceType(VaListType), false);
16519  ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16520  if (Init.isInvalid())
16521  return ExprError();
16522  E = Init.getAs<Expr>();
16523  } else {
16524  // Otherwise, the va_list argument must be an l-value because
16525  // it is modified by va_arg.
16526  if (!E->isTypeDependent() &&
16527  CheckForModifiableLvalue(E, BuiltinLoc, *this))
16528  return ExprError();
16529  }
16530  }
16531 
16532  if (!IsMS && !E->isTypeDependent() &&
16533  !Context.hasSameType(VaListType, E->getType()))
16534  return ExprError(
16535  Diag(E->getBeginLoc(),
16536  diag::err_first_argument_to_va_arg_not_of_type_va_list)
16537  << OrigExpr->getType() << E->getSourceRange());
16538 
16539  if (!TInfo->getType()->isDependentType()) {
16540  if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16541  diag::err_second_parameter_to_va_arg_incomplete,
16542  TInfo->getTypeLoc()))
16543  return ExprError();
16544 
16545  if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16546  TInfo->getType(),
16547  diag::err_second_parameter_to_va_arg_abstract,
16548  TInfo->getTypeLoc()))
16549  return ExprError();
16550 
16551  if (!TInfo->getType().isPODType(Context)) {
16552  Diag(TInfo->getTypeLoc().getBeginLoc(),
16553  TInfo->getType()->isObjCLifetimeType()
16554  ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16555  : diag::warn_second_parameter_to_va_arg_not_pod)
16556  << TInfo->getType()
16557  << TInfo->getTypeLoc().getSourceRange();
16558  }
16559 
16560  // Check for va_arg where arguments of the given type will be promoted
16561  // (i.e. this va_arg is guaranteed to have undefined behavior).
16562  QualType PromoteType;
16563  if (Context.isPromotableIntegerType(TInfo->getType())) {
16564  PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16565  // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16566  // and C23 7.16.1.1p2 says, in part:
16567  // If type is not compatible with the type of the actual next argument
16568  // (as promoted according to the default argument promotions), the
16569  // behavior is undefined, except for the following cases:
16570  // - both types are pointers to qualified or unqualified versions of
16571  // compatible types;
16572  // - one type is compatible with a signed integer type, the other
16573  // type is compatible with the corresponding unsigned integer type,
16574  // and the value is representable in both types;
16575  // - one type is pointer to qualified or unqualified void and the
16576  // other is a pointer to a qualified or unqualified character type;
16577  // - or, the type of the next argument is nullptr_t and type is a
16578  // pointer type that has the same representation and alignment
16579  // requirements as a pointer to a character type.
16580  // Given that type compatibility is the primary requirement (ignoring
16581  // qualifications), you would think we could call typesAreCompatible()
16582  // directly to test this. However, in C++, that checks for *same type*,
16583  // which causes false positives when passing an enumeration type to
16584  // va_arg. Instead, get the underlying type of the enumeration and pass
16585  // that.
16586  QualType UnderlyingType = TInfo->getType();
16587  if (const auto *ET = UnderlyingType->getAs<EnumType>())
16588  UnderlyingType = ET->getDecl()->getIntegerType();
16589  if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16590  /*CompareUnqualified*/ true))
16591  PromoteType = QualType();
16592 
16593  // If the types are still not compatible, we need to test whether the
16594  // promoted type and the underlying type are the same except for
16595  // signedness. Ask the AST for the correctly corresponding type and see
16596  // if that's compatible.
16597  if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16598  PromoteType->isUnsignedIntegerType() !=
16599  UnderlyingType->isUnsignedIntegerType()) {
16600  UnderlyingType =
16601  UnderlyingType->isUnsignedIntegerType()
16602  ? Context.getCorrespondingSignedType(UnderlyingType)
16603  : Context.getCorrespondingUnsignedType(UnderlyingType);
16604  if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16605  /*CompareUnqualified*/ true))
16606  PromoteType = QualType();
16607  }
16608  }
16610  PromoteType = Context.DoubleTy;
16611  if (!PromoteType.isNull())
16612  DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16613  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16614  << TInfo->getType()
16615  << PromoteType
16616  << TInfo->getTypeLoc().getSourceRange());
16617  }
16618 
16619  QualType T = TInfo->getType().getNonLValueExprType(Context);
16620  return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16621 }
16622 
16624  // The type of __null will be int or long, depending on the size of
16625  // pointers on the target.
16626  QualType Ty;
16627  unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
16628  if (pw == Context.getTargetInfo().getIntWidth())
16629  Ty = Context.IntTy;
16630  else if (pw == Context.getTargetInfo().getLongWidth())
16631  Ty = Context.LongTy;
16632  else if (pw == Context.getTargetInfo().getLongLongWidth())
16633  Ty = Context.LongLongTy;
16634  else {
16635  llvm_unreachable("I don't know size of pointer!");
16636  }
16637 
16638  return new (Context) GNUNullExpr(Ty, TokenLoc);
16639 }
16640 
16642  CXXRecordDecl *ImplDecl = nullptr;
16643 
16644  // Fetch the std::source_location::__impl decl.
16645  if (NamespaceDecl *Std = S.getStdNamespace()) {
16646  LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16648  if (S.LookupQualifiedName(ResultSL, Std)) {
16649  if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16650  LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16652  if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16653  S.LookupQualifiedName(ResultImpl, SLDecl)) {
16654  ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16655  }
16656  }
16657  }
16658  }
16659 
16660  if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16661  S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16662  return nullptr;
16663  }
16664 
16665  // Verify that __impl is a trivial struct type, with no base classes, and with
16666  // only the four expected fields.
16667  if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16668  ImplDecl->getNumBases() != 0) {
16669  S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16670  return nullptr;
16671  }
16672 
16673  unsigned Count = 0;
16674  for (FieldDecl *F : ImplDecl->fields()) {
16675  StringRef Name = F->getName();
16676 
16677  if (Name == "_M_file_name") {
16678  if (F->getType() !=
16680  break;
16681  Count++;
16682  } else if (Name == "_M_function_name") {
16683  if (F->getType() !=
16685  break;
16686  Count++;
16687  } else if (Name == "_M_line") {
16688  if (!F->getType()->isIntegerType())
16689  break;
16690  Count++;
16691  } else if (Name == "_M_column") {
16692  if (!F->getType()->isIntegerType())
16693  break;
16694  Count++;
16695  } else {
16696  Count = 100; // invalid
16697  break;
16698  }
16699  }
16700  if (Count != 4) {
16701  S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16702  return nullptr;
16703  }
16704 
16705  return ImplDecl;
16706 }
16707 
16709  SourceLocation BuiltinLoc,
16710  SourceLocation RPLoc) {
16711  QualType ResultTy;
16712  switch (Kind) {
16717  QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16718  ResultTy =
16719  Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16720  break;
16721  }
16724  ResultTy = Context.UnsignedIntTy;
16725  break;
16727  if (!StdSourceLocationImplDecl) {
16728  StdSourceLocationImplDecl =
16729  LookupStdSourceLocationImpl(*this, BuiltinLoc);
16730  if (!StdSourceLocationImplDecl)
16731  return ExprError();
16732  }
16733  ResultTy = Context.getPointerType(
16734  Context.getRecordType(StdSourceLocationImplDecl).withConst());
16735  break;
16736  }
16737 
16738  return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16739 }
16740 
16742  SourceLocation BuiltinLoc,
16743  SourceLocation RPLoc,
16744  DeclContext *ParentContext) {
16745  return new (Context)
16746  SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16747 }
16748 
16750  const Expr *SrcExpr) {
16751  if (!DstType->isFunctionPointerType() ||
16752  !SrcExpr->getType()->isFunctionType())
16753  return false;
16754 
16755  auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16756  if (!DRE)
16757  return false;
16758 
16759  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16760  if (!FD)
16761  return false;
16762 
16763  return !S.checkAddressOfFunctionIsAvailable(FD,
16764  /*Complain=*/true,
16765  SrcExpr->getBeginLoc());
16766 }
16767 
16770  QualType DstType, QualType SrcType,
16771  Expr *SrcExpr, AssignmentAction Action,
16772  bool *Complained) {
16773  if (Complained)
16774  *Complained = false;
16775 
16776  // Decode the result (notice that AST's are still created for extensions).
16777  bool CheckInferredResultType = false;
16778  bool isInvalid = false;
16779  unsigned DiagKind = 0;
16780  ConversionFixItGenerator ConvHints;
16781  bool MayHaveConvFixit = false;
16782  bool MayHaveFunctionDiff = false;
16783  const ObjCInterfaceDecl *IFace = nullptr;
16784  const ObjCProtocolDecl *PDecl = nullptr;
16785 
16786  switch (ConvTy) {
16787  case Compatible:
16788  DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16789  return false;
16790 
16791  case PointerToInt:
16792  if (getLangOpts().CPlusPlus) {
16793  DiagKind = diag::err_typecheck_convert_pointer_int;
16794  isInvalid = true;
16795  } else {
16796  DiagKind = diag::ext_typecheck_convert_pointer_int;
16797  }
16798  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16799  MayHaveConvFixit = true;
16800  break;
16801  case IntToPointer:
16802  if (getLangOpts().CPlusPlus) {
16803  DiagKind = diag::err_typecheck_convert_int_pointer;
16804  isInvalid = true;
16805  } else {
16806  DiagKind = diag::ext_typecheck_convert_int_pointer;
16807  }
16808  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16809  MayHaveConvFixit = true;
16810  break;
16811  case IncompatibleFunctionPointerStrict:
16812  DiagKind =
16813  diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16814  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16815  MayHaveConvFixit = true;
16816  break;
16817  case IncompatibleFunctionPointer:
16818  if (getLangOpts().CPlusPlus) {
16819  DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16820  isInvalid = true;
16821  } else {
16822  DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16823  }
16824  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16825  MayHaveConvFixit = true;
16826  break;
16827  case IncompatiblePointer:
16828  if (Action == AA_Passing_CFAudited) {
16829  DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16830  } else if (getLangOpts().CPlusPlus) {
16831  DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16832  isInvalid = true;
16833  } else {
16834  DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16835  }
16836  CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16837  SrcType->isObjCObjectPointerType();
16838  if (CheckInferredResultType) {
16839  SrcType = SrcType.getUnqualifiedType();
16840  DstType = DstType.getUnqualifiedType();
16841  } else {
16842  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16843  }
16844  MayHaveConvFixit = true;
16845  break;
16846  case IncompatiblePointerSign:
16847  if (getLangOpts().CPlusPlus) {
16848  DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16849  isInvalid = true;
16850  } else {
16851  DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16852  }
16853  break;
16854  case FunctionVoidPointer:
16855  if (getLangOpts().CPlusPlus) {
16856  DiagKind = diag::err_typecheck_convert_pointer_void_func;
16857  isInvalid = true;
16858  } else {
16859  DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16860  }
16861  break;
16862  case IncompatiblePointerDiscardsQualifiers: {
16863  // Perform array-to-pointer decay if necessary.
16864  if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16865 
16866  isInvalid = true;
16867 
16868  Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16869  Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16870  if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16871  DiagKind = diag::err_typecheck_incompatible_address_space;
16872  break;
16873  } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16874  DiagKind = diag::err_typecheck_incompatible_ownership;
16875  break;
16876  }
16877 
16878  llvm_unreachable("unknown error case for discarding qualifiers!");
16879  // fallthrough
16880  }
16881  case CompatiblePointerDiscardsQualifiers:
16882  // If the qualifiers lost were because we were applying the
16883  // (deprecated) C++ conversion from a string literal to a char*
16884  // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16885  // Ideally, this check would be performed in
16886  // checkPointerTypesForAssignment. However, that would require a
16887  // bit of refactoring (so that the second argument is an
16888  // expression, rather than a type), which should be done as part
16889  // of a larger effort to fix checkPointerTypesForAssignment for
16890  // C++ semantics.
16891  if (getLangOpts().CPlusPlus &&
16892  IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16893  return false;
16894  if (getLangOpts().CPlusPlus) {
16895  DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16896  isInvalid = true;
16897  } else {
16898  DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16899  }
16900 
16901  break;
16902  case IncompatibleNestedPointerQualifiers:
16903  if (getLangOpts().CPlusPlus) {
16904  isInvalid = true;
16905  DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16906  } else {
16907  DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16908  }
16909  break;
16910  case IncompatibleNestedPointerAddressSpaceMismatch:
16911  DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16912  isInvalid = true;
16913  break;
16914  case IntToBlockPointer:
16915  DiagKind = diag::err_int_to_block_pointer;
16916  isInvalid = true;
16917  break;
16918  case IncompatibleBlockPointer:
16919  DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16920  isInvalid = true;
16921  break;
16922  case IncompatibleObjCQualifiedId: {
16923  if (SrcType->isObjCQualifiedIdType()) {
16924  const ObjCObjectPointerType *srcOPT =
16925  SrcType->castAs<ObjCObjectPointerType>();
16926  for (auto *srcProto : srcOPT->quals()) {
16927  PDecl = srcProto;
16928  break;
16929  }
16930  if (const ObjCInterfaceType *IFaceT =
16932  IFace = IFaceT->getDecl();
16933  }
16934  else if (DstType->isObjCQualifiedIdType()) {
16935  const ObjCObjectPointerType *dstOPT =
16936  DstType->castAs<ObjCObjectPointerType>();
16937  for (auto *dstProto : dstOPT->quals()) {
16938  PDecl = dstProto;
16939  break;
16940  }
16941  if (const ObjCInterfaceType *IFaceT =
16943  IFace = IFaceT->getDecl();
16944  }
16945  if (getLangOpts().CPlusPlus) {
16946  DiagKind = diag::err_incompatible_qualified_id;
16947  isInvalid = true;
16948  } else {
16949  DiagKind = diag::warn_incompatible_qualified_id;
16950  }
16951  break;
16952  }
16953  case IncompatibleVectors:
16954  if (getLangOpts().CPlusPlus) {
16955  DiagKind = diag::err_incompatible_vectors;
16956  isInvalid = true;
16957  } else {
16958  DiagKind = diag::warn_incompatible_vectors;
16959  }
16960  break;
16961  case IncompatibleObjCWeakRef:
16962  DiagKind = diag::err_arc_weak_unavailable_assign;
16963  isInvalid = true;
16964  break;
16965  case Incompatible:
16966  if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16967  if (Complained)
16968  *Complained = true;
16969  return true;
16970  }
16971 
16972  DiagKind = diag::err_typecheck_convert_incompatible;
16973  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16974  MayHaveConvFixit = true;
16975  isInvalid = true;
16976  MayHaveFunctionDiff = true;
16977  break;
16978  }
16979 
16980  QualType FirstType, SecondType;
16981  switch (Action) {
16982  case AA_Assigning:
16983  case AA_Initializing:
16984  // The destination type comes first.
16985  FirstType = DstType;
16986  SecondType = SrcType;
16987  break;
16988 
16989  case AA_Returning:
16990  case AA_Passing:
16991  case AA_Passing_CFAudited:
16992  case AA_Converting:
16993  case AA_Sending:
16994  case AA_Casting:
16995  // The source type comes first.
16996  FirstType = SrcType;
16997  SecondType = DstType;
16998  break;
16999  }
17000 
17001  PartialDiagnostic FDiag = PDiag(DiagKind);
17002  AssignmentAction ActionForDiag = Action;
17003  if (Action == AA_Passing_CFAudited)
17004  ActionForDiag = AA_Passing;
17005 
17006  FDiag << FirstType << SecondType << ActionForDiag
17007  << SrcExpr->getSourceRange();
17008 
17009  if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17010  DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17011  auto isPlainChar = [](const clang::Type *Type) {
17012  return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17013  Type->isSpecificBuiltinType(BuiltinType::Char_U);
17014  };
17015  FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17016  isPlainChar(SecondType->getPointeeOrArrayElementType()));
17017  }
17018 
17019  // If we can fix the conversion, suggest the FixIts.
17020  if (!ConvHints.isNull()) {
17021  for (FixItHint &H : ConvHints.Hints)
17022  FDiag << H;
17023  }
17024 
17025  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17026 
17027  if (MayHaveFunctionDiff)
17028  HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17029 
17030  Diag(Loc, FDiag);
17031  if ((DiagKind == diag::warn_incompatible_qualified_id ||
17032  DiagKind == diag::err_incompatible_qualified_id) &&
17033  PDecl && IFace && !IFace->hasDefinition())
17034  Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17035  << IFace << PDecl;
17036 
17037  if (SecondType == Context.OverloadTy)
17038  NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17039  FirstType, /*TakingAddress=*/true);
17040 
17041  if (CheckInferredResultType)
17042  ObjC().EmitRelatedResultTypeNote(SrcExpr);
17043 
17044  if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17045  ObjC().EmitRelatedResultTypeNoteForReturn(DstType);
17046 
17047  if (Complained)
17048  *Complained = true;
17049  return isInvalid;
17050 }
17051 
17053  llvm::APSInt *Result,
17054  AllowFoldKind CanFold) {
17055  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17056  public:
17057  SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17058  QualType T) override {
17059  return S.Diag(Loc, diag::err_ice_not_integral)
17060  << T << S.LangOpts.CPlusPlus;
17061  }
17062  SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17063  return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17064  }
17065  } Diagnoser;
17066 
17067  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17068 }
17069 
17071  llvm::APSInt *Result,
17072  unsigned DiagID,
17073  AllowFoldKind CanFold) {
17074  class IDDiagnoser : public VerifyICEDiagnoser {
17075  unsigned DiagID;
17076 
17077  public:
17078  IDDiagnoser(unsigned DiagID)
17079  : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17080 
17081  SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17082  return S.Diag(Loc, DiagID);
17083  }
17084  } Diagnoser(DiagID);
17085 
17086  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17087 }
17088 
17091  QualType T) {
17092  return diagnoseNotICE(S, Loc);
17093 }
17094 
17097  return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17098 }
17099 
17100 ExprResult
17102  VerifyICEDiagnoser &Diagnoser,
17103  AllowFoldKind CanFold) {
17104  SourceLocation DiagLoc = E->getBeginLoc();
17105 
17106  if (getLangOpts().CPlusPlus11) {
17107  // C++11 [expr.const]p5:
17108  // If an expression of literal class type is used in a context where an
17109  // integral constant expression is required, then that class type shall
17110  // have a single non-explicit conversion function to an integral or
17111  // unscoped enumeration type
17112  ExprResult Converted;
17113  class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17114  VerifyICEDiagnoser &BaseDiagnoser;
17115  public:
17116  CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17117  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17118  BaseDiagnoser.Suppress, true),
17119  BaseDiagnoser(BaseDiagnoser) {}
17120 
17121  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17122  QualType T) override {
17123  return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17124  }
17125 
17126  SemaDiagnosticBuilder diagnoseIncomplete(
17127  Sema &S, SourceLocation Loc, QualType T) override {
17128  return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17129  }
17130 
17131  SemaDiagnosticBuilder diagnoseExplicitConv(
17132  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17133  return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17134  }
17135 
17136  SemaDiagnosticBuilder noteExplicitConv(
17137  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17138  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17139  << ConvTy->isEnumeralType() << ConvTy;
17140  }
17141 
17142  SemaDiagnosticBuilder diagnoseAmbiguous(
17143  Sema &S, SourceLocation Loc, QualType T) override {
17144  return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17145  }
17146 
17147  SemaDiagnosticBuilder noteAmbiguous(
17148  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17149  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17150  << ConvTy->isEnumeralType() << ConvTy;
17151  }
17152 
17153  SemaDiagnosticBuilder diagnoseConversion(
17154  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17155  llvm_unreachable("conversion functions are permitted");
17156  }
17157  } ConvertDiagnoser(Diagnoser);
17158 
17159  Converted = PerformContextualImplicitConversion(DiagLoc, E,
17160  ConvertDiagnoser);
17161  if (Converted.isInvalid())
17162  return Converted;
17163  E = Converted.get();
17164  // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17165  // don't try to evaluate it later. We also don't want to return the
17166  // RecoveryExpr here, as it results in this call succeeding, thus callers of
17167  // this function will attempt to use 'Value'.
17168  if (isa<RecoveryExpr>(E))
17169  return ExprError();
17171  return ExprError();
17172  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17173  // An ICE must be of integral or unscoped enumeration type.
17174  if (!Diagnoser.Suppress)
17175  Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17176  << E->getSourceRange();
17177  return ExprError();
17178  }
17179 
17180  ExprResult RValueExpr = DefaultLvalueConversion(E);
17181  if (RValueExpr.isInvalid())
17182  return ExprError();
17183 
17184  E = RValueExpr.get();
17185 
17186  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17187  // in the non-ICE case.
17188  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17189  if (Result)
17190  *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17191  if (!isa<ConstantExpr>(E))
17192  E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17193  : ConstantExpr::Create(Context, E);
17194  return E;
17195  }
17196 
17197  Expr::EvalResult EvalResult;
17199  EvalResult.Diag = &Notes;
17200 
17201  // Try to evaluate the expression, and produce diagnostics explaining why it's
17202  // not a constant expression as a side-effect.
17203  bool Folded =
17204  E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17205  EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17206 
17207  if (!isa<ConstantExpr>(E))
17208  E = ConstantExpr::Create(Context, E, EvalResult.Val);
17209 
17210  // In C++11, we can rely on diagnostics being produced for any expression
17211  // which is not a constant expression. If no diagnostics were produced, then
17212  // this is a constant expression.
17213  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17214  if (Result)
17215  *Result = EvalResult.Val.getInt();
17216  return E;
17217  }
17218 
17219  // If our only note is the usual "invalid subexpression" note, just point
17220  // the caret at its location rather than producing an essentially
17221  // redundant note.
17222  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17223  diag::note_invalid_subexpr_in_const_expr) {
17224  DiagLoc = Notes[0].first;
17225  Notes.clear();
17226  }
17227 
17228  if (!Folded || !CanFold) {
17229  if (!Diagnoser.Suppress) {
17230  Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17231  for (const PartialDiagnosticAt &Note : Notes)
17232  Diag(Note.first, Note.second);
17233  }
17234 
17235  return ExprError();
17236  }
17237 
17238  Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17239  for (const PartialDiagnosticAt &Note : Notes)
17240  Diag(Note.first, Note.second);
17241 
17242  if (Result)
17243  *Result = EvalResult.Val.getInt();
17244  return E;
17245 }
17246 
17247 namespace {
17248  // Handle the case where we conclude a expression which we speculatively
17249  // considered to be unevaluated is actually evaluated.
17250  class TransformToPE : public TreeTransform<TransformToPE> {
17251  typedef TreeTransform<TransformToPE> BaseTransform;
17252 
17253  public:
17254  TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17255 
17256  // Make sure we redo semantic analysis
17257  bool AlwaysRebuild() { return true; }
17258  bool ReplacingOriginal() { return true; }
17259 
17260  // We need to special-case DeclRefExprs referring to FieldDecls which
17261  // are not part of a member pointer formation; normal TreeTransforming
17262  // doesn't catch this case because of the way we represent them in the AST.
17263  // FIXME: This is a bit ugly; is it really the best way to handle this
17264  // case?
17265  //
17266  // Error on DeclRefExprs referring to FieldDecls.
17267  ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17268  if (isa<FieldDecl>(E->getDecl()) &&
17269  !SemaRef.isUnevaluatedContext())
17270  return SemaRef.Diag(E->getLocation(),
17271  diag::err_invalid_non_static_member_use)
17272  << E->getDecl() << E->getSourceRange();
17273 
17274  return BaseTransform::TransformDeclRefExpr(E);
17275  }
17276 
17277  // Exception: filter out member pointer formation
17278  ExprResult TransformUnaryOperator(UnaryOperator *E) {
17279  if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17280  return E;
17281 
17282  return BaseTransform::TransformUnaryOperator(E);
17283  }
17284 
17285  // The body of a lambda-expression is in a separate expression evaluation
17286  // context so never needs to be transformed.
17287  // FIXME: Ideally we wouldn't transform the closure type either, and would
17288  // just recreate the capture expressions and lambda expression.
17289  StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17290  return SkipLambdaBody(E, Body);
17291  }
17292  };
17293 }
17294 
17296  assert(isUnevaluatedContext() &&
17297  "Should only transform unevaluated expressions");
17298  ExprEvalContexts.back().Context =
17299  ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17300  if (isUnevaluatedContext())
17301  return E;
17302  return TransformToPE(*this).TransformExpr(E);
17303 }
17304 
17306  assert(isUnevaluatedContext() &&
17307  "Should only transform unevaluated expressions");
17308  ExprEvalContexts.back().Context = parentEvaluationContext().Context;
17309  if (isUnevaluatedContext())
17310  return TInfo;
17311  return TransformToPE(*this).TransformType(TInfo);
17312 }
17313 
17314 void
17316  ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17318  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17319  LambdaContextDecl, ExprContext);
17320 
17321  // Discarded statements and immediate contexts nested in other
17322  // discarded statements or immediate context are themselves
17323  // a discarded statement or an immediate context, respectively.
17324  ExprEvalContexts.back().InDiscardedStatement =
17325  parentEvaluationContext().isDiscardedStatementContext();
17326 
17327  // C++23 [expr.const]/p15
17328  // An expression or conversion is in an immediate function context if [...]
17329  // it is a subexpression of a manifestly constant-evaluated expression or
17330  // conversion.
17331  const auto &Prev = parentEvaluationContext();
17332  ExprEvalContexts.back().InImmediateFunctionContext =
17333  Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17334 
17335  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17336  Prev.InImmediateEscalatingFunctionContext;
17337 
17338  Cleanup.reset();
17339  if (!MaybeODRUseExprs.empty())
17340  std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17341 }
17342 
17343 void
17347  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17348  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17349 }
17350 
17351 namespace {
17352 
17353 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17354  PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17355  if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17356  if (E->getOpcode() == UO_Deref)
17357  return CheckPossibleDeref(S, E->getSubExpr());
17358  } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17359  return CheckPossibleDeref(S, E->getBase());
17360  } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17361  return CheckPossibleDeref(S, E->getBase());
17362  } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17363  QualType Inner;
17364  QualType Ty = E->getType();
17365  if (const auto *Ptr = Ty->getAs<PointerType>())
17366  Inner = Ptr->getPointeeType();
17367  else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17368  Inner = Arr->getElementType();
17369  else
17370  return nullptr;
17371 
17372  if (Inner->hasAttr(attr::NoDeref))
17373  return E;
17374  }
17375  return nullptr;
17376 }
17377 
17378 } // namespace
17379 
17381  for (const Expr *E : Rec.PossibleDerefs) {
17382  const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17383  if (DeclRef) {
17384  const ValueDecl *Decl = DeclRef->getDecl();
17385  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17386  << Decl->getName() << E->getSourceRange();
17387  Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17388  } else {
17389  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17390  << E->getSourceRange();
17391  }
17392  }
17393  Rec.PossibleDerefs.clear();
17394 }
17395 
17396 /// Check whether E, which is either a discarded-value expression or an
17397 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17398 /// and if so, remove it from the list of volatile-qualified assignments that
17399 /// we are going to warn are deprecated.
17401  if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17402  return;
17403 
17404  // Note: ignoring parens here is not justified by the standard rules, but
17405  // ignoring parentheses seems like a more reasonable approach, and this only
17406  // drives a deprecation warning so doesn't affect conformance.
17407  if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17408  if (BO->getOpcode() == BO_Assign) {
17409  auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17410  llvm::erase(LHSs, BO->getLHS());
17411  }
17412  }
17413 }
17414 
17416  assert(getLangOpts().CPlusPlus20 &&
17417  ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17418  "Cannot mark an immediate escalating expression outside of an "
17419  "immediate escalating context");
17420  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17421  Call && Call->getCallee()) {
17422  if (auto *DeclRef =
17423  dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17424  DeclRef->setIsImmediateEscalating(true);
17425  } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17426  Ctr->setIsImmediateEscalating(true);
17427  } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17428  DeclRef->setIsImmediateEscalating(true);
17429  } else {
17430  assert(false && "expected an immediately escalating expression");
17431  }
17432  if (FunctionScopeInfo *FI = getCurFunction())
17433  FI->FoundImmediateEscalatingExpression = true;
17434 }
17435 
17437  if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17438  !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17439  isCheckingDefaultArgumentOrInitializer() ||
17440  RebuildingImmediateInvocation || isImmediateFunctionContext())
17441  return E;
17442 
17443  /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17444  /// It's OK if this fails; we'll also remove this in
17445  /// HandleImmediateInvocations, but catching it here allows us to avoid
17446  /// walking the AST looking for it in simple cases.
17447  if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17448  if (auto *DeclRef =
17449  dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17450  ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17451 
17452  // C++23 [expr.const]/p16
17453  // An expression or conversion is immediate-escalating if it is not initially
17454  // in an immediate function context and it is [...] an immediate invocation
17455  // that is not a constant expression and is not a subexpression of an
17456  // immediate invocation.
17457  APValue Cached;
17458  auto CheckConstantExpressionAndKeepResult = [&]() {
17460  Expr::EvalResult Eval;
17461  Eval.Diag = &Notes;
17462  bool Res = E.get()->EvaluateAsConstantExpr(
17463  Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17464  if (Res && Notes.empty()) {
17465  Cached = std::move(Eval.Val);
17466  return true;
17467  }
17468  return false;
17469  };
17470 
17471  if (!E.get()->isValueDependent() &&
17472  ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17473  !CheckConstantExpressionAndKeepResult()) {
17474  MarkExpressionAsImmediateEscalating(E.get());
17475  return E;
17476  }
17477 
17478  if (Cleanup.exprNeedsCleanups()) {
17479  // Since an immediate invocation is a full expression itself - it requires
17480  // an additional ExprWithCleanups node, but it can participate to a bigger
17481  // full expression which actually requires cleanups to be run after so
17482  // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17483  // may discard cleanups for outer expression too early.
17484 
17485  // Note that ExprWithCleanups created here must always have empty cleanup
17486  // objects:
17487  // - compound literals do not create cleanup objects in C++ and immediate
17488  // invocations are C++-only.
17489  // - blocks are not allowed inside constant expressions and compiler will
17490  // issue an error if they appear there.
17491  //
17492  // Hence, in correct code any cleanup objects created inside current
17493  // evaluation context must be outside the immediate invocation.
17494  E = ExprWithCleanups::Create(getASTContext(), E.get(),
17495  Cleanup.cleanupsHaveSideEffects(), {});
17496  }
17497 
17499  getASTContext(), E.get(),
17500  ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17501  getASTContext()),
17502  /*IsImmediateInvocation*/ true);
17503  if (Cached.hasValue())
17504  Res->MoveIntoResult(Cached, getASTContext());
17505  /// Value-dependent constant expressions should not be immediately
17506  /// evaluated until they are instantiated.
17507  if (!Res->isValueDependent())
17508  ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17509  return Res;
17510 }
17511 
17513  Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17515  Expr::EvalResult Eval;
17516  Eval.Diag = &Notes;
17517  ConstantExpr *CE = Candidate.getPointer();
17518  bool Result = CE->EvaluateAsConstantExpr(
17520  if (!Result || !Notes.empty()) {
17521  SemaRef.FailedImmediateInvocations.insert(CE);
17522  Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17523  if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17524  InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17525  FunctionDecl *FD = nullptr;
17526  if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17527  FD = cast<FunctionDecl>(Call->getCalleeDecl());
17528  else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17529  FD = Call->getConstructor();
17530  else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17531  FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17532 
17533  assert(FD && FD->isImmediateFunction() &&
17534  "could not find an immediate function in this expression");
17535  if (FD->isInvalidDecl())
17536  return;
17537  SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17538  << FD << FD->isConsteval();
17539  if (auto Context =
17541  SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17542  << Context->Decl;
17543  SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17544  }
17545  if (!FD->isConsteval())
17547  for (auto &Note : Notes)
17548  SemaRef.Diag(Note.first, Note.second);
17549  return;
17550  }
17551  CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17552 }
17553 
17557  struct ComplexRemove : TreeTransform<ComplexRemove> {
17559  llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17562  CurrentII;
17563  ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17566  4>::reverse_iterator Current)
17567  : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17568  void RemoveImmediateInvocation(ConstantExpr* E) {
17569  auto It = std::find_if(CurrentII, IISet.rend(),
17571  return Elem.getPointer() == E;
17572  });
17573  // It is possible that some subexpression of the current immediate
17574  // invocation was handled from another expression evaluation context. Do
17575  // not handle the current immediate invocation if some of its
17576  // subexpressions failed before.
17577  if (It == IISet.rend()) {
17578  if (SemaRef.FailedImmediateInvocations.contains(E))
17579  CurrentII->setInt(1);
17580  } else {
17581  It->setInt(1); // Mark as deleted
17582  }
17583  }
17584  ExprResult TransformConstantExpr(ConstantExpr *E) {
17585  if (!E->isImmediateInvocation())
17586  return Base::TransformConstantExpr(E);
17587  RemoveImmediateInvocation(E);
17588  return Base::TransformExpr(E->getSubExpr());
17589  }
17590  /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17591  /// we need to remove its DeclRefExpr from the DRSet.
17592  ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17593  DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17594  return Base::TransformCXXOperatorCallExpr(E);
17595  }
17596  /// Base::TransformUserDefinedLiteral doesn't preserve the
17597  /// UserDefinedLiteral node.
17598  ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17599  /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17600  /// here.
17601  ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17602  if (!Init)
17603  return Init;
17604  /// ConstantExpr are the first layer of implicit node to be removed so if
17605  /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17606  if (auto *CE = dyn_cast<ConstantExpr>(Init))
17607  if (CE->isImmediateInvocation())
17608  RemoveImmediateInvocation(CE);
17609  return Base::TransformInitializer(Init, NotCopyInit);
17610  }
17611  ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17612  DRSet.erase(E);
17613  return E;
17614  }
17615  ExprResult TransformLambdaExpr(LambdaExpr *E) {
17616  // Do not rebuild lambdas to avoid creating a new type.
17617  // Lambdas have already been processed inside their eval context.
17618  return E;
17619  }
17620  bool AlwaysRebuild() { return false; }
17621  bool ReplacingOriginal() { return true; }
17622  bool AllowSkippingCXXConstructExpr() {
17623  bool Res = AllowSkippingFirstCXXConstructExpr;
17624  AllowSkippingFirstCXXConstructExpr = true;
17625  return Res;
17626  }
17627  bool AllowSkippingFirstCXXConstructExpr = true;
17628  } Transformer(SemaRef, Rec.ReferenceToConsteval,
17630 
17631  /// CXXConstructExpr with a single argument are getting skipped by
17632  /// TreeTransform in some situtation because they could be implicit. This
17633  /// can only occur for the top-level CXXConstructExpr because it is used
17634  /// nowhere in the expression being transformed therefore will not be rebuilt.
17635  /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17636  /// skipping the first CXXConstructExpr.
17637  if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17638  Transformer.AllowSkippingFirstCXXConstructExpr = false;
17639 
17640  ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17641  // The result may not be usable in case of previous compilation errors.
17642  // In this case evaluation of the expression may result in crash so just
17643  // don't do anything further with the result.
17644  if (Res.isUsable()) {
17645  Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17646  It->getPointer()->setSubExpr(Res.get());
17647  }
17648 }
17649 
17650 static void
17653  if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17654  Rec.ReferenceToConsteval.size() == 0) ||
17656  return;
17657 
17658  /// When we have more than 1 ImmediateInvocationCandidates or previously
17659  /// failed immediate invocations, we need to check for nested
17660  /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17661  /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17662  /// invocation.
17663  if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17664  !SemaRef.FailedImmediateInvocations.empty()) {
17665 
17666  /// Prevent sema calls during the tree transform from adding pointers that
17667  /// are already in the sets.
17668  llvm::SaveAndRestore DisableIITracking(
17669  SemaRef.RebuildingImmediateInvocation, true);
17670 
17671  /// Prevent diagnostic during tree transfrom as they are duplicates
17672  Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17673 
17674  for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17675  It != Rec.ImmediateInvocationCandidates.rend(); It++)
17676  if (!It->getInt())
17677  RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17678  } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17679  Rec.ReferenceToConsteval.size()) {
17680  struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17681  llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17682  SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17683  bool VisitDeclRefExpr(DeclRefExpr *E) {
17684  DRSet.erase(E);
17685  return DRSet.size();
17686  }
17687  } Visitor(Rec.ReferenceToConsteval);
17688  Visitor.TraverseStmt(
17689  Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17690  }
17691  for (auto CE : Rec.ImmediateInvocationCandidates)
17692  if (!CE.getInt())
17694  for (auto *DR : Rec.ReferenceToConsteval) {
17695  // If the expression is immediate escalating, it is not an error;
17696  // The outer context itself becomes immediate and further errors,
17697  // if any, will be handled by DiagnoseImmediateEscalatingReason.
17698  if (DR->isImmediateEscalating())
17699  continue;
17700  auto *FD = cast<FunctionDecl>(DR->getDecl());
17701  const NamedDecl *ND = FD;
17702  if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17703  MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17704  ND = MD->getParent();
17705 
17706  // C++23 [expr.const]/p16
17707  // An expression or conversion is immediate-escalating if it is not
17708  // initially in an immediate function context and it is [...] a
17709  // potentially-evaluated id-expression that denotes an immediate function
17710  // that is not a subexpression of an immediate invocation.
17711  bool ImmediateEscalating = false;
17712  bool IsPotentiallyEvaluated =
17713  Rec.Context ==
17715  Rec.Context ==
17717  if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17718  ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17719 
17721  (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17722  SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17723  << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17724  SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17725  if (auto Context =
17727  SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17728  << Context->Decl;
17729  SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17730  }
17731  if (FD->isImmediateEscalating() && !FD->isConsteval())
17733 
17734  } else {
17736  }
17737  }
17738 }
17739 
17741  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17742  unsigned NumTypos = Rec.NumTypos;
17743 
17744  if (!Rec.Lambdas.empty()) {
17746  if (!getLangOpts().CPlusPlus20 &&
17747  (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17748  Rec.isUnevaluated() ||
17749  (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17750  unsigned D;
17751  if (Rec.isUnevaluated()) {
17752  // C++11 [expr.prim.lambda]p2:
17753  // A lambda-expression shall not appear in an unevaluated operand
17754  // (Clause 5).
17755  D = diag::err_lambda_unevaluated_operand;
17756  } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17757  // C++1y [expr.const]p2:
17758  // A conditional-expression e is a core constant expression unless the
17759  // evaluation of e, following the rules of the abstract machine, would
17760  // evaluate [...] a lambda-expression.
17761  D = diag::err_lambda_in_constant_expression;
17762  } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17763  // C++17 [expr.prim.lamda]p2:
17764  // A lambda-expression shall not appear [...] in a template-argument.
17765  D = diag::err_lambda_in_invalid_context;
17766  } else
17767  llvm_unreachable("Couldn't infer lambda error message.");
17768 
17769  for (const auto *L : Rec.Lambdas)
17770  Diag(L->getBeginLoc(), D);
17771  }
17772  }
17773 
17774  // Append the collected materialized temporaries into previous context before
17775  // exit if the previous also is a lifetime extending context.
17776  auto &PrevRecord = parentEvaluationContext();
17777  if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
17778  PrevRecord.InLifetimeExtendingContext &&
17779  !Rec.ForRangeLifetimeExtendTemps.empty()) {
17780  PrevRecord.ForRangeLifetimeExtendTemps.append(
17782  }
17783 
17784  WarnOnPendingNoDerefs(Rec);
17785  HandleImmediateInvocations(*this, Rec);
17786 
17787  // Warn on any volatile-qualified simple-assignments that are not discarded-
17788  // value expressions nor unevaluated operands (those cases get removed from
17789  // this list by CheckUnusedVolatileAssignment).
17790  for (auto *BO : Rec.VolatileAssignmentLHSs)
17791  Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17792  << BO->getType();
17793 
17794  // When are coming out of an unevaluated context, clear out any
17795  // temporaries that we may have created as part of the evaluation of
17796  // the expression in that context: they aren't relevant because they
17797  // will never be constructed.
17798  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17799  ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17800  ExprCleanupObjects.end());
17801  Cleanup = Rec.ParentCleanup;
17802  CleanupVarDeclMarking();
17803  std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17804  // Otherwise, merge the contexts together.
17805  } else {
17806  Cleanup.mergeFrom(Rec.ParentCleanup);
17807  MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17808  Rec.SavedMaybeODRUseExprs.end());
17809  }
17810 
17811  // Pop the current expression evaluation context off the stack.
17812  ExprEvalContexts.pop_back();
17813 
17814  // The global expression evaluation context record is never popped.
17815  ExprEvalContexts.back().NumTypos += NumTypos;
17816 }
17817 
17819  ExprCleanupObjects.erase(
17820  ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17821  ExprCleanupObjects.end());
17822  Cleanup.reset();
17823  MaybeODRUseExprs.clear();
17824 }
17825 
17827  ExprResult Result = CheckPlaceholderExpr(E);
17828  if (Result.isInvalid())
17829  return ExprError();
17830  E = Result.get();
17831  if (!E->getType()->isVariablyModifiedType())
17832  return E;
17833  return TransformToPotentiallyEvaluated(E);
17834 }
17835 
17836 /// Are we in a context that is potentially constant evaluated per C++20
17837 /// [expr.const]p12?
17839  /// C++2a [expr.const]p12:
17840  // An expression or conversion is potentially constant evaluated if it is
17841  switch (SemaRef.ExprEvalContexts.back().Context) {
17844 
17845  // -- a manifestly constant-evaluated expression,
17849  // -- a potentially-evaluated expression,
17851  // -- an immediate subexpression of a braced-init-list,
17852 
17853  // -- [FIXME] an expression of the form & cast-expression that occurs
17854  // within a templated entity
17855  // -- a subexpression of one of the above that is not a subexpression of
17856  // a nested unevaluated operand.
17857  return true;
17858 
17861  // Expressions in this context are never evaluated.
17862  return false;
17863  }
17864  llvm_unreachable("Invalid context");
17865 }
17866 
17867 /// Return true if this function has a calling convention that requires mangling
17868 /// in the size of the parameter pack.
17870  // These manglings don't do anything on non-Windows or non-x86 platforms, so
17871  // we don't need parameter type sizes.
17872  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17873  if (!TT.isOSWindows() || !TT.isX86())
17874  return false;
17875 
17876  // If this is C++ and this isn't an extern "C" function, parameters do not
17877  // need to be complete. In this case, C++ mangling will apply, which doesn't
17878  // use the size of the parameters.
17879  if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17880  return false;
17881 
17882  // Stdcall, fastcall, and vectorcall need this special treatment.
17883  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17884  switch (CC) {
17885  case CC_X86StdCall:
17886  case CC_X86FastCall:
17887  case CC_X86VectorCall:
17888  return true;
17889  default:
17890  break;
17891  }
17892  return false;
17893 }
17894 
17895 /// Require that all of the parameter types of function be complete. Normally,
17896 /// parameter types are only required to be complete when a function is called
17897 /// or defined, but to mangle functions with certain calling conventions, the
17898 /// mangler needs to know the size of the parameter list. In this situation,
17899 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17900 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17901 /// result in a linker error. Clang doesn't implement this behavior, and instead
17902 /// attempts to error at compile time.
17904  SourceLocation Loc) {
17905  class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17906  FunctionDecl *FD;
17907  ParmVarDecl *Param;
17908 
17909  public:
17910  ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17911  : FD(FD), Param(Param) {}
17912 
17913  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17914  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17915  StringRef CCName;
17916  switch (CC) {
17917  case CC_X86StdCall:
17918  CCName = "stdcall";
17919  break;
17920  case CC_X86FastCall:
17921  CCName = "fastcall";
17922  break;
17923  case CC_X86VectorCall:
17924  CCName = "vectorcall";
17925  break;
17926  default:
17927  llvm_unreachable("CC does not need mangling");
17928  }
17929 
17930  S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17931  << Param->getDeclName() << FD->getDeclName() << CCName;
17932  }
17933  };
17934 
17935  for (ParmVarDecl *Param : FD->parameters()) {
17936  ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17937  S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17938  }
17939 }
17940 
17941 namespace {
17942 enum class OdrUseContext {
17943  /// Declarations in this context are not odr-used.
17944  None,
17945  /// Declarations in this context are formally odr-used, but this is a
17946  /// dependent context.
17947  Dependent,
17948  /// Declarations in this context are odr-used but not actually used (yet).
17949  FormallyOdrUsed,
17950  /// Declarations in this context are used.
17951  Used
17952 };
17953 }
17954 
17955 /// Are we within a context in which references to resolved functions or to
17956 /// variables result in odr-use?
17957 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17958  OdrUseContext Result;
17959 
17960  switch (SemaRef.ExprEvalContexts.back().Context) {
17964  return OdrUseContext::None;
17965 
17969  Result = OdrUseContext::Used;
17970  break;
17971 
17973  Result = OdrUseContext::FormallyOdrUsed;
17974  break;
17975 
17977  // A default argument formally results in odr-use, but doesn't actually
17978  // result in a use in any real sense until it itself is used.
17979  Result = OdrUseContext::FormallyOdrUsed;
17980  break;
17981  }
17982 
17983  if (SemaRef.CurContext->isDependentContext())
17984  return OdrUseContext::Dependent;
17985 
17986  return Result;
17987 }
17988 
17990  if (!Func->isConstexpr())
17991  return false;
17992 
17993  if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17994  return true;
17995  auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17996  return CCD && CCD->getInheritedConstructor();
17997 }
17998 
17999 /// Mark a function referenced, and check whether it is odr-used
18000 /// (C++ [basic.def.odr]p2, C99 6.9p3)
18002  bool MightBeOdrUse) {
18003  assert(Func && "No function?");
18004 
18005  Func->setReferenced();
18006 
18007  // Recursive functions aren't really used until they're used from some other
18008  // context.
18009  bool IsRecursiveCall = CurContext == Func;
18010 
18011  // C++11 [basic.def.odr]p3:
18012  // A function whose name appears as a potentially-evaluated expression is
18013  // odr-used if it is the unique lookup result or the selected member of a
18014  // set of overloaded functions [...].
18015  //
18016  // We (incorrectly) mark overload resolution as an unevaluated context, so we
18017  // can just check that here.
18018  OdrUseContext OdrUse =
18019  MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18020  if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18021  OdrUse = OdrUseContext::FormallyOdrUsed;
18022 
18023  // Trivial default constructors and destructors are never actually used.
18024  // FIXME: What about other special members?
18025  if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18026  OdrUse == OdrUseContext::Used) {
18027  if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18028  if (Constructor->isDefaultConstructor())
18029  OdrUse = OdrUseContext::FormallyOdrUsed;
18030  if (isa<CXXDestructorDecl>(Func))
18031  OdrUse = OdrUseContext::FormallyOdrUsed;
18032  }
18033 
18034  // C++20 [expr.const]p12:
18035  // A function [...] is needed for constant evaluation if it is [...] a
18036  // constexpr function that is named by an expression that is potentially
18037  // constant evaluated
18038  bool NeededForConstantEvaluation =
18041 
18042  // Determine whether we require a function definition to exist, per
18043  // C++11 [temp.inst]p3:
18044  // Unless a function template specialization has been explicitly
18045  // instantiated or explicitly specialized, the function template
18046  // specialization is implicitly instantiated when the specialization is
18047  // referenced in a context that requires a function definition to exist.
18048  // C++20 [temp.inst]p7:
18049  // The existence of a definition of a [...] function is considered to
18050  // affect the semantics of the program if the [...] function is needed for
18051  // constant evaluation by an expression
18052  // C++20 [basic.def.odr]p10:
18053  // Every program shall contain exactly one definition of every non-inline
18054  // function or variable that is odr-used in that program outside of a
18055  // discarded statement
18056  // C++20 [special]p1:
18057  // The implementation will implicitly define [defaulted special members]
18058  // if they are odr-used or needed for constant evaluation.
18059  //
18060  // Note that we skip the implicit instantiation of templates that are only
18061  // used in unused default arguments or by recursive calls to themselves.
18062  // This is formally non-conforming, but seems reasonable in practice.
18063  bool NeedDefinition =
18064  !IsRecursiveCall &&
18065  (OdrUse == OdrUseContext::Used ||
18066  (NeededForConstantEvaluation && !Func->isPureVirtual()));
18067 
18068  // C++14 [temp.expl.spec]p6:
18069  // If a template [...] is explicitly specialized then that specialization
18070  // shall be declared before the first use of that specialization that would
18071  // cause an implicit instantiation to take place, in every translation unit
18072  // in which such a use occurs
18073  if (NeedDefinition &&
18074  (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18075  Func->getMemberSpecializationInfo()))
18076  checkSpecializationReachability(Loc, Func);
18077 
18078  if (getLangOpts().CUDA)
18079  CUDA().CheckCall(Loc, Func);
18080 
18081  // If we need a definition, try to create one.
18082  if (NeedDefinition && !Func->getBody()) {
18084  if (CXXConstructorDecl *Constructor =
18085  dyn_cast<CXXConstructorDecl>(Func)) {
18086  Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18087  if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18088  if (Constructor->isDefaultConstructor()) {
18089  if (Constructor->isTrivial() &&
18090  !Constructor->hasAttr<DLLExportAttr>())
18091  return;
18092  DefineImplicitDefaultConstructor(Loc, Constructor);
18093  } else if (Constructor->isCopyConstructor()) {
18094  DefineImplicitCopyConstructor(Loc, Constructor);
18095  } else if (Constructor->isMoveConstructor()) {
18096  DefineImplicitMoveConstructor(Loc, Constructor);
18097  }
18098  } else if (Constructor->getInheritedConstructor()) {
18099  DefineInheritingConstructor(Loc, Constructor);
18100  }
18101  } else if (CXXDestructorDecl *Destructor =
18102  dyn_cast<CXXDestructorDecl>(Func)) {
18103  Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18104  if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18105  if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18106  return;
18107  DefineImplicitDestructor(Loc, Destructor);
18108  }
18109  if (Destructor->isVirtual() && getLangOpts().AppleKext)
18110  MarkVTableUsed(Loc, Destructor->getParent());
18111  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18112  if (MethodDecl->isOverloadedOperator() &&
18113  MethodDecl->getOverloadedOperator() == OO_Equal) {
18114  MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18115  if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18116  if (MethodDecl->isCopyAssignmentOperator())
18117  DefineImplicitCopyAssignment(Loc, MethodDecl);
18118  else if (MethodDecl->isMoveAssignmentOperator())
18119  DefineImplicitMoveAssignment(Loc, MethodDecl);
18120  }
18121  } else if (isa<CXXConversionDecl>(MethodDecl) &&
18122  MethodDecl->getParent()->isLambda()) {
18123  CXXConversionDecl *Conversion =
18124  cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18125  if (Conversion->isLambdaToBlockPointerConversion())
18126  DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18127  else
18128  DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18129  } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18130  MarkVTableUsed(Loc, MethodDecl->getParent());
18131  }
18132 
18133  if (Func->isDefaulted() && !Func->isDeleted()) {
18134  DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18135  if (DCK != DefaultedComparisonKind::None)
18136  DefineDefaultedComparison(Loc, Func, DCK);
18137  }
18138 
18139  // Implicit instantiation of function templates and member functions of
18140  // class templates.
18141  if (Func->isImplicitlyInstantiable()) {
18143  Func->getTemplateSpecializationKindForInstantiation();
18144  SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18145  bool FirstInstantiation = PointOfInstantiation.isInvalid();
18146  if (FirstInstantiation) {
18147  PointOfInstantiation = Loc;
18148  if (auto *MSI = Func->getMemberSpecializationInfo())
18149  MSI->setPointOfInstantiation(Loc);
18150  // FIXME: Notify listener.
18151  else
18152  Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18153  } else if (TSK != TSK_ImplicitInstantiation) {
18154  // Use the point of use as the point of instantiation, instead of the
18155  // point of explicit instantiation (which we track as the actual point
18156  // of instantiation). This gives better backtraces in diagnostics.
18157  PointOfInstantiation = Loc;
18158  }
18159 
18160  if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18161  Func->isConstexpr()) {
18162  if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18163  cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18164  CodeSynthesisContexts.size())
18165  PendingLocalImplicitInstantiations.push_back(
18166  std::make_pair(Func, PointOfInstantiation));
18167  else if (Func->isConstexpr())
18168  // Do not defer instantiations of constexpr functions, to avoid the
18169  // expression evaluator needing to call back into Sema if it sees a
18170  // call to such a function.
18171  InstantiateFunctionDefinition(PointOfInstantiation, Func);
18172  else {
18173  Func->setInstantiationIsPending(true);
18174  PendingInstantiations.push_back(
18175  std::make_pair(Func, PointOfInstantiation));
18176  // Notify the consumer that a function was implicitly instantiated.
18177  Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18178  }
18179  }
18180  } else {
18181  // Walk redefinitions, as some of them may be instantiable.
18182  for (auto *i : Func->redecls()) {
18183  if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18184  MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18185  }
18186  }
18187  });
18188  }
18189 
18190  // If a constructor was defined in the context of a default parameter
18191  // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18192  // context), its initializers may not be referenced yet.
18193  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18195  *this,
18196  Constructor->isImmediateFunction()
18197  ? ExpressionEvaluationContext::ImmediateFunctionContext
18198  : ExpressionEvaluationContext::PotentiallyEvaluated,
18199  Constructor);
18200  for (CXXCtorInitializer *Init : Constructor->inits()) {
18201  if (Init->isInClassMemberInitializer())
18202  runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18203  MarkDeclarationsReferencedInExpr(Init->getInit());
18204  });
18205  }
18206  }
18207 
18208  // C++14 [except.spec]p17:
18209  // An exception-specification is considered to be needed when:
18210  // - the function is odr-used or, if it appears in an unevaluated operand,
18211  // would be odr-used if the expression were potentially-evaluated;
18212  //
18213  // Note, we do this even if MightBeOdrUse is false. That indicates that the
18214  // function is a pure virtual function we're calling, and in that case the
18215  // function was selected by overload resolution and we need to resolve its
18216  // exception specification for a different reason.
18217  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18219  ResolveExceptionSpec(Loc, FPT);
18220 
18221  // A callee could be called by a host function then by a device function.
18222  // If we only try recording once, we will miss recording the use on device
18223  // side. Therefore keep trying until it is recorded.
18224  if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18225  !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
18226  CUDA().RecordImplicitHostDeviceFuncUsedByDevice(Func);
18227 
18228  // If this is the first "real" use, act on that.
18229  if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18230  // Keep track of used but undefined functions.
18231  if (!Func->isDefined()) {
18232  if (mightHaveNonExternalLinkage(Func))
18233  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18234  else if (Func->getMostRecentDecl()->isInlined() &&
18235  !LangOpts.GNUInline &&
18236  !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18237  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18238  else if (isExternalWithNoLinkageType(Func))
18239  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18240  }
18241 
18242  // Some x86 Windows calling conventions mangle the size of the parameter
18243  // pack into the name. Computing the size of the parameters requires the
18244  // parameter types to be complete. Check that now.
18245  if (funcHasParameterSizeMangling(*this, Func))
18247 
18248  // In the MS C++ ABI, the compiler emits destructor variants where they are
18249  // used. If the destructor is used here but defined elsewhere, mark the
18250  // virtual base destructors referenced. If those virtual base destructors
18251  // are inline, this will ensure they are defined when emitting the complete
18252  // destructor variant. This checking may be redundant if the destructor is
18253  // provided later in this TU.
18254  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18255  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18256  CXXRecordDecl *Parent = Dtor->getParent();
18257  if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18258  CheckCompleteDestructorVariant(Loc, Dtor);
18259  }
18260  }
18261 
18262  Func->markUsed(Context);
18263  }
18264 }
18265 
18266 /// Directly mark a variable odr-used. Given a choice, prefer to use
18267 /// MarkVariableReferenced since it does additional checks and then
18268 /// calls MarkVarDeclODRUsed.
18269 /// If the variable must be captured:
18270 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18271 /// - else capture it in the DeclContext that maps to the
18272 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18273 static void
18275  const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18276  // Keep track of used but undefined variables.
18277  // FIXME: We shouldn't suppress this warning for static data members.
18278  VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18279  assert(Var && "expected a capturable variable");
18280 
18281  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18282  (!Var->isExternallyVisible() || Var->isInline() ||
18283  SemaRef.isExternalWithNoLinkageType(Var)) &&
18284  !(Var->isStaticDataMember() && Var->hasInit())) {
18285  SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18286  if (old.isInvalid())
18287  old = Loc;
18288  }
18289  QualType CaptureType, DeclRefType;
18290  if (SemaRef.LangOpts.OpenMP)
18291  SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
18293  /*EllipsisLoc*/ SourceLocation(),
18294  /*BuildAndDiagnose*/ true, CaptureType,
18295  DeclRefType, FunctionScopeIndexToStopAt);
18296 
18297  if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18298  auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18299  auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18300  auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18301  if (VarTarget == SemaCUDA::CVT_Host &&
18302  (UserTarget == CUDAFunctionTarget::Device ||
18303  UserTarget == CUDAFunctionTarget::HostDevice ||
18304  UserTarget == CUDAFunctionTarget::Global)) {
18305  // Diagnose ODR-use of host global variables in device functions.
18306  // Reference of device global variables in host functions is allowed
18307  // through shadow variables therefore it is not diagnosed.
18308  if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18309  SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18310  << /*host*/ 2 << /*variable*/ 1 << Var
18311  << llvm::to_underlying(UserTarget);
18312  SemaRef.targetDiag(Var->getLocation(),
18313  Var->getType().isConstQualified()
18314  ? diag::note_cuda_const_var_unpromoted
18315  : diag::note_cuda_host_var);
18316  }
18317  } else if (VarTarget == SemaCUDA::CVT_Device &&
18318  !Var->hasAttr<CUDASharedAttr>() &&
18319  (UserTarget == CUDAFunctionTarget::Host ||
18320  UserTarget == CUDAFunctionTarget::HostDevice)) {
18321  // Record a CUDA/HIP device side variable if it is ODR-used
18322  // by host code. This is done conservatively, when the variable is
18323  // referenced in any of the following contexts:
18324  // - a non-function context
18325  // - a host function
18326  // - a host device function
18327  // This makes the ODR-use of the device side variable by host code to
18328  // be visible in the device compilation for the compiler to be able to
18329  // emit template variables instantiated by host code only and to
18330  // externalize the static device side variable ODR-used by host code.
18331  if (!Var->hasExternalStorage())
18332  SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18333  else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18334  (!FD || (!FD->getDescribedFunctionTemplate() &&
18335  SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
18337  SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18338  }
18339  }
18340 
18341  V->markUsed(SemaRef.Context);
18342 }
18343 
18346  unsigned CapturingScopeIndex) {
18347  MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18348 }
18349 
18351  ValueDecl *var) {
18352  DeclContext *VarDC = var->getDeclContext();
18353 
18354  // If the parameter still belongs to the translation unit, then
18355  // we're actually just using one parameter in the declaration of
18356  // the next.
18357  if (isa<ParmVarDecl>(var) &&
18358  isa<TranslationUnitDecl>(VarDC))
18359  return;
18360 
18361  // For C code, don't diagnose about capture if we're not actually in code
18362  // right now; it's impossible to write a non-constant expression outside of
18363  // function context, so we'll get other (more useful) diagnostics later.
18364  //
18365  // For C++, things get a bit more nasty... it would be nice to suppress this
18366  // diagnostic for certain cases like using a local variable in an array bound
18367  // for a member of a local class, but the correct predicate is not obvious.
18368  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18369  return;
18370 
18371  unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18372  unsigned ContextKind = 3; // unknown
18373  if (isa<CXXMethodDecl>(VarDC) &&
18374  cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18375  ContextKind = 2;
18376  } else if (isa<FunctionDecl>(VarDC)) {
18377  ContextKind = 0;
18378  } else if (isa<BlockDecl>(VarDC)) {
18379  ContextKind = 1;
18380  }
18381 
18382  S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18383  << var << ValueKind << ContextKind << VarDC;
18384  S.Diag(var->getLocation(), diag::note_entity_declared_at)
18385  << var;
18386 
18387  // FIXME: Add additional diagnostic info about class etc. which prevents
18388  // capture.
18389 }
18390 
18392  ValueDecl *Var,
18393  bool &SubCapturesAreNested,
18394  QualType &CaptureType,
18395  QualType &DeclRefType) {
18396  // Check whether we've already captured it.
18397  if (CSI->CaptureMap.count(Var)) {
18398  // If we found a capture, any subcaptures are nested.
18399  SubCapturesAreNested = true;
18400 
18401  // Retrieve the capture type for this variable.
18402  CaptureType = CSI->getCapture(Var).getCaptureType();
18403 
18404  // Compute the type of an expression that refers to this variable.
18405  DeclRefType = CaptureType.getNonReferenceType();
18406 
18407  // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18408  // are mutable in the sense that user can change their value - they are
18409  // private instances of the captured declarations.
18410  const Capture &Cap = CSI->getCapture(Var);
18411  if (Cap.isCopyCapture() &&
18412  !(isa<LambdaScopeInfo>(CSI) &&
18413  !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18414  !(isa<CapturedRegionScopeInfo>(CSI) &&
18415  cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18416  DeclRefType.addConst();
18417  return true;
18418  }
18419  return false;
18420 }
18421 
18422 // Only block literals, captured statements, and lambda expressions can
18423 // capture; other scopes don't work.
18425  ValueDecl *Var,
18427  const bool Diagnose,
18428  Sema &S) {
18429  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18431 
18432  VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18433  if (Underlying) {
18434  if (Underlying->hasLocalStorage() && Diagnose)
18436  }
18437  return nullptr;
18438 }
18439 
18440 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18441 // certain types of variables (unnamed, variably modified types etc.)
18442 // so check for eligibility.
18444  SourceLocation Loc, const bool Diagnose,
18445  Sema &S) {
18446 
18447  assert((isa<VarDecl, BindingDecl>(Var)) &&
18448  "Only variables and structured bindings can be captured");
18449 
18450  bool IsBlock = isa<BlockScopeInfo>(CSI);
18451  bool IsLambda = isa<LambdaScopeInfo>(CSI);
18452 
18453  // Lambdas are not allowed to capture unnamed variables
18454  // (e.g. anonymous unions).
18455  // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18456  // assuming that's the intent.
18457  if (IsLambda && !Var->getDeclName()) {
18458  if (Diagnose) {
18459  S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18460  S.Diag(Var->getLocation(), diag::note_declared_at);
18461  }
18462  return false;
18463  }
18464 
18465  // Prohibit variably-modified types in blocks; they're difficult to deal with.
18466  if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18467  if (Diagnose) {
18468  S.Diag(Loc, diag::err_ref_vm_type);
18469  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18470  }
18471  return false;
18472  }
18473  // Prohibit structs with flexible array members too.
18474  // We cannot capture what is in the tail end of the struct.
18475  if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18476  if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18477  if (Diagnose) {
18478  if (IsBlock)
18479  S.Diag(Loc, diag::err_ref_flexarray_type);
18480  else
18481  S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18482  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18483  }
18484  return false;
18485  }
18486  }
18487  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18488  // Lambdas and captured statements are not allowed to capture __block
18489  // variables; they don't support the expected semantics.
18490  if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18491  if (Diagnose) {
18492  S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18493  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18494  }
18495  return false;
18496  }
18497  // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18498  if (S.getLangOpts().OpenCL && IsBlock &&
18499  Var->getType()->isBlockPointerType()) {
18500  if (Diagnose)
18501  S.Diag(Loc, diag::err_opencl_block_ref_block);
18502  return false;
18503  }
18504 
18505  if (isa<BindingDecl>(Var)) {
18506  if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18507  if (Diagnose)
18509  return false;
18510  } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18511  S.Diag(Loc, S.LangOpts.CPlusPlus20
18512  ? diag::warn_cxx17_compat_capture_binding
18513  : diag::ext_capture_binding)
18514  << Var;
18515  S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18516  }
18517  }
18518 
18519  return true;
18520 }
18521 
18522 // Returns true if the capture by block was successful.
18523 static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
18524  SourceLocation Loc, const bool BuildAndDiagnose,
18525  QualType &CaptureType, QualType &DeclRefType,
18526  const bool Nested, Sema &S, bool Invalid) {
18527  bool ByRef = false;
18528 
18529  // Blocks are not allowed to capture arrays, excepting OpenCL.
18530  // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18531  // (decayed to pointers).
18532  if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18533  if (BuildAndDiagnose) {
18534  S.Diag(Loc, diag::err_ref_array_type);
18535  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18536  Invalid = true;
18537  } else {
18538  return false;
18539  }
18540  }
18541 
18542  // Forbid the block-capture of autoreleasing variables.
18543  if (!Invalid &&
18545  if (BuildAndDiagnose) {
18546  S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18547  << /*block*/ 0;
18548  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18549  Invalid = true;
18550  } else {
18551  return false;
18552  }
18553  }
18554 
18555  // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18556  if (const auto *PT = CaptureType->getAs<PointerType>()) {
18557  QualType PointeeTy = PT->getPointeeType();
18558 
18559  if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18561  !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18562  if (BuildAndDiagnose) {
18563  SourceLocation VarLoc = Var->getLocation();
18564  S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18565  S.Diag(VarLoc, diag::note_declare_parameter_strong);
18566  }
18567  }
18568  }
18569 
18570  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18571  if (HasBlocksAttr || CaptureType->isReferenceType() ||
18572  (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18573  // Block capture by reference does not change the capture or
18574  // declaration reference types.
18575  ByRef = true;
18576  } else {
18577  // Block capture by copy introduces 'const'.
18578  CaptureType = CaptureType.getNonReferenceType().withConst();
18579  DeclRefType = CaptureType;
18580  }
18581 
18582  // Actually capture the variable.
18583  if (BuildAndDiagnose)
18584  BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18585  CaptureType, Invalid);
18586 
18587  return !Invalid;
18588 }
18589 
18590 /// Capture the given variable in the captured region.
18593  const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18594  const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18595  bool IsTopScope, Sema &S, bool Invalid) {
18596  // By default, capture variables by reference.
18597  bool ByRef = true;
18598  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18599  ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18600  } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18601  // Using an LValue reference type is consistent with Lambdas (see below).
18602  if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18603  bool HasConst = DeclRefType.isConstQualified();
18604  DeclRefType = DeclRefType.getUnqualifiedType();
18605  // Don't lose diagnostics about assignments to const.
18606  if (HasConst)
18607  DeclRefType.addConst();
18608  }
18609  // Do not capture firstprivates in tasks.
18610  if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18611  RSI->OpenMPCaptureLevel) != OMPC_unknown)
18612  return true;
18613  ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18614  RSI->OpenMPCaptureLevel);
18615  }
18616 
18617  if (ByRef)
18618  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18619  else
18620  CaptureType = DeclRefType;
18621 
18622  // Actually capture the variable.
18623  if (BuildAndDiagnose)
18624  RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18625  Loc, SourceLocation(), CaptureType, Invalid);
18626 
18627  return !Invalid;
18628 }
18629 
18630 /// Capture the given variable in the lambda.
18632  SourceLocation Loc, const bool BuildAndDiagnose,
18633  QualType &CaptureType, QualType &DeclRefType,
18634  const bool RefersToCapturedVariable,
18635  const Sema::TryCaptureKind Kind,
18636  SourceLocation EllipsisLoc, const bool IsTopScope,
18637  Sema &S, bool Invalid) {
18638  // Determine whether we are capturing by reference or by value.
18639  bool ByRef = false;
18640  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18641  ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18642  } else {
18644  }
18645 
18646  if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18648  S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18649  Invalid = true;
18650  }
18651 
18652  // Compute the type of the field that will capture this variable.
18653  if (ByRef) {
18654  // C++11 [expr.prim.lambda]p15:
18655  // An entity is captured by reference if it is implicitly or
18656  // explicitly captured but not captured by copy. It is
18657  // unspecified whether additional unnamed non-static data
18658  // members are declared in the closure type for entities
18659  // captured by reference.
18660  //
18661  // FIXME: It is not clear whether we want to build an lvalue reference
18662  // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18663  // to do the former, while EDG does the latter. Core issue 1249 will
18664  // clarify, but for now we follow GCC because it's a more permissive and
18665  // easily defensible position.
18666  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18667  } else {
18668  // C++11 [expr.prim.lambda]p14:
18669  // For each entity captured by copy, an unnamed non-static
18670  // data member is declared in the closure type. The
18671  // declaration order of these members is unspecified. The type
18672  // of such a data member is the type of the corresponding
18673  // captured entity if the entity is not a reference to an
18674  // object, or the referenced type otherwise. [Note: If the
18675  // captured entity is a reference to a function, the
18676  // corresponding data member is also a reference to a
18677  // function. - end note ]
18678  if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18679  if (!RefType->getPointeeType()->isFunctionType())
18680  CaptureType = RefType->getPointeeType();
18681  }
18682 
18683  // Forbid the lambda copy-capture of autoreleasing variables.
18684  if (!Invalid &&
18686  if (BuildAndDiagnose) {
18687  S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18688  S.Diag(Var->getLocation(), diag::note_previous_decl)
18689  << Var->getDeclName();
18690  Invalid = true;
18691  } else {
18692  return false;
18693  }
18694  }
18695 
18696  // Make sure that by-copy captures are of a complete and non-abstract type.
18697  if (!Invalid && BuildAndDiagnose) {
18698  if (!CaptureType->isDependentType() &&
18700  Loc, CaptureType,
18701  diag::err_capture_of_incomplete_or_sizeless_type,
18702  Var->getDeclName()))
18703  Invalid = true;
18704  else if (S.RequireNonAbstractType(Loc, CaptureType,
18705  diag::err_capture_of_abstract_type))
18706  Invalid = true;
18707  }
18708  }
18709 
18710  // Compute the type of a reference to this captured variable.
18711  if (ByRef)
18712  DeclRefType = CaptureType.getNonReferenceType();
18713  else {
18714  // C++ [expr.prim.lambda]p5:
18715  // The closure type for a lambda-expression has a public inline
18716  // function call operator [...]. This function call operator is
18717  // declared const (9.3.1) if and only if the lambda-expression's
18718  // parameter-declaration-clause is not followed by mutable.
18719  DeclRefType = CaptureType.getNonReferenceType();
18720  bool Const = LSI->lambdaCaptureShouldBeConst();
18721  if (Const && !CaptureType->isReferenceType())
18722  DeclRefType.addConst();
18723  }
18724 
18725  // Add the capture.
18726  if (BuildAndDiagnose)
18727  LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18728  Loc, EllipsisLoc, CaptureType, Invalid);
18729 
18730  return !Invalid;
18731 }
18732 
18734  const ASTContext &Context) {
18735  // Offer a Copy fix even if the type is dependent.
18736  if (Var->getType()->isDependentType())
18737  return true;
18739  if (T.isTriviallyCopyableType(Context))
18740  return true;
18741  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18742 
18743  if (!(RD = RD->getDefinition()))
18744  return false;
18745  if (RD->hasSimpleCopyConstructor())
18746  return true;
18747  if (RD->hasUserDeclaredCopyConstructor())
18748  for (CXXConstructorDecl *Ctor : RD->ctors())
18749  if (Ctor->isCopyConstructor())
18750  return !Ctor->isDeleted();
18751  }
18752  return false;
18753 }
18754 
18755 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18756 /// default capture. Fixes may be omitted if they aren't allowed by the
18757 /// standard, for example we can't emit a default copy capture fix-it if we
18758 /// already explicitly copy capture capture another variable.
18760  ValueDecl *Var) {
18762  // Don't offer Capture by copy of default capture by copy fixes if Var is
18763  // known not to be copy constructible.
18764  bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18765 
18766  SmallString<32> FixBuffer;
18767  StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18768  if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18769  SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18770  if (ShouldOfferCopyFix) {
18771  // Offer fixes to insert an explicit capture for the variable.
18772  // [] -> [VarName]
18773  // [OtherCapture] -> [OtherCapture, VarName]
18774  FixBuffer.assign({Separator, Var->getName()});
18775  Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18776  << Var << /*value*/ 0
18777  << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18778  }
18779  // As above but capture by reference.
18780  FixBuffer.assign({Separator, "&", Var->getName()});
18781  Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18782  << Var << /*reference*/ 1
18783  << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18784  }
18785 
18786  // Only try to offer default capture if there are no captures excluding this
18787  // and init captures.
18788  // [this]: OK.
18789  // [X = Y]: OK.
18790  // [&A, &B]: Don't offer.
18791  // [A, B]: Don't offer.
18792  if (llvm::any_of(LSI->Captures, [](Capture &C) {
18793  return !C.isThisCapture() && !C.isInitCapture();
18794  }))
18795  return;
18796 
18797  // The default capture specifiers, '=' or '&', must appear first in the
18798  // capture body.
18799  SourceLocation DefaultInsertLoc =
18801 
18802  if (ShouldOfferCopyFix) {
18803  bool CanDefaultCopyCapture = true;
18804  // [=, *this] OK since c++17
18805  // [=, this] OK since c++20
18806  if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18807  CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18808  ? LSI->getCXXThisCapture().isCopyCapture()
18809  : false;
18810  // We can't use default capture by copy if any captures already specified
18811  // capture by copy.
18812  if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18813  return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18814  })) {
18815  FixBuffer.assign({"=", Separator});
18816  Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18817  << /*value*/ 0
18818  << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18819  }
18820  }
18821 
18822  // We can't use default capture by reference if any captures already specified
18823  // capture by reference.
18824  if (llvm::none_of(LSI->Captures, [](Capture &C) {
18825  return !C.isInitCapture() && C.isReferenceCapture() &&
18826  !C.isThisCapture();
18827  })) {
18828  FixBuffer.assign({"&", Separator});
18829  Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18830  << /*reference*/ 1
18831  << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18832  }
18833 }
18834 
18837  SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18838  QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18839  // An init-capture is notionally from the context surrounding its
18840  // declaration, but its parent DC is the lambda class.
18841  DeclContext *VarDC = Var->getDeclContext();
18842  DeclContext *DC = CurContext;
18843 
18844  // tryCaptureVariable is called every time a DeclRef is formed,
18845  // it can therefore have non-negigible impact on performances.
18846  // For local variables and when there is no capturing scope,
18847  // we can bailout early.
18848  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18849  return true;
18850 
18851  const auto *VD = dyn_cast<VarDecl>(Var);
18852  if (VD) {
18853  if (VD->isInitCapture())
18854  VarDC = VarDC->getParent();
18855  } else {
18856  VD = Var->getPotentiallyDecomposedVarDecl();
18857  }
18858  assert(VD && "Cannot capture a null variable");
18859 
18860  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18861  ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18862  // We need to sync up the Declaration Context with the
18863  // FunctionScopeIndexToStopAt
18864  if (FunctionScopeIndexToStopAt) {
18865  unsigned FSIndex = FunctionScopes.size() - 1;
18866  while (FSIndex != MaxFunctionScopesIndex) {
18868  --FSIndex;
18869  }
18870  }
18871 
18872  // Capture global variables if it is required to use private copy of this
18873  // variable.
18874  bool IsGlobal = !VD->hasLocalStorage();
18875  if (IsGlobal && !(LangOpts.OpenMP &&
18876  OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18877  MaxFunctionScopesIndex)))
18878  return true;
18879 
18880  if (isa<VarDecl>(Var))
18881  Var = cast<VarDecl>(Var->getCanonicalDecl());
18882 
18883  // Walk up the stack to determine whether we can capture the variable,
18884  // performing the "simple" checks that don't depend on type. We stop when
18885  // we've either hit the declared scope of the variable or find an existing
18886  // capture of that variable. We start from the innermost capturing-entity
18887  // (the DC) and ensure that all intervening capturing-entities
18888  // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18889  // declcontext can either capture the variable or have already captured
18890  // the variable.
18891  CaptureType = Var->getType();
18892  DeclRefType = CaptureType.getNonReferenceType();
18893  bool Nested = false;
18894  bool Explicit = (Kind != TryCapture_Implicit);
18895  unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18896  do {
18897 
18898  LambdaScopeInfo *LSI = nullptr;
18899  if (!FunctionScopes.empty())
18900  LSI = dyn_cast_or_null<LambdaScopeInfo>(
18901  FunctionScopes[FunctionScopesIndex]);
18902 
18903  bool IsInScopeDeclarationContext =
18904  !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
18905 
18906  if (LSI && !LSI->AfterParameterList) {
18907  // This allows capturing parameters from a default value which does not
18908  // seems correct
18909  if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18910  return true;
18911  }
18912  // If the variable is declared in the current context, there is no need to
18913  // capture it.
18914  if (IsInScopeDeclarationContext &&
18915  FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18916  return true;
18917 
18918  // Only block literals, captured statements, and lambda expressions can
18919  // capture; other scopes don't work.
18920  DeclContext *ParentDC =
18921  !IsInScopeDeclarationContext
18922  ? DC->getParent()
18923  : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18924  BuildAndDiagnose, *this);
18925  // We need to check for the parent *first* because, if we *have*
18926  // private-captured a global variable, we need to recursively capture it in
18927  // intermediate blocks, lambdas, etc.
18928  if (!ParentDC) {
18929  if (IsGlobal) {
18930  FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18931  break;
18932  }
18933  return true;
18934  }
18935 
18936  FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18937  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18938 
18939  // Check whether we've already captured it.
18940  if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18941  DeclRefType)) {
18942  CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18943  break;
18944  }
18945 
18946  // When evaluating some attributes (like enable_if) we might refer to a
18947  // function parameter appertaining to the same declaration as that
18948  // attribute.
18949  if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
18950  Parm && Parm->getDeclContext() == DC)
18951  return true;
18952 
18953  // If we are instantiating a generic lambda call operator body,
18954  // we do not want to capture new variables. What was captured
18955  // during either a lambdas transformation or initial parsing
18956  // should be used.
18958  if (BuildAndDiagnose) {
18959  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18961  Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18962  Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18963  Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18964  buildLambdaCaptureFixit(*this, LSI, Var);
18965  } else
18966  diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
18967  }
18968  return true;
18969  }
18970 
18971  // Try to capture variable-length arrays types.
18972  if (Var->getType()->isVariablyModifiedType()) {
18973  // We're going to walk down into the type and look for VLA
18974  // expressions.
18975  QualType QTy = Var->getType();
18976  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18977  QTy = PVD->getOriginalType();
18978  captureVariablyModifiedType(Context, QTy, CSI);
18979  }
18980 
18981  if (getLangOpts().OpenMP) {
18982  if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18983  // OpenMP private variables should not be captured in outer scope, so
18984  // just break here. Similarly, global variables that are captured in a
18985  // target region should not be captured outside the scope of the region.
18986  if (RSI->CapRegionKind == CR_OpenMP) {
18987  // FIXME: We should support capturing structured bindings in OpenMP.
18988  if (isa<BindingDecl>(Var)) {
18989  if (BuildAndDiagnose) {
18990  Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
18991  Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18992  }
18993  return true;
18994  }
18995  OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
18996  Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18997  // If the variable is private (i.e. not captured) and has variably
18998  // modified type, we still need to capture the type for correct
18999  // codegen in all regions, associated with the construct. Currently,
19000  // it is captured in the innermost captured region only.
19001  if (IsOpenMPPrivateDecl != OMPC_unknown &&
19002  Var->getType()->isVariablyModifiedType()) {
19003  QualType QTy = Var->getType();
19004  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19005  QTy = PVD->getOriginalType();
19006  for (int I = 1,
19007  E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19008  I < E; ++I) {
19009  auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19010  FunctionScopes[FunctionScopesIndex - I]);
19011  assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19012  "Wrong number of captured regions associated with the "
19013  "OpenMP construct.");
19014  captureVariablyModifiedType(Context, QTy, OuterRSI);
19015  }
19016  }
19017  bool IsTargetCap =
19018  IsOpenMPPrivateDecl != OMPC_private &&
19019  OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19020  RSI->OpenMPCaptureLevel);
19021  // Do not capture global if it is not privatized in outer regions.
19022  bool IsGlobalCap =
19023  IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19024  Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19025 
19026  // When we detect target captures we are looking from inside the
19027  // target region, therefore we need to propagate the capture from the
19028  // enclosing region. Therefore, the capture is not initially nested.
19029  if (IsTargetCap)
19030  OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19031  RSI->OpenMPLevel);
19032 
19033  if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19034  (IsGlobal && !IsGlobalCap)) {
19035  Nested = !IsTargetCap;
19036  bool HasConst = DeclRefType.isConstQualified();
19037  DeclRefType = DeclRefType.getUnqualifiedType();
19038  // Don't lose diagnostics about assignments to const.
19039  if (HasConst)
19040  DeclRefType.addConst();
19041  CaptureType = Context.getLValueReferenceType(DeclRefType);
19042  break;
19043  }
19044  }
19045  }
19046  }
19047  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19048  // No capture-default, and this is not an explicit capture
19049  // so cannot capture this variable.
19050  if (BuildAndDiagnose) {
19051  Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19052  Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19053  auto *LSI = cast<LambdaScopeInfo>(CSI);
19054  if (LSI->Lambda) {
19055  Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19056  buildLambdaCaptureFixit(*this, LSI, Var);
19057  }
19058  // FIXME: If we error out because an outer lambda can not implicitly
19059  // capture a variable that an inner lambda explicitly captures, we
19060  // should have the inner lambda do the explicit capture - because
19061  // it makes for cleaner diagnostics later. This would purely be done
19062  // so that the diagnostic does not misleadingly claim that a variable
19063  // can not be captured by a lambda implicitly even though it is captured
19064  // explicitly. Suggestion:
19065  // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19066  // at the function head
19067  // - cache the StartingDeclContext - this must be a lambda
19068  // - captureInLambda in the innermost lambda the variable.
19069  }
19070  return true;
19071  }
19072  Explicit = false;
19073  FunctionScopesIndex--;
19074  if (IsInScopeDeclarationContext)
19075  DC = ParentDC;
19076  } while (!VarDC->Equals(DC));
19077 
19078  // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19079  // computing the type of the capture at each step, checking type-specific
19080  // requirements, and adding captures if requested.
19081  // If the variable had already been captured previously, we start capturing
19082  // at the lambda nested within that one.
19083  bool Invalid = false;
19084  for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19085  ++I) {
19086  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19087 
19088  // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19089  // certain types of variables (unnamed, variably modified types etc.)
19090  // so check for eligibility.
19091  if (!Invalid)
19092  Invalid =
19093  !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19094 
19095  // After encountering an error, if we're actually supposed to capture, keep
19096  // capturing in nested contexts to suppress any follow-on diagnostics.
19097  if (Invalid && !BuildAndDiagnose)
19098  return true;
19099 
19100  if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19101  Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19102  DeclRefType, Nested, *this, Invalid);
19103  Nested = true;
19104  } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19105  Invalid = !captureInCapturedRegion(
19106  RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19107  Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19108  Nested = true;
19109  } else {
19110  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19111  Invalid =
19112  !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19113  DeclRefType, Nested, Kind, EllipsisLoc,
19114  /*IsTopScope*/ I == N - 1, *this, Invalid);
19115  Nested = true;
19116  }
19117 
19118  if (Invalid && !BuildAndDiagnose)
19119  return true;
19120  }
19121  return Invalid;
19122 }
19123 
19125  TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19126  QualType CaptureType;
19127  QualType DeclRefType;
19128  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19129  /*BuildAndDiagnose=*/true, CaptureType,
19130  DeclRefType, nullptr);
19131 }
19132 
19134  QualType CaptureType;
19135  QualType DeclRefType;
19136  return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19137  /*BuildAndDiagnose=*/false, CaptureType,
19138  DeclRefType, nullptr);
19139 }
19140 
19142  QualType CaptureType;
19143  QualType DeclRefType;
19144 
19145  // Determine whether we can capture this variable.
19146  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19147  /*BuildAndDiagnose=*/false, CaptureType,
19148  DeclRefType, nullptr))
19149  return QualType();
19150 
19151  return DeclRefType;
19152 }
19153 
19154 namespace {
19155 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19156 // The produced TemplateArgumentListInfo* points to data stored within this
19157 // object, so should only be used in contexts where the pointer will not be
19158 // used after the CopiedTemplateArgs object is destroyed.
19159 class CopiedTemplateArgs {
19160  bool HasArgs;
19161  TemplateArgumentListInfo TemplateArgStorage;
19162 public:
19163  template<typename RefExpr>
19164  CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19165  if (HasArgs)
19166  E->copyTemplateArgumentsInto(TemplateArgStorage);
19167  }
19168  operator TemplateArgumentListInfo*()
19169 #ifdef __has_cpp_attribute
19170 #if __has_cpp_attribute(clang::lifetimebound)
19171  [[clang::lifetimebound]]
19172 #endif
19173 #endif
19174  {
19175  return HasArgs ? &TemplateArgStorage : nullptr;
19176  }
19177 };
19178 }
19179 
19180 /// Walk the set of potential results of an expression and mark them all as
19181 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19182 ///
19183 /// \return A new expression if we found any potential results, ExprEmpty() if
19184 /// not, and ExprError() if we diagnosed an error.
19186  NonOdrUseReason NOUR) {
19187  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19188  // an object that satisfies the requirements for appearing in a
19189  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19190  // is immediately applied." This function handles the lvalue-to-rvalue
19191  // conversion part.
19192  //
19193  // If we encounter a node that claims to be an odr-use but shouldn't be, we
19194  // transform it into the relevant kind of non-odr-use node and rebuild the
19195  // tree of nodes leading to it.
19196  //
19197  // This is a mini-TreeTransform that only transforms a restricted subset of
19198  // nodes (and only certain operands of them).
19199 
19200  // Rebuild a subexpression.
19201  auto Rebuild = [&](Expr *Sub) {
19202  return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19203  };
19204 
19205  // Check whether a potential result satisfies the requirements of NOUR.
19206  auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19207  // Any entity other than a VarDecl is always odr-used whenever it's named
19208  // in a potentially-evaluated expression.
19209  auto *VD = dyn_cast<VarDecl>(D);
19210  if (!VD)
19211  return true;
19212 
19213  // C++2a [basic.def.odr]p4:
19214  // A variable x whose name appears as a potentially-evalauted expression
19215  // e is odr-used by e unless
19216  // -- x is a reference that is usable in constant expressions, or
19217  // -- x is a variable of non-reference type that is usable in constant
19218  // expressions and has no mutable subobjects, and e is an element of
19219  // the set of potential results of an expression of
19220  // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19221  // conversion is applied, or
19222  // -- x is a variable of non-reference type, and e is an element of the
19223  // set of potential results of a discarded-value expression to which
19224  // the lvalue-to-rvalue conversion is not applied
19225  //
19226  // We check the first bullet and the "potentially-evaluated" condition in
19227  // BuildDeclRefExpr. We check the type requirements in the second bullet
19228  // in CheckLValueToRValueConversionOperand below.
19229  switch (NOUR) {
19230  case NOUR_None:
19231  case NOUR_Unevaluated:
19232  llvm_unreachable("unexpected non-odr-use-reason");
19233 
19234  case NOUR_Constant:
19235  // Constant references were handled when they were built.
19236  if (VD->getType()->isReferenceType())
19237  return true;
19238  if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19239  if (RD->hasMutableFields())
19240  return true;
19241  if (!VD->isUsableInConstantExpressions(S.Context))
19242  return true;
19243  break;
19244 
19245  case NOUR_Discarded:
19246  if (VD->getType()->isReferenceType())
19247  return true;
19248  break;
19249  }
19250  return false;
19251  };
19252 
19253  // Mark that this expression does not constitute an odr-use.
19254  auto MarkNotOdrUsed = [&] {
19255  S.MaybeODRUseExprs.remove(E);
19256  if (LambdaScopeInfo *LSI = S.getCurLambda())
19257  LSI->markVariableExprAsNonODRUsed(E);
19258  };
19259 
19260  // C++2a [basic.def.odr]p2:
19261  // The set of potential results of an expression e is defined as follows:
19262  switch (E->getStmtClass()) {
19263  // -- If e is an id-expression, ...
19264  case Expr::DeclRefExprClass: {
19265  auto *DRE = cast<DeclRefExpr>(E);
19266  if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19267  break;
19268 
19269  // Rebuild as a non-odr-use DeclRefExpr.
19270  MarkNotOdrUsed();
19271  return DeclRefExpr::Create(
19272  S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19273  DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19274  DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19275  DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19276  }
19277 
19278  case Expr::FunctionParmPackExprClass: {
19279  auto *FPPE = cast<FunctionParmPackExpr>(E);
19280  // If any of the declarations in the pack is odr-used, then the expression
19281  // as a whole constitutes an odr-use.
19282  for (VarDecl *D : *FPPE)
19283  if (IsPotentialResultOdrUsed(D))
19284  return ExprEmpty();
19285 
19286  // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19287  // nothing cares about whether we marked this as an odr-use, but it might
19288  // be useful for non-compiler tools.
19289  MarkNotOdrUsed();
19290  break;
19291  }
19292 
19293  // -- If e is a subscripting operation with an array operand...
19294  case Expr::ArraySubscriptExprClass: {
19295  auto *ASE = cast<ArraySubscriptExpr>(E);
19296  Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19297  if (!OldBase->getType()->isArrayType())
19298  break;
19299  ExprResult Base = Rebuild(OldBase);
19300  if (!Base.isUsable())
19301  return Base;
19302  Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19303  Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19304  SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19305  return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19306  ASE->getRBracketLoc());
19307  }
19308 
19309  case Expr::MemberExprClass: {
19310  auto *ME = cast<MemberExpr>(E);
19311  // -- If e is a class member access expression [...] naming a non-static
19312  // data member...
19313  if (isa<FieldDecl>(ME->getMemberDecl())) {
19314  ExprResult Base = Rebuild(ME->getBase());
19315  if (!Base.isUsable())
19316  return Base;
19317  return MemberExpr::Create(
19318  S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19319  ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19320  ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19321  CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19322  ME->getObjectKind(), ME->isNonOdrUse());
19323  }
19324 
19325  if (ME->getMemberDecl()->isCXXInstanceMember())
19326  break;
19327 
19328  // -- If e is a class member access expression naming a static data member,
19329  // ...
19330  if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19331  break;
19332 
19333  // Rebuild as a non-odr-use MemberExpr.
19334  MarkNotOdrUsed();
19335  return MemberExpr::Create(
19336  S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19337  ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19338  ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19339  ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19340  }
19341 
19342  case Expr::BinaryOperatorClass: {
19343  auto *BO = cast<BinaryOperator>(E);
19344  Expr *LHS = BO->getLHS();
19345  Expr *RHS = BO->getRHS();
19346  // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19347  if (BO->getOpcode() == BO_PtrMemD) {
19348  ExprResult Sub = Rebuild(LHS);
19349  if (!Sub.isUsable())
19350  return Sub;
19351  BO->setLHS(Sub.get());
19352  // -- If e is a comma expression, ...
19353  } else if (BO->getOpcode() == BO_Comma) {
19354  ExprResult Sub = Rebuild(RHS);
19355  if (!Sub.isUsable())
19356  return Sub;
19357  BO->setRHS(Sub.get());
19358  } else {
19359  break;
19360  }
19361  return ExprResult(BO);
19362  }
19363 
19364  // -- If e has the form (e1)...
19365  case Expr::ParenExprClass: {
19366  auto *PE = cast<ParenExpr>(E);
19367  ExprResult Sub = Rebuild(PE->getSubExpr());
19368  if (!Sub.isUsable())
19369  return Sub;
19370  return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19371  }
19372 
19373  // -- If e is a glvalue conditional expression, ...
19374  // We don't apply this to a binary conditional operator. FIXME: Should we?
19375  case Expr::ConditionalOperatorClass: {
19376  auto *CO = cast<ConditionalOperator>(E);
19377  ExprResult LHS = Rebuild(CO->getLHS());
19378  if (LHS.isInvalid())
19379  return ExprError();
19380  ExprResult RHS = Rebuild(CO->getRHS());
19381  if (RHS.isInvalid())
19382  return ExprError();
19383  if (!LHS.isUsable() && !RHS.isUsable())
19384  return ExprEmpty();
19385  if (!LHS.isUsable())
19386  LHS = CO->getLHS();
19387  if (!RHS.isUsable())
19388  RHS = CO->getRHS();
19389  return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19390  CO->getCond(), LHS.get(), RHS.get());
19391  }
19392 
19393  // [Clang extension]
19394  // -- If e has the form __extension__ e1...
19395  case Expr::UnaryOperatorClass: {
19396  auto *UO = cast<UnaryOperator>(E);
19397  if (UO->getOpcode() != UO_Extension)
19398  break;
19399  ExprResult Sub = Rebuild(UO->getSubExpr());
19400  if (!Sub.isUsable())
19401  return Sub;
19402  return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19403  Sub.get());
19404  }
19405 
19406  // [Clang extension]
19407  // -- If e has the form _Generic(...), the set of potential results is the
19408  // union of the sets of potential results of the associated expressions.
19409  case Expr::GenericSelectionExprClass: {
19410  auto *GSE = cast<GenericSelectionExpr>(E);
19411 
19412  SmallVector<Expr *, 4> AssocExprs;
19413  bool AnyChanged = false;
19414  for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19415  ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19416  if (AssocExpr.isInvalid())
19417  return ExprError();
19418  if (AssocExpr.isUsable()) {
19419  AssocExprs.push_back(AssocExpr.get());
19420  AnyChanged = true;
19421  } else {
19422  AssocExprs.push_back(OrigAssocExpr);
19423  }
19424  }
19425 
19426  void *ExOrTy = nullptr;
19427  bool IsExpr = GSE->isExprPredicate();
19428  if (IsExpr)
19429  ExOrTy = GSE->getControllingExpr();
19430  else
19431  ExOrTy = GSE->getControllingType();
19432  return AnyChanged ? S.CreateGenericSelectionExpr(
19433  GSE->getGenericLoc(), GSE->getDefaultLoc(),
19434  GSE->getRParenLoc(), IsExpr, ExOrTy,
19435  GSE->getAssocTypeSourceInfos(), AssocExprs)
19436  : ExprEmpty();
19437  }
19438 
19439  // [Clang extension]
19440  // -- If e has the form __builtin_choose_expr(...), the set of potential
19441  // results is the union of the sets of potential results of the
19442  // second and third subexpressions.
19443  case Expr::ChooseExprClass: {
19444  auto *CE = cast<ChooseExpr>(E);
19445 
19446  ExprResult LHS = Rebuild(CE->getLHS());
19447  if (LHS.isInvalid())
19448  return ExprError();
19449 
19450  ExprResult RHS = Rebuild(CE->getLHS());
19451  if (RHS.isInvalid())
19452  return ExprError();
19453 
19454  if (!LHS.get() && !RHS.get())
19455  return ExprEmpty();
19456  if (!LHS.isUsable())
19457  LHS = CE->getLHS();
19458  if (!RHS.isUsable())
19459  RHS = CE->getRHS();
19460 
19461  return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19462  RHS.get(), CE->getRParenLoc());
19463  }
19464 
19465  // Step through non-syntactic nodes.
19466  case Expr::ConstantExprClass: {
19467  auto *CE = cast<ConstantExpr>(E);
19468  ExprResult Sub = Rebuild(CE->getSubExpr());
19469  if (!Sub.isUsable())
19470  return Sub;
19471  return ConstantExpr::Create(S.Context, Sub.get());
19472  }
19473 
19474  // We could mostly rely on the recursive rebuilding to rebuild implicit
19475  // casts, but not at the top level, so rebuild them here.
19476  case Expr::ImplicitCastExprClass: {
19477  auto *ICE = cast<ImplicitCastExpr>(E);
19478  // Only step through the narrow set of cast kinds we expect to encounter.
19479  // Anything else suggests we've left the region in which potential results
19480  // can be found.
19481  switch (ICE->getCastKind()) {
19482  case CK_NoOp:
19483  case CK_DerivedToBase:
19484  case CK_UncheckedDerivedToBase: {
19485  ExprResult Sub = Rebuild(ICE->getSubExpr());
19486  if (!Sub.isUsable())
19487  return Sub;
19488  CXXCastPath Path(ICE->path());
19489  return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19490  ICE->getValueKind(), &Path);
19491  }
19492 
19493  default:
19494  break;
19495  }
19496  break;
19497  }
19498 
19499  default:
19500  break;
19501  }
19502 
19503  // Can't traverse through this node. Nothing to do.
19504  return ExprEmpty();
19505 }
19506 
19508  // Check whether the operand is or contains an object of non-trivial C union
19509  // type.
19510  if (E->getType().isVolatileQualified() &&
19513  checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19515  NTCUK_Destruct|NTCUK_Copy);
19516 
19517  // C++2a [basic.def.odr]p4:
19518  // [...] an expression of non-volatile-qualified non-class type to which
19519  // the lvalue-to-rvalue conversion is applied [...]
19520  if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19521  return E;
19522 
19523  ExprResult Result =
19525  if (Result.isInvalid())
19526  return ExprError();
19527  return Result.get() ? Result : E;
19528 }
19529 
19531  Res = CorrectDelayedTyposInExpr(Res);
19532 
19533  if (!Res.isUsable())
19534  return Res;
19535 
19536  // If a constant-expression is a reference to a variable where we delay
19537  // deciding whether it is an odr-use, just assume we will apply the
19538  // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19539  // (a non-type template argument), we have special handling anyway.
19540  return CheckLValueToRValueConversionOperand(Res.get());
19541 }
19542 
19544  // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19545  // call.
19546  MaybeODRUseExprSet LocalMaybeODRUseExprs;
19547  std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19548 
19549  for (Expr *E : LocalMaybeODRUseExprs) {
19550  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19551  MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19552  DRE->getLocation(), *this);
19553  } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19554  MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19555  *this);
19556  } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19557  for (VarDecl *VD : *FP)
19558  MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19559  } else {
19560  llvm_unreachable("Unexpected expression");
19561  }
19562  }
19563 
19564  assert(MaybeODRUseExprs.empty() &&
19565  "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19566 }
19567 
19569  ValueDecl *Var, Expr *E) {
19571  if (!VD)
19572  return;
19573 
19574  const bool RefersToEnclosingScope =
19575  (SemaRef.CurContext != VD->getDeclContext() &&
19577  if (RefersToEnclosingScope) {
19578  LambdaScopeInfo *const LSI =
19579  SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19580  if (LSI && (!LSI->CallOperator ||
19581  !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19582  // If a variable could potentially be odr-used, defer marking it so
19583  // until we finish analyzing the full expression for any
19584  // lvalue-to-rvalue
19585  // or discarded value conversions that would obviate odr-use.
19586  // Add it to the list of potential captures that will be analyzed
19587  // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19588  // unless the variable is a reference that was initialized by a constant
19589  // expression (this will never need to be captured or odr-used).
19590  //
19591  // FIXME: We can simplify this a lot after implementing P0588R1.
19592  assert(E && "Capture variable should be used in an expression.");
19593  if (!Var->getType()->isReferenceType() ||
19594  !VD->isUsableInConstantExpressions(SemaRef.Context))
19595  LSI->addPotentialCapture(E->IgnoreParens());
19596  }
19597  }
19598 }
19599 
19601  Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19602  llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19603  assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19604  isa<FunctionParmPackExpr>(E)) &&
19605  "Invalid Expr argument to DoMarkVarDeclReferenced");
19606  Var->setReferenced();
19607 
19608  if (Var->isInvalidDecl())
19609  return;
19610 
19611  auto *MSI = Var->getMemberSpecializationInfo();
19614 
19615  OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19616  bool UsableInConstantExpr =
19618 
19619  if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19620  RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19621  }
19622 
19623  // C++20 [expr.const]p12:
19624  // A variable [...] is needed for constant evaluation if it is [...] a
19625  // variable whose name appears as a potentially constant evaluated
19626  // expression that is either a contexpr variable or is of non-volatile
19627  // const-qualified integral type or of reference type
19628  bool NeededForConstantEvaluation =
19629  isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19630 
19631  bool NeedDefinition =
19632  OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19633 
19634  assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19635  "Can't instantiate a partial template specialization.");
19636 
19637  // If this might be a member specialization of a static data member, check
19638  // the specialization is visible. We already did the checks for variable
19639  // template specializations when we created them.
19640  if (NeedDefinition && TSK != TSK_Undeclared &&
19641  !isa<VarTemplateSpecializationDecl>(Var))
19642  SemaRef.checkSpecializationVisibility(Loc, Var);
19643 
19644  // Perform implicit instantiation of static data members, static data member
19645  // templates of class templates, and variable template specializations. Delay
19646  // instantiations of variable templates, except for those that could be used
19647  // in a constant expression.
19648  if (NeedDefinition && isTemplateInstantiation(TSK)) {
19649  // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19650  // instantiation declaration if a variable is usable in a constant
19651  // expression (among other cases).
19652  bool TryInstantiating =
19653  TSK == TSK_ImplicitInstantiation ||
19654  (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19655 
19656  if (TryInstantiating) {
19657  SourceLocation PointOfInstantiation =
19658  MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19659  bool FirstInstantiation = PointOfInstantiation.isInvalid();
19660  if (FirstInstantiation) {
19661  PointOfInstantiation = Loc;
19662  if (MSI)
19663  MSI->setPointOfInstantiation(PointOfInstantiation);
19664  // FIXME: Notify listener.
19665  else
19666  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19667  }
19668 
19669  if (UsableInConstantExpr) {
19670  // Do not defer instantiations of variables that could be used in a
19671  // constant expression.
19672  SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19673  SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19674  });
19675 
19676  // Re-set the member to trigger a recomputation of the dependence bits
19677  // for the expression.
19678  if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19679  DRE->setDecl(DRE->getDecl());
19680  else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19681  ME->setMemberDecl(ME->getMemberDecl());
19682  } else if (FirstInstantiation) {
19683  SemaRef.PendingInstantiations
19684  .push_back(std::make_pair(Var, PointOfInstantiation));
19685  } else {
19686  bool Inserted = false;
19687  for (auto &I : SemaRef.SavedPendingInstantiations) {
19688  auto Iter = llvm::find_if(
19689  I, [Var](const Sema::PendingImplicitInstantiation &P) {
19690  return P.first == Var;
19691  });
19692  if (Iter != I.end()) {
19693  SemaRef.PendingInstantiations.push_back(*Iter);
19694  I.erase(Iter);
19695  Inserted = true;
19696  break;
19697  }
19698  }
19699 
19700  // FIXME: For a specialization of a variable template, we don't
19701  // distinguish between "declaration and type implicitly instantiated"
19702  // and "implicit instantiation of definition requested", so we have
19703  // no direct way to avoid enqueueing the pending instantiation
19704  // multiple times.
19705  if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19706  SemaRef.PendingInstantiations
19707  .push_back(std::make_pair(Var, PointOfInstantiation));
19708  }
19709  }
19710  }
19711 
19712  // C++2a [basic.def.odr]p4:
19713  // A variable x whose name appears as a potentially-evaluated expression e
19714  // is odr-used by e unless
19715  // -- x is a reference that is usable in constant expressions
19716  // -- x is a variable of non-reference type that is usable in constant
19717  // expressions and has no mutable subobjects [FIXME], and e is an
19718  // element of the set of potential results of an expression of
19719  // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19720  // conversion is applied
19721  // -- x is a variable of non-reference type, and e is an element of the set
19722  // of potential results of a discarded-value expression to which the
19723  // lvalue-to-rvalue conversion is not applied [FIXME]
19724  //
19725  // We check the first part of the second bullet here, and
19726  // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19727  // FIXME: To get the third bullet right, we need to delay this even for
19728  // variables that are not usable in constant expressions.
19729 
19730  // If we already know this isn't an odr-use, there's nothing more to do.
19731  if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19732  if (DRE->isNonOdrUse())
19733  return;
19734  if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19735  if (ME->isNonOdrUse())
19736  return;
19737 
19738  switch (OdrUse) {
19739  case OdrUseContext::None:
19740  // In some cases, a variable may not have been marked unevaluated, if it
19741  // appears in a defaukt initializer.
19742  assert((!E || isa<FunctionParmPackExpr>(E) ||
19743  SemaRef.isUnevaluatedContext()) &&
19744  "missing non-odr-use marking for unevaluated decl ref");
19745  break;
19746 
19747  case OdrUseContext::FormallyOdrUsed:
19748  // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19749  // behavior.
19750  break;
19751 
19752  case OdrUseContext::Used:
19753  // If we might later find that this expression isn't actually an odr-use,
19754  // delay the marking.
19755  if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19756  SemaRef.MaybeODRUseExprs.insert(E);
19757  else
19758  MarkVarDeclODRUsed(Var, Loc, SemaRef);
19759  break;
19760 
19761  case OdrUseContext::Dependent:
19762  // If this is a dependent context, we don't need to mark variables as
19763  // odr-used, but we may still need to track them for lambda capture.
19764  // FIXME: Do we also need to do this inside dependent typeid expressions
19765  // (which are modeled as unevaluated at this point)?
19766  DoMarkPotentialCapture(SemaRef, Loc, Var, E);
19767  break;
19768  }
19769 }
19770 
19772  BindingDecl *BD, Expr *E) {
19773  BD->setReferenced();
19774 
19775  if (BD->isInvalidDecl())
19776  return;
19777 
19778  OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19779  if (OdrUse == OdrUseContext::Used) {
19780  QualType CaptureType, DeclRefType;
19782  /*EllipsisLoc*/ SourceLocation(),
19783  /*BuildAndDiagnose*/ true, CaptureType,
19784  DeclRefType,
19785  /*FunctionScopeIndexToStopAt*/ nullptr);
19786  } else if (OdrUse == OdrUseContext::Dependent) {
19787  DoMarkPotentialCapture(SemaRef, Loc, BD, E);
19788  }
19789 }
19790 
19791 /// Mark a variable referenced, and check whether it is odr-used
19792 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19793 /// used directly for normal expressions referring to VarDecl.
19795  DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19796 }
19797 
19798 // C++ [temp.dep.expr]p3:
19799 // An id-expression is type-dependent if it contains:
19800 // - an identifier associated by name lookup with an entity captured by copy
19801 // in a lambda-expression that has an explicit object parameter whose type
19802 // is dependent ([dcl.fct]),
19804  Sema &SemaRef, ValueDecl *D, Expr *E) {
19805  auto *ID = dyn_cast<DeclRefExpr>(E);
19806  if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19807  return;
19808 
19809  // If any enclosing lambda with a dependent explicit object parameter either
19810  // explicitly captures the variable by value, or has a capture default of '='
19811  // and does not capture the variable by reference, then the type of the DRE
19812  // is dependent on the type of that lambda's explicit object parameter.
19813  auto IsDependent = [&]() {
19814  for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19815  auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19816  if (!LSI)
19817  continue;
19818 
19819  if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19820  LSI->AfterParameterList)
19821  return false;
19822 
19823  const auto *MD = LSI->CallOperator;
19824  if (MD->getType().isNull())
19825  continue;
19826 
19827  const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19828  if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19829  !Ty->getParamType(0)->isDependentType())
19830  continue;
19831 
19832  if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19833  if (C->isCopyCapture())
19834  return true;
19835  continue;
19836  }
19837 
19838  if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19839  return true;
19840  }
19841  return false;
19842  }();
19843 
19844  ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19845  IsDependent, SemaRef.getASTContext());
19846 }
19847 
19848 static void
19850  bool MightBeOdrUse,
19851  llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19852  if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
19853  SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
19854 
19855  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19856  DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19857  if (SemaRef.getLangOpts().CPlusPlus)
19859  Var, E);
19860  return;
19861  }
19862 
19863  if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19864  DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
19865  if (SemaRef.getLangOpts().CPlusPlus)
19867  Decl, E);
19868  return;
19869  }
19870  SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19871 
19872  // If this is a call to a method via a cast, also mark the method in the
19873  // derived class used in case codegen can devirtualize the call.
19874  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19875  if (!ME)
19876  return;
19877  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19878  if (!MD)
19879  return;
19880  // Only attempt to devirtualize if this is truly a virtual call.
19881  bool IsVirtualCall = MD->isVirtual() &&
19882  ME->performsVirtualDispatch(SemaRef.getLangOpts());
19883  if (!IsVirtualCall)
19884  return;
19885 
19886  // If it's possible to devirtualize the call, mark the called function
19887  // referenced.
19889  ME->getBase(), SemaRef.getLangOpts().AppleKext);
19890  if (DM)
19891  SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19892 }
19893 
19894 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19895 ///
19896 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19897 /// handled with care if the DeclRefExpr is not newly-created.
19899  // TODO: update this with DR# once a defect report is filed.
19900  // C++11 defect. The address of a pure member should not be an ODR use, even
19901  // if it's a qualified reference.
19902  bool OdrUse = true;
19903  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19904  if (Method->isVirtual() &&
19905  !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19906  OdrUse = false;
19907 
19908  if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
19909  if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
19910  !isImmediateFunctionContext() &&
19911  !isCheckingDefaultArgumentOrInitializer() &&
19912  FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
19913  !FD->isDependentContext())
19914  ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19915  }
19916  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19917  RefsMinusAssignments);
19918 }
19919 
19920 /// Perform reference-marking and odr-use handling for a MemberExpr.
19922  // C++11 [basic.def.odr]p2:
19923  // A non-overloaded function whose name appears as a potentially-evaluated
19924  // expression or a member of a set of candidate functions, if selected by
19925  // overload resolution when referred to from a potentially-evaluated
19926  // expression, is odr-used, unless it is a pure virtual function and its
19927  // name is not explicitly qualified.
19928  bool MightBeOdrUse = true;
19929  if (E->performsVirtualDispatch(getLangOpts())) {
19930  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19931  if (Method->isPureVirtual())
19932  MightBeOdrUse = false;
19933  }
19935  E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19936  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19937  RefsMinusAssignments);
19938 }
19939 
19940 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19942  for (VarDecl *VD : *E)
19943  MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19944  RefsMinusAssignments);
19945 }
19946 
19947 /// Perform marking for a reference to an arbitrary declaration. It
19948 /// marks the declaration referenced, and performs odr-use checking for
19949 /// functions and variables. This method should not be used when building a
19950 /// normal expression which refers to a variable.
19952  bool MightBeOdrUse) {
19953  if (MightBeOdrUse) {
19954  if (auto *VD = dyn_cast<VarDecl>(D)) {
19955  MarkVariableReferenced(Loc, VD);
19956  return;
19957  }
19958  }
19959  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19960  MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19961  return;
19962  }
19963  D->setReferenced();
19964 }
19965 
19966 namespace {
19967  // Mark all of the declarations used by a type as referenced.
19968  // FIXME: Not fully implemented yet! We need to have a better understanding
19969  // of when we're entering a context we should not recurse into.
19970  // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19971  // TreeTransforms rebuilding the type in a new context. Rather than
19972  // duplicating the TreeTransform logic, we should consider reusing it here.
19973  // Currently that causes problems when rebuilding LambdaExprs.
19974  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19975  Sema &S;
19977 
19978  public:
19979  typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19980 
19981  MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19982 
19983  bool TraverseTemplateArgument(const TemplateArgument &Arg);
19984  };
19985 }
19986 
19987 bool MarkReferencedDecls::TraverseTemplateArgument(
19988  const TemplateArgument &Arg) {
19989  {
19990  // A non-type template argument is a constant-evaluated context.
19993  if (Arg.getKind() == TemplateArgument::Declaration) {
19994  if (Decl *D = Arg.getAsDecl())
19995  S.MarkAnyDeclReferenced(Loc, D, true);
19996  } else if (Arg.getKind() == TemplateArgument::Expression) {
19998  }
19999  }
20000 
20001  return Inherited::TraverseTemplateArgument(Arg);
20002 }
20003 
20005  MarkReferencedDecls Marker(*this, Loc);
20006  Marker.TraverseType(T);
20007 }
20008 
20009 namespace {
20010 /// Helper class that marks all of the declarations referenced by
20011 /// potentially-evaluated subexpressions as "referenced".
20012 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20013 public:
20014  typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20015  bool SkipLocalVariables;
20016  ArrayRef<const Expr *> StopAt;
20017 
20018  EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20019  ArrayRef<const Expr *> StopAt)
20020  : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20021 
20022  void visitUsedDecl(SourceLocation Loc, Decl *D) {
20023  S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20024  }
20025 
20026  void Visit(Expr *E) {
20027  if (llvm::is_contained(StopAt, E))
20028  return;
20029  Inherited::Visit(E);
20030  }
20031 
20032  void VisitConstantExpr(ConstantExpr *E) {
20033  // Don't mark declarations within a ConstantExpression, as this expression
20034  // will be evaluated and folded to a value.
20035  }
20036 
20037  void VisitDeclRefExpr(DeclRefExpr *E) {
20038  // If we were asked not to visit local variables, don't.
20039  if (SkipLocalVariables) {
20040  if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20041  if (VD->hasLocalStorage())
20042  return;
20043  }
20044 
20045  // FIXME: This can trigger the instantiation of the initializer of a
20046  // variable, which can cause the expression to become value-dependent
20047  // or error-dependent. Do we need to propagate the new dependence bits?
20048  S.MarkDeclRefReferenced(E);
20049  }
20050 
20051  void VisitMemberExpr(MemberExpr *E) {
20052  S.MarkMemberReferenced(E);
20053  Visit(E->getBase());
20054  }
20055 };
20056 } // namespace
20057 
20058 /// Mark any declarations that appear within this expression or any
20059 /// potentially-evaluated subexpressions as "referenced".
20060 ///
20061 /// \param SkipLocalVariables If true, don't mark local variables as
20062 /// 'referenced'.
20063 /// \param StopAt Subexpressions that we shouldn't recurse into.
20065  bool SkipLocalVariables,
20066  ArrayRef<const Expr*> StopAt) {
20067  EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20068 }
20069 
20070 /// Emit a diagnostic when statements are reachable.
20071 /// FIXME: check for reachability even in expressions for which we don't build a
20072 /// CFG (eg, in the initializer of a global or in a constant expression).
20073 /// For example,
20074 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20076  const PartialDiagnostic &PD) {
20077  if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20078  if (!FunctionScopes.empty())
20079  FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20080  sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20081  return true;
20082  }
20083 
20084  // The initializer of a constexpr variable or of the first declaration of a
20085  // static data member is not syntactically a constant evaluated constant,
20086  // but nonetheless is always required to be a constant expression, so we
20087  // can skip diagnosing.
20088  // FIXME: Using the mangling context here is a hack.
20089  if (auto *VD = dyn_cast_or_null<VarDecl>(
20090  ExprEvalContexts.back().ManglingContextDecl)) {
20091  if (VD->isConstexpr() ||
20092  (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20093  return false;
20094  // FIXME: For any other kind of variable, we should build a CFG for its
20095  // initializer and check whether the context in question is reachable.
20096  }
20097 
20098  Diag(Loc, PD);
20099  return true;
20100 }
20101 
20102 /// Emit a diagnostic that describes an effect on the run-time behavior
20103 /// of the program being compiled.
20104 ///
20105 /// This routine emits the given diagnostic when the code currently being
20106 /// type-checked is "potentially evaluated", meaning that there is a
20107 /// possibility that the code will actually be executable. Code in sizeof()
20108 /// expressions, code used only during overload resolution, etc., are not
20109 /// potentially evaluated. This routine will suppress such diagnostics or,
20110 /// in the absolutely nutty case of potentially potentially evaluated
20111 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20112 /// later.
20113 ///
20114 /// This routine should be used for all diagnostics that describe the run-time
20115 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20116 /// Failure to do so will likely result in spurious diagnostics or failures
20117 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20119  const PartialDiagnostic &PD) {
20120 
20121  if (ExprEvalContexts.back().isDiscardedStatementContext())
20122  return false;
20123 
20124  switch (ExprEvalContexts.back().Context) {
20125  case ExpressionEvaluationContext::Unevaluated:
20126  case ExpressionEvaluationContext::UnevaluatedList:
20127  case ExpressionEvaluationContext::UnevaluatedAbstract:
20128  case ExpressionEvaluationContext::DiscardedStatement:
20129  // The argument will never be evaluated, so don't complain.
20130  break;
20131 
20132  case ExpressionEvaluationContext::ConstantEvaluated:
20133  case ExpressionEvaluationContext::ImmediateFunctionContext:
20134  // Relevant diagnostics should be produced by constant evaluation.
20135  break;
20136 
20137  case ExpressionEvaluationContext::PotentiallyEvaluated:
20138  case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20139  return DiagIfReachable(Loc, Stmts, PD);
20140  }
20141 
20142  return false;
20143 }
20144 
20146  const PartialDiagnostic &PD) {
20147  return DiagRuntimeBehavior(
20148  Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20149 }
20150 
20152  CallExpr *CE, FunctionDecl *FD) {
20153  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20154  return false;
20155 
20156  // If we're inside a decltype's expression, don't check for a valid return
20157  // type or construct temporaries until we know whether this is the last call.
20158  if (ExprEvalContexts.back().ExprContext ==
20159  ExpressionEvaluationContextRecord::EK_Decltype) {
20160  ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20161  return false;
20162  }
20163 
20164  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20165  FunctionDecl *FD;
20166  CallExpr *CE;
20167 
20168  public:
20169  CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20170  : FD(FD), CE(CE) { }
20171 
20172  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20173  if (!FD) {
20174  S.Diag(Loc, diag::err_call_incomplete_return)
20175  << T << CE->getSourceRange();
20176  return;
20177  }
20178 
20179  S.Diag(Loc, diag::err_call_function_incomplete_return)
20180  << CE->getSourceRange() << FD << T;
20181  S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20182  << FD->getDeclName();
20183  }
20184  } Diagnoser(FD, CE);
20185 
20186  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20187  return true;
20188 
20189  return false;
20190 }
20191 
20192 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20193 // will prevent this condition from triggering, which is what we want.
20196 
20197  unsigned diagnostic = diag::warn_condition_is_assignment;
20198  bool IsOrAssign = false;
20199 
20200  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20201  if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20202  return;
20203 
20204  IsOrAssign = Op->getOpcode() == BO_OrAssign;
20205 
20206  // Greylist some idioms by putting them into a warning subcategory.
20207  if (ObjCMessageExpr *ME
20208  = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20209  Selector Sel = ME->getSelector();
20210 
20211  // self = [<foo> init...]
20212  if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20213  diagnostic = diag::warn_condition_is_idiomatic_assignment;
20214 
20215  // <foo> = [<bar> nextObject]
20216  else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20217  diagnostic = diag::warn_condition_is_idiomatic_assignment;
20218  }
20219 
20220  Loc = Op->getOperatorLoc();
20221  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20222  if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20223  return;
20224 
20225  IsOrAssign = Op->getOperator() == OO_PipeEqual;
20226  Loc = Op->getOperatorLoc();
20227  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20228  return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20229  else {
20230  // Not an assignment.
20231  return;
20232  }
20233 
20234  Diag(Loc, diagnostic) << E->getSourceRange();
20235 
20236  SourceLocation Open = E->getBeginLoc();
20237  SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20238  Diag(Loc, diag::note_condition_assign_silence)
20239  << FixItHint::CreateInsertion(Open, "(")
20240  << FixItHint::CreateInsertion(Close, ")");
20241 
20242  if (IsOrAssign)
20243  Diag(Loc, diag::note_condition_or_assign_to_comparison)
20245  else
20246  Diag(Loc, diag::note_condition_assign_to_comparison)
20248 }
20249 
20250 /// Redundant parentheses over an equality comparison can indicate
20251 /// that the user intended an assignment used as condition.
20253  // Don't warn if the parens came from a macro.
20254  SourceLocation parenLoc = ParenE->getBeginLoc();
20255  if (parenLoc.isInvalid() || parenLoc.isMacroID())
20256  return;
20257  // Don't warn for dependent expressions.
20258  if (ParenE->isTypeDependent())
20259  return;
20260 
20261  Expr *E = ParenE->IgnoreParens();
20262 
20263  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20264  if (opE->getOpcode() == BO_EQ &&
20265  opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20266  == Expr::MLV_Valid) {
20267  SourceLocation Loc = opE->getOperatorLoc();
20268 
20269  Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20270  SourceRange ParenERange = ParenE->getSourceRange();
20271  Diag(Loc, diag::note_equality_comparison_silence)
20272  << FixItHint::CreateRemoval(ParenERange.getBegin())
20273  << FixItHint::CreateRemoval(ParenERange.getEnd());
20274  Diag(Loc, diag::note_equality_comparison_to_assign)
20276  }
20277 }
20278 
20280  bool IsConstexpr) {
20281  DiagnoseAssignmentAsCondition(E);
20282  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20283  DiagnoseEqualityWithExtraParens(parenE);
20284 
20285  ExprResult result = CheckPlaceholderExpr(E);
20286  if (result.isInvalid()) return ExprError();
20287  E = result.get();
20288 
20289  if (!E->isTypeDependent()) {
20290  if (getLangOpts().CPlusPlus)
20291  return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20292 
20293  ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20294  if (ERes.isInvalid())
20295  return ExprError();
20296  E = ERes.get();
20297 
20298  QualType T = E->getType();
20299  if (!T->isScalarType()) { // C99 6.8.4.1p1
20300  Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20301  << T << E->getSourceRange();
20302  return ExprError();
20303  }
20305  }
20306 
20307  return E;
20308 }
20309 
20311  Expr *SubExpr, ConditionKind CK,
20312  bool MissingOK) {
20313  // MissingOK indicates whether having no condition expression is valid
20314  // (for loop) or invalid (e.g. while loop).
20315  if (!SubExpr)
20316  return MissingOK ? ConditionResult() : ConditionError();
20317 
20318  ExprResult Cond;
20319  switch (CK) {
20321  Cond = CheckBooleanCondition(Loc, SubExpr);
20322  break;
20323 
20324  case ConditionKind::ConstexprIf:
20325  Cond = CheckBooleanCondition(Loc, SubExpr, true);
20326  break;
20327 
20328  case ConditionKind::Switch:
20329  Cond = CheckSwitchCondition(Loc, SubExpr);
20330  break;
20331  }
20332  if (Cond.isInvalid()) {
20333  Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20334  {SubExpr}, PreferredConditionType(CK));
20335  if (!Cond.get())
20336  return ConditionError();
20337  }
20338  // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20339  FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20340  if (!FullExpr.get())
20341  return ConditionError();
20342 
20343  return ConditionResult(*this, nullptr, FullExpr,
20344  CK == ConditionKind::ConstexprIf);
20345 }
20346 
20347 namespace {
20348  /// A visitor for rebuilding a call to an __unknown_any expression
20349  /// to have an appropriate type.
20350  struct RebuildUnknownAnyFunction
20351  : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20352 
20353  Sema &S;
20354 
20355  RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20356 
20357  ExprResult VisitStmt(Stmt *S) {
20358  llvm_unreachable("unexpected statement!");
20359  }
20360 
20361  ExprResult VisitExpr(Expr *E) {
20362  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20363  << E->getSourceRange();
20364  return ExprError();
20365  }
20366 
20367  /// Rebuild an expression which simply semantically wraps another
20368  /// expression which it shares the type and value kind of.
20369  template <class T> ExprResult rebuildSugarExpr(T *E) {
20370  ExprResult SubResult = Visit(E->getSubExpr());
20371  if (SubResult.isInvalid()) return ExprError();
20372 
20373  Expr *SubExpr = SubResult.get();
20374  E->setSubExpr(SubExpr);
20375  E->setType(SubExpr->getType());
20376  E->setValueKind(SubExpr->getValueKind());
20377  assert(E->getObjectKind() == OK_Ordinary);
20378  return E;
20379  }
20380 
20381  ExprResult VisitParenExpr(ParenExpr *E) {
20382  return rebuildSugarExpr(E);
20383  }
20384 
20385  ExprResult VisitUnaryExtension(UnaryOperator *E) {
20386  return rebuildSugarExpr(E);
20387  }
20388 
20389  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20390  ExprResult SubResult = Visit(E->getSubExpr());
20391  if (SubResult.isInvalid()) return ExprError();
20392 
20393  Expr *SubExpr = SubResult.get();
20394  E->setSubExpr(SubExpr);
20395  E->setType(S.Context.getPointerType(SubExpr->getType()));
20396  assert(E->isPRValue());
20397  assert(E->getObjectKind() == OK_Ordinary);
20398  return E;
20399  }
20400 
20401  ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20402  if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20403 
20404  E->setType(VD->getType());
20405 
20406  assert(E->isPRValue());
20407  if (S.getLangOpts().CPlusPlus &&
20408  !(isa<CXXMethodDecl>(VD) &&
20409  cast<CXXMethodDecl>(VD)->isInstance()))
20410  E->setValueKind(VK_LValue);
20411 
20412  return E;
20413  }
20414 
20415  ExprResult VisitMemberExpr(MemberExpr *E) {
20416  return resolveDecl(E, E->getMemberDecl());
20417  }
20418 
20419  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20420  return resolveDecl(E, E->getDecl());
20421  }
20422  };
20423 }
20424 
20425 /// Given a function expression of unknown-any type, try to rebuild it
20426 /// to have a function type.
20427 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20428  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20429  if (Result.isInvalid()) return ExprError();
20430  return S.DefaultFunctionArrayConversion(Result.get());
20431 }
20432 
20433 namespace {
20434  /// A visitor for rebuilding an expression of type __unknown_anytype
20435  /// into one which resolves the type directly on the referring
20436  /// expression. Strict preservation of the original source
20437  /// structure is not a goal.
20438  struct RebuildUnknownAnyExpr
20439  : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20440 
20441  Sema &S;
20442 
20443  /// The current destination type.
20444  QualType DestType;
20445 
20446  RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20447  : S(S), DestType(CastType) {}
20448 
20449  ExprResult VisitStmt(Stmt *S) {
20450  llvm_unreachable("unexpected statement!");
20451  }
20452 
20453  ExprResult VisitExpr(Expr *E) {
20454  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20455  << E->getSourceRange();
20456  return ExprError();
20457  }
20458 
20459  ExprResult VisitCallExpr(CallExpr *E);
20460  ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20461 
20462  /// Rebuild an expression which simply semantically wraps another
20463  /// expression which it shares the type and value kind of.
20464  template <class T> ExprResult rebuildSugarExpr(T *E) {
20465  ExprResult SubResult = Visit(E->getSubExpr());
20466  if (SubResult.isInvalid()) return ExprError();
20467  Expr *SubExpr = SubResult.get();
20468  E->setSubExpr(SubExpr);
20469  E->setType(SubExpr->getType());
20470  E->setValueKind(SubExpr->getValueKind());
20471  assert(E->getObjectKind() == OK_Ordinary);
20472  return E;
20473  }
20474 
20475  ExprResult VisitParenExpr(ParenExpr *E) {
20476  return rebuildSugarExpr(E);
20477  }
20478 
20479  ExprResult VisitUnaryExtension(UnaryOperator *E) {
20480  return rebuildSugarExpr(E);
20481  }
20482 
20483  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20484  const PointerType *Ptr = DestType->getAs<PointerType>();
20485  if (!Ptr) {
20486  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20487  << E->getSourceRange();
20488  return ExprError();
20489  }
20490 
20491  if (isa<CallExpr>(E->getSubExpr())) {
20492  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20493  << E->getSourceRange();
20494  return ExprError();
20495  }
20496 
20497  assert(E->isPRValue());
20498  assert(E->getObjectKind() == OK_Ordinary);
20499  E->setType(DestType);
20500 
20501  // Build the sub-expression as if it were an object of the pointee type.
20502  DestType = Ptr->getPointeeType();
20503  ExprResult SubResult = Visit(E->getSubExpr());
20504  if (SubResult.isInvalid()) return ExprError();
20505  E->setSubExpr(SubResult.get());
20506  return E;
20507  }
20508 
20509  ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20510 
20511  ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20512 
20513  ExprResult VisitMemberExpr(MemberExpr *E) {
20514  return resolveDecl(E, E->getMemberDecl());
20515  }
20516 
20517  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20518  return resolveDecl(E, E->getDecl());
20519  }
20520  };
20521 }
20522 
20523 /// Rebuilds a call expression which yielded __unknown_anytype.
20524 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20525  Expr *CalleeExpr = E->getCallee();
20526 
20527  enum FnKind {
20528  FK_MemberFunction,
20529  FK_FunctionPointer,
20530  FK_BlockPointer
20531  };
20532 
20533  FnKind Kind;
20534  QualType CalleeType = CalleeExpr->getType();
20535  if (CalleeType == S.Context.BoundMemberTy) {
20536  assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20537  Kind = FK_MemberFunction;
20538  CalleeType = Expr::findBoundMemberType(CalleeExpr);
20539  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20540  CalleeType = Ptr->getPointeeType();
20541  Kind = FK_FunctionPointer;
20542  } else {
20543  CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20544  Kind = FK_BlockPointer;
20545  }
20546  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20547 
20548  // Verify that this is a legal result type of a function.
20549  if (DestType->isArrayType() || DestType->isFunctionType()) {
20550  unsigned diagID = diag::err_func_returning_array_function;
20551  if (Kind == FK_BlockPointer)
20552  diagID = diag::err_block_returning_array_function;
20553 
20554  S.Diag(E->getExprLoc(), diagID)
20555  << DestType->isFunctionType() << DestType;
20556  return ExprError();
20557  }
20558 
20559  // Otherwise, go ahead and set DestType as the call's result.
20560  E->setType(DestType.getNonLValueExprType(S.Context));
20562  assert(E->getObjectKind() == OK_Ordinary);
20563 
20564  // Rebuild the function type, replacing the result type with DestType.
20565  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20566  if (Proto) {
20567  // __unknown_anytype(...) is a special case used by the debugger when
20568  // it has no idea what a function's signature is.
20569  //
20570  // We want to build this call essentially under the K&R
20571  // unprototyped rules, but making a FunctionNoProtoType in C++
20572  // would foul up all sorts of assumptions. However, we cannot
20573  // simply pass all arguments as variadic arguments, nor can we
20574  // portably just call the function under a non-variadic type; see
20575  // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20576  // However, it turns out that in practice it is generally safe to
20577  // call a function declared as "A foo(B,C,D);" under the prototype
20578  // "A foo(B,C,D,...);". The only known exception is with the
20579  // Windows ABI, where any variadic function is implicitly cdecl
20580  // regardless of its normal CC. Therefore we change the parameter
20581  // types to match the types of the arguments.
20582  //
20583  // This is a hack, but it is far superior to moving the
20584  // corresponding target-specific code from IR-gen to Sema/AST.
20585 
20586  ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20587  SmallVector<QualType, 8> ArgTypes;
20588  if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20589  ArgTypes.reserve(E->getNumArgs());
20590  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20591  ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20592  }
20593  ParamTypes = ArgTypes;
20594  }
20595  DestType = S.Context.getFunctionType(DestType, ParamTypes,
20596  Proto->getExtProtoInfo());
20597  } else {
20598  DestType = S.Context.getFunctionNoProtoType(DestType,
20599  FnType->getExtInfo());
20600  }
20601 
20602  // Rebuild the appropriate pointer-to-function type.
20603  switch (Kind) {
20604  case FK_MemberFunction:
20605  // Nothing to do.
20606  break;
20607 
20608  case FK_FunctionPointer:
20609  DestType = S.Context.getPointerType(DestType);
20610  break;
20611 
20612  case FK_BlockPointer:
20613  DestType = S.Context.getBlockPointerType(DestType);
20614  break;
20615  }
20616 
20617  // Finally, we can recurse.
20618  ExprResult CalleeResult = Visit(CalleeExpr);
20619  if (!CalleeResult.isUsable()) return ExprError();
20620  E->setCallee(CalleeResult.get());
20621 
20622  // Bind a temporary if necessary.
20623  return S.MaybeBindToTemporary(E);
20624 }
20625 
20626 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20627  // Verify that this is a legal result type of a call.
20628  if (DestType->isArrayType() || DestType->isFunctionType()) {
20629  S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20630  << DestType->isFunctionType() << DestType;
20631  return ExprError();
20632  }
20633 
20634  // Rewrite the method result type if available.
20635  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20636  assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20637  Method->setReturnType(DestType);
20638  }
20639 
20640  // Change the type of the message.
20641  E->setType(DestType.getNonReferenceType());
20643 
20644  return S.MaybeBindToTemporary(E);
20645 }
20646 
20647 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20648  // The only case we should ever see here is a function-to-pointer decay.
20649  if (E->getCastKind() == CK_FunctionToPointerDecay) {
20650  assert(E->isPRValue());
20651  assert(E->getObjectKind() == OK_Ordinary);
20652 
20653  E->setType(DestType);
20654 
20655  // Rebuild the sub-expression as the pointee (function) type.
20656  DestType = DestType->castAs<PointerType>()->getPointeeType();
20657 
20658  ExprResult Result = Visit(E->getSubExpr());
20659  if (!Result.isUsable()) return ExprError();
20660 
20661  E->setSubExpr(Result.get());
20662  return E;
20663  } else if (E->getCastKind() == CK_LValueToRValue) {
20664  assert(E->isPRValue());
20665  assert(E->getObjectKind() == OK_Ordinary);
20666 
20667  assert(isa<BlockPointerType>(E->getType()));
20668 
20669  E->setType(DestType);
20670 
20671  // The sub-expression has to be a lvalue reference, so rebuild it as such.
20672  DestType = S.Context.getLValueReferenceType(DestType);
20673 
20674  ExprResult Result = Visit(E->getSubExpr());
20675  if (!Result.isUsable()) return ExprError();
20676 
20677  E->setSubExpr(Result.get());
20678  return E;
20679  } else {
20680  llvm_unreachable("Unhandled cast type!");
20681  }
20682 }
20683 
20684 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20685  ExprValueKind ValueKind = VK_LValue;
20686  QualType Type = DestType;
20687 
20688  // We know how to make this work for certain kinds of decls:
20689 
20690  // - functions
20691  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20692  if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20693  DestType = Ptr->getPointeeType();
20694  ExprResult Result = resolveDecl(E, VD);
20695  if (Result.isInvalid()) return ExprError();
20696  return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20697  VK_PRValue);
20698  }
20699 
20700  if (!Type->isFunctionType()) {
20701  S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20702  << VD << E->getSourceRange();
20703  return ExprError();
20704  }
20705  if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20706  // We must match the FunctionDecl's type to the hack introduced in
20707  // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20708  // type. See the lengthy commentary in that routine.
20709  QualType FDT = FD->getType();
20710  const FunctionType *FnType = FDT->castAs<FunctionType>();
20711  const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20712  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20713  if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20714  SourceLocation Loc = FD->getLocation();
20716  S.Context, FD->getDeclContext(), Loc, Loc,
20717  FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20719  false /*isInlineSpecified*/, FD->hasPrototype(),
20720  /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20721 
20722  if (FD->getQualifier())
20723  NewFD->setQualifierInfo(FD->getQualifierLoc());
20724 
20726  for (const auto &AI : FT->param_types()) {
20727  ParmVarDecl *Param =
20728  S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20729  Param->setScopeInfo(0, Params.size());
20730  Params.push_back(Param);
20731  }
20732  NewFD->setParams(Params);
20733  DRE->setDecl(NewFD);
20734  VD = DRE->getDecl();
20735  }
20736  }
20737 
20738  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20739  if (MD->isInstance()) {
20740  ValueKind = VK_PRValue;
20742  }
20743 
20744  // Function references aren't l-values in C.
20745  if (!S.getLangOpts().CPlusPlus)
20746  ValueKind = VK_PRValue;
20747 
20748  // - variables
20749  } else if (isa<VarDecl>(VD)) {
20750  if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20751  Type = RefTy->getPointeeType();
20752  } else if (Type->isFunctionType()) {
20753  S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20754  << VD << E->getSourceRange();
20755  return ExprError();
20756  }
20757 
20758  // - nothing else
20759  } else {
20760  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20761  << VD << E->getSourceRange();
20762  return ExprError();
20763  }
20764 
20765  // Modifying the declaration like this is friendly to IR-gen but
20766  // also really dangerous.
20767  VD->setType(DestType);
20768  E->setType(Type);
20769  E->setValueKind(ValueKind);
20770  return E;
20771 }
20772 
20773 /// Check a cast of an unknown-any type. We intentionally only
20774 /// trigger this for C-style casts.
20777  ExprValueKind &VK, CXXCastPath &Path) {
20778  // The type we're casting to must be either void or complete.
20779  if (!CastType->isVoidType() &&
20780  RequireCompleteType(TypeRange.getBegin(), CastType,
20781  diag::err_typecheck_cast_to_incomplete))
20782  return ExprError();
20783 
20784  // Rewrite the casted expression from scratch.
20785  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20786  if (!result.isUsable()) return ExprError();
20787 
20788  CastExpr = result.get();
20789  VK = CastExpr->getValueKind();
20790  CastKind = CK_NoOp;
20791 
20792  return CastExpr;
20793 }
20794 
20796  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20797 }
20798 
20800  Expr *arg, QualType &paramType) {
20801  // If the syntactic form of the argument is not an explicit cast of
20802  // any sort, just do default argument promotion.
20803  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20804  if (!castArg) {
20805  ExprResult result = DefaultArgumentPromotion(arg);
20806  if (result.isInvalid()) return ExprError();
20807  paramType = result.get()->getType();
20808  return result;
20809  }
20810 
20811  // Otherwise, use the type that was written in the explicit cast.
20812  assert(!arg->hasPlaceholderType());
20813  paramType = castArg->getTypeAsWritten();
20814 
20815  // Copy-initialize a parameter of that type.
20816  InitializedEntity entity =
20817  InitializedEntity::InitializeParameter(Context, paramType,
20818  /*consumed*/ false);
20819  return PerformCopyInitialization(entity, callLoc, arg);
20820 }
20821 
20823  Expr *orig = E;
20824  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20825  while (true) {
20826  E = E->IgnoreParenImpCasts();
20827  if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20828  E = call->getCallee();
20829  diagID = diag::err_uncasted_call_of_unknown_any;
20830  } else {
20831  break;
20832  }
20833  }
20834 
20835  SourceLocation loc;
20836  NamedDecl *d;
20837  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20838  loc = ref->getLocation();
20839  d = ref->getDecl();
20840  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20841  loc = mem->getMemberLoc();
20842  d = mem->getMemberDecl();
20843  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20844  diagID = diag::err_uncasted_call_of_unknown_any;
20845  loc = msg->getSelectorStartLoc();
20846  d = msg->getMethodDecl();
20847  if (!d) {
20848  S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20849  << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20850  << orig->getSourceRange();
20851  return ExprError();
20852  }
20853  } else {
20854  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20855  << E->getSourceRange();
20856  return ExprError();
20857  }
20858 
20859  S.Diag(loc, diagID) << d << orig->getSourceRange();
20860 
20861  // Never recoverable.
20862  return ExprError();
20863 }
20864 
20865 /// Check for operands with placeholder types and complain if found.
20866 /// Returns ExprError() if there was an error and no recovery was possible.
20868  if (!Context.isDependenceAllowed()) {
20869  // C cannot handle TypoExpr nodes on either side of a binop because it
20870  // doesn't handle dependent types properly, so make sure any TypoExprs have
20871  // been dealt with before checking the operands.
20872  ExprResult Result = CorrectDelayedTyposInExpr(E);
20873  if (!Result.isUsable()) return ExprError();
20874  E = Result.get();
20875  }
20876 
20877  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20878  if (!placeholderType) return E;
20879 
20880  switch (placeholderType->getKind()) {
20881  case BuiltinType::UnresolvedTemplate: {
20882  auto *ULE = cast<UnresolvedLookupExpr>(E);
20883  const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20884  // There's only one FoundDecl for UnresolvedTemplate type. See
20885  // BuildTemplateIdExpr.
20886  NamedDecl *Temp = *ULE->decls_begin();
20887  const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20888 
20889  if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
20890  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20891  << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
20892  << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
20893  else
20894  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20895  << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
20896  << IsTypeAliasTemplateDecl;
20897  Diag(Temp->getLocation(), diag::note_referenced_type_template)
20898  << IsTypeAliasTemplateDecl;
20899 
20900  return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
20901  }
20902 
20903  // Overloaded expressions.
20904  case BuiltinType::Overload: {
20905  // Try to resolve a single function template specialization.
20906  // This is obligatory.
20907  ExprResult Result = E;
20908  if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20909  return Result;
20910 
20911  // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20912  // leaves Result unchanged on failure.
20913  Result = E;
20914  if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20915  return Result;
20916 
20917  // If that failed, try to recover with a call.
20918  tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20919  /*complain*/ true);
20920  return Result;
20921  }
20922 
20923  // Bound member functions.
20924  case BuiltinType::BoundMember: {
20925  ExprResult result = E;
20926  const Expr *BME = E->IgnoreParens();
20927  PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20928  // Try to give a nicer diagnostic if it is a bound member that we recognize.
20929  if (isa<CXXPseudoDestructorExpr>(BME)) {
20930  PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20931  } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20932  if (ME->getMemberNameInfo().getName().getNameKind() ==
20934  PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20935  }
20936  tryToRecoverWithCall(result, PD,
20937  /*complain*/ true);
20938  return result;
20939  }
20940 
20941  // ARC unbridged casts.
20942  case BuiltinType::ARCUnbridgedCast: {
20943  Expr *realCast = ObjC().stripARCUnbridgedCast(E);
20944  ObjC().diagnoseARCUnbridgedCast(realCast);
20945  return realCast;
20946  }
20947 
20948  // Expressions of unknown type.
20949  case BuiltinType::UnknownAny:
20950  return diagnoseUnknownAnyExpr(*this, E);
20951 
20952  // Pseudo-objects.
20953  case BuiltinType::PseudoObject:
20954  return PseudoObject().checkRValue(E);
20955 
20956  case BuiltinType::BuiltinFn: {
20957  // Accept __noop without parens by implicitly converting it to a call expr.
20958  auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20959  if (DRE) {
20960  auto *FD = cast<FunctionDecl>(DRE->getDecl());
20961  unsigned BuiltinID = FD->getBuiltinID();
20962  if (BuiltinID == Builtin::BI__noop) {
20963  E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20964  CK_BuiltinFnToFnPtr)
20965  .get();
20966  return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20968  FPOptionsOverride());
20969  }
20970 
20971  if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20972  // Any use of these other than a direct call is ill-formed as of C++20,
20973  // because they are not addressable functions. In earlier language
20974  // modes, warn and force an instantiation of the real body.
20975  Diag(E->getBeginLoc(),
20976  getLangOpts().CPlusPlus20
20977  ? diag::err_use_of_unaddressable_function
20978  : diag::warn_cxx20_compat_use_of_unaddressable_function);
20979  if (FD->isImplicitlyInstantiable()) {
20980  // Require a definition here because a normal attempt at
20981  // instantiation for a builtin will be ignored, and we won't try
20982  // again later. We assume that the definition of the template
20983  // precedes this use.
20984  InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20985  /*Recursive=*/false,
20986  /*DefinitionRequired=*/true,
20987  /*AtEndOfTU=*/false);
20988  }
20989  // Produce a properly-typed reference to the function.
20990  CXXScopeSpec SS;
20991  SS.Adopt(DRE->getQualifierLoc());
20992  TemplateArgumentListInfo TemplateArgs;
20993  DRE->copyTemplateArgumentsInto(TemplateArgs);
20994  return BuildDeclRefExpr(
20995  FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20996  DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20997  DRE->getTemplateKeywordLoc(),
20998  DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20999  }
21000  }
21001 
21002  Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21003  return ExprError();
21004  }
21005 
21006  case BuiltinType::IncompleteMatrixIdx:
21007  Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21008  ->getRowIdx()
21009  ->getBeginLoc(),
21010  diag::err_matrix_incomplete_index);
21011  return ExprError();
21012 
21013  // Expressions of unknown type.
21014  case BuiltinType::ArraySection:
21015  Diag(E->getBeginLoc(), diag::err_array_section_use)
21016  << cast<ArraySectionExpr>(E)->isOMPArraySection();
21017  return ExprError();
21018 
21019  // Expressions of unknown type.
21020  case BuiltinType::OMPArrayShaping:
21021  return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21022 
21023  case BuiltinType::OMPIterator:
21024  return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21025 
21026  // Everything else should be impossible.
21027 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21028  case BuiltinType::Id:
21029 #include "clang/Basic/OpenCLImageTypes.def"
21030 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21031  case BuiltinType::Sampled##Id:
21032 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
21033 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
21034 #include "clang/Basic/OpenCLImageTypes.def"
21035 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21036  case BuiltinType::Id:
21037 #include "clang/Basic/OpenCLExtensionTypes.def"
21038 #define SVE_TYPE(Name, Id, SingletonId) \
21039  case BuiltinType::Id:
21040 #include "clang/Basic/AArch64SVEACLETypes.def"
21041 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21042  case BuiltinType::Id:
21043 #include "clang/Basic/PPCTypes.def"
21044 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21045 #include "clang/Basic/RISCVVTypes.def"
21046 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21047 #include "clang/Basic/WebAssemblyReferenceTypes.def"
21048 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21049 #define PLACEHOLDER_TYPE(Id, SingletonId)
21050 #include "clang/AST/BuiltinTypes.def"
21051  break;
21052  }
21053 
21054  llvm_unreachable("invalid placeholder type!");
21055 }
21056 
21058  if (E->isTypeDependent())
21059  return true;
21060  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21061  return E->getType()->isIntegralOrEnumerationType();
21062  return false;
21063 }
21064 
21066  ArrayRef<Expr *> SubExprs, QualType T) {
21067  if (!Context.getLangOpts().RecoveryAST)
21068  return ExprError();
21069 
21070  if (isSFINAEContext())
21071  return ExprError();
21072 
21073  if (T.isNull() || T->isUndeducedType() ||
21074  !Context.getLangOpts().RecoveryASTType)
21075  // We don't know the concrete type, fallback to dependent type.
21076  T = Context.DependentTy;
21077 
21078  return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21079 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3299
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static char ID
Definition: Arena.cpp:183
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
llvm::APSInt APSInt
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Offset
Definition: Format.cpp:2978
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
unsigned Iter
Definition: HTMLLogger.cpp:154
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:50
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
This file declares semantic analysis for CUDA constructs.
CastType
Definition: SemaCast.cpp:50
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9237
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17651
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:2015
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:15259
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
Definition: SemaExpr.cpp:10119
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:18591
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10861
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
Definition: SemaExpr.cpp:15049
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6209
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10780
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
Definition: SemaExpr.cpp:8804
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3269
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8258
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
Definition: SemaExpr.cpp:8464
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
Definition: SemaExpr.cpp:11809
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10825
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16641
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11759
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
Definition: SemaExpr.cpp:2722
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2298
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14522
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:17989
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13303
@ NCCK_Block
Definition: SemaExpr.cpp:13303
@ NCCK_None
Definition: SemaExpr.cpp:13303
@ NCCK_Lambda
Definition: SemaExpr.cpp:13303
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
Definition: SemaExpr.cpp:10013
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:9286
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6133
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19803
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18424
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18443
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16749
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
Definition: SemaExpr.cpp:8708
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14661
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13862
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4837
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12161
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14422
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4437
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8783
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17838
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:14578
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:10946
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:8101
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19600
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3294
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:8067
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1999
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11851
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6485
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13487
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19849
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
Definition: SemaExpr.cpp:10060
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19568
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14709
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14404
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17512
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12036
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
Definition: SemaExpr.cpp:8738
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
Definition: SemaExpr.cpp:14676
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1385
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6375
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
Definition: SemaExpr.cpp:9674
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
Definition: SemaExpr.cpp:8382
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:8088
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10792
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4894
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9013
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17554
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
Definition: SemaExpr.cpp:15140
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr * > Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2444
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
Definition: SemaExpr.cpp:13970
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8327
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
Definition: SemaExpr.cpp:8436
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10619
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11865
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:4307
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10667
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3593
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5846
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:146
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11298
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4229
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9186
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
Definition: SemaExpr.cpp:1342
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18274
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:10976
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13551
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we're in an extern inline function and referring to a variable or function with interna...
Definition: SemaExpr.cpp:162
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
Definition: SemaExpr.cpp:17869
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:11660
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15197
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14131
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1435
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4908
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
Definition: SemaExpr.cpp:10163
@ ConstMethod
Definition: SemaExpr.cpp:13353
@ ConstUnknown
Definition: SemaExpr.cpp:13355
@ ConstVariable
Definition: SemaExpr.cpp:13351
@ NestedConstMember
Definition: SemaExpr.cpp:13354
@ ConstMember
Definition: SemaExpr.cpp:13352
@ ConstFunction
Definition: SemaExpr.cpp:13350
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:18631
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15104
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:639
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:8838
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
Definition: SemaExpr.cpp:17957
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
Definition: SemaExpr.cpp:13362
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13340
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18391
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10839
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4259
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11493
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12079
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20822
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:2007
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8502
OriginalExprKind
Definition: SemaExpr.cpp:13481
@ OEK_Variable
Definition: SemaExpr.cpp:13482
@ OEK_LValue
Definition: SemaExpr.cpp:13484
@ OEK_Member
Definition: SemaExpr.cpp:13483
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:18523
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1292
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10767
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
Definition: SemaExpr.cpp:11399
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18350
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1367
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10583
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13290
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
Definition: SemaExpr.cpp:18759
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6444
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:9034
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:6302
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4247
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15125
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4927
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3723
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1567
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:11027
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6402
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1481
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4289
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10809
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
Definition: SemaExpr.cpp:8297
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11997
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12869
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8416
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14071
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8723
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
Definition: SemaExpr.cpp:1186
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:14620
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:664
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
Definition: SemaExpr.cpp:20427
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1261
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11712
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1214
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19771
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1975
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:107
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1528
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1237
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13934
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18733
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10757
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11649
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
Definition: SemaExpr.cpp:14732
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11699
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13304
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:8232
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15169
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15155
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11689
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15092
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4503
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:10081
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15438
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13679
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13099
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
Definition: SemaExpr.cpp:19185
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:17903
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11292
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:10893
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7589
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
This file declares semantic analysis for expressions involving.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
tok::TokenKind ContextKind
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
SourceLocation End
SourceLocation Begin
LineState State
__DEVICE__ int max(int __a, int __b)
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool hasValue() const
Definition: APValue.h:399
bool isInt() const
Definition: APValue.h:401
APSInt & getInt()
Definition: APValue.h:423
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
CanQualType AccumTy
Definition: ASTContext.h:1107
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1125
CanQualType LongTy
Definition: ASTContext.h:1103
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
CanQualType Int128Ty
Definition: ASTContext.h:1103
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2133
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:651
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:2147
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1107
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1106
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2589
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2605
CanQualType DoubleTy
Definition: ASTContext.h:1106
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
Definition: ASTContext.h:1106
CanQualType Char16Ty
Definition: ASTContext.h:1101
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1121
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1122
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1605
CanQualType WideCharTy
Definition: ASTContext.h:1098
IdentifierTable & Idents
Definition: ASTContext.h:647
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:649
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2782
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
bool typesAreBlockPointerCompatible(QualType, QualType)
const LangOptions & getLangOpts() const
Definition: ASTContext.h:778
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1095
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType Float128Ty
Definition: ASTContext.h:1106
CanQualType UnsignedLongTy
Definition: ASTContext.h:1104
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1110
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
Definition: ASTContext.h:1122
CanQualType CharTy
Definition: ASTContext.h:1096
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1103
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1171
CanQualType PseudoObjectTy
Definition: ASTContext.h:1125
CanQualType Float16Ty
Definition: ASTContext.h:1120
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2171
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1122
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2335
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1175
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2632
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2355
CanQualType BuiltinFnTy
Definition: ASTContext.h:1124
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1094
CanQualType UnsignedCharTy
Definition: ASTContext.h:1104
CanQualType UnsignedIntTy
Definition: ASTContext.h:1104
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1892
CanQualType UnknownAnyTy
Definition: ASTContext.h:1123
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1105
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1583
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1103
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1110
CanQualType LongAccumTy
Definition: ASTContext.h:1108
CanQualType Char32Ty
Definition: ASTContext.h:1102
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
CanQualType LongFractTy
Definition: ASTContext.h:1110
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1138
QualType getCorrespondingUnsignedType(QualType T) const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:761
CanQualType LongLongTy
Definition: ASTContext.h:1103
QualType getCorrespondingSignedType(QualType T) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1808
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2014
unsigned char getFixedPointScale(QualType Ty) const
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1100
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1118
bool isDependenceAllowed() const
Definition: ASTContext.h:784
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1076
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2359
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4390
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2716
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2771
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3530
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3544
QualType getElementType() const
Definition: Type.h:3542
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6275
Attr - This represents one attribute.
Definition: Attr.h:46
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5671
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5993
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4293
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3892
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2236
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3991
bool isComparisonOp() const
Definition: Expr.h:3992
StringRef getOpcodeStr() const
Definition: Expr.h:3957
bool isRelationalOp() const
Definition: Expr.h:3986
SourceLocation getOperatorLoc() const
Definition: Expr.h:3933
bool isCompoundAssignmentOp() const
Definition: Expr.h:4035
bool isMultiplicativeOp() const
Definition: Expr.h:3976
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2189
bool isShiftOp() const
Definition: Expr.h:3980
bool isEqualityOp() const
Definition: Expr.h:3989
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4843
bool isBitwiseOp() const
Definition: Expr.h:3983
bool isAdditiveOp() const
Definition: Expr.h:3978
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition: Expr.cpp:2261
Opcode getOpcode() const
Definition: Expr.h:3936
Expr * getRHS() const
Definition: Expr.h:3943
bool isAssignmentOp() const
Definition: Expr.h:4030
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2198
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3982
Expr * getLHS() const
Definition: Expr.h:3941
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
A class which contains all the information about a particular captured value.
Definition: Decl.h:4503
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4497
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5233
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4583
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4579
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4636
void setIsVariadic(bool value)
Definition: Decl.h:4573
SourceLocation getCaretLocation() const
Definition: Decl.h:4570
void setBody(CompoundStmt *B)
Definition: Decl.h:4577
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5244
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5420
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6214
Pointer to a block type.
Definition: Type.h:3361
This class is used for builtin types like 'int'.
Definition: Type.h:2989
bool isSVEBool() const
Definition: Type.h:3064
Kind getKind() const
Definition: Type.h:3035
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:209
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:1857
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1605
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2904
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1264
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:969
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.cpp:1023
Expr * getExpr()
Get the initialization expression that will be used.
Definition: ExprCXX.cpp:1035
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1484
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:2293
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:149
SourceRange getSourceRange() const
Definition: ExprCXX.h:161
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1226
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:569
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1930
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Represents the this expression in C++.
Definition: ExprCXX.h:1148
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3053
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3076
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1549
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3082
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3050
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3063
Expr * getCallee()
Definition: Expr.h:3022
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3042
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:3104
void setCallee(Expr *F)
Definition: Expr.h:3024
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:3095
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3535
CastKind getCastKind() const
Definition: Expr.h:3579
Expr * getSubExpr()
Definition: Expr.h:3585
const char * getCastKindName() const
Definition: Expr.h:3583
void setSubExpr(Expr *E)
Definition: Expr.h:3587
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
unsigned getValue() const
Definition: Expr.h:1610
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4610
Complex values, per C99 6.2.5p11.
Definition: Type.h:3098
QualType getElementType() const
Definition: Type.h:3108
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4865
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3465
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
bool body_empty() const
Definition: Stmt.h:1650
Stmt * getStmtExprResult()
Definition: Stmt.h:1723
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4231
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3568
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3624
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3644
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1072
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:302
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:378
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1122
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
bool isImmediateInvocation() const
Definition: Expr.h:1144
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4179
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4200
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4197
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4551
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
void setTypoName(const IdentifierInfo *II)
void setTypoNNS(NestedNameSpecifier *NNS)
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1585
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1964
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1233
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1352
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1409
ValueDecl * getDecl()
Definition: Expr.h:1328
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1458
void setDecl(ValueDecl *NewD)
Definition: Expr.cpp:544
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1355
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition: Expr.h:1413
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1332
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1381
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1343
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1347
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1365
SourceLocation getLocation() const
Definition: Expr.h:1336
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:725
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
bool isInvalidDecl() const
Definition: DeclBase.h:594
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setReferenced(bool R=true)
Definition: DeclBase.h:629
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
bool hasAttr() const
Definition: DeclBase.h:583
Kind getKind() const
Definition: DeclBase.h:448
T * getAttr() const
Definition: DeclBase.h:579
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:2001
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:800
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:837
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
DeclaratorContext getContext() const
Definition: DeclSpec.h:2072
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
bool isInvalidType() const
Definition: DeclSpec.h:2714
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2330
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:482
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:922
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:696
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
RAII object that enters a new expression evaluation context.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5587
EnumDecl * getDecl() const
Definition: Type.h:5594
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3782
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3809
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
This represents one expression.
Definition: Expr.h:110
LValueClassification
Definition: Expr.h:282
@ LV_ArrayTemporary
Definition: Expr.h:292
@ LV_ClassTemporary
Definition: Expr.h:291
@ LV_MemberFunction
Definition: Expr.h:289
@ LV_IncompleteVoidType
Definition: Expr.h:285
@ LV_Valid
Definition: Expr.h:283
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition: Expr.cpp:3138
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:3067
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3116
void setType(QualType t)
Definition: Expr.h:143
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition: Expr.h:239
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3111
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3099
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3120
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3107
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3331
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:817
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3608
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3091
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:792
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:804
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:807
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:794
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3980
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
@ ImmediateInvocation
An immediate invocation.
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition: Expr.cpp:4232
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
isModifiableLvalueResult
Definition: Expr.h:297
@ MLV_DuplicateVectorComponents
Definition: Expr.h:301
@ MLV_LValueCast
Definition: Expr.h:303
@ MLV_InvalidMessageExpression
Definition: Expr.h:312
@ MLV_ConstQualifiedField
Definition: Expr.h:306
@ MLV_InvalidExpression
Definition: Expr.h:302
@ MLV_IncompleteType
Definition: Expr.h:304
@ MLV_Valid
Definition: Expr.h:298
@ MLV_ConstQualified
Definition: Expr.h:305
@ MLV_NoSetterProperty
Definition: Expr.h:309
@ MLV_ArrayTemporary
Definition: Expr.h:314
@ MLV_SubObjCPropertySetting
Definition: Expr.h:311
@ MLV_ConstAddrSpace
Definition: Expr.h:307
@ MLV_MemberFunction
Definition: Expr.h:310
@ MLV_NotObjectType
Definition: Expr.h:299
@ MLV_ArrayType
Definition: Expr.h:308
@ MLV_ClassTemporary
Definition: Expr.h:313
@ MLV_IncompleteVoidType
Definition: Expr.h:300
QualType getType() const
Definition: Expr.h:142
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:448
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:136
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6154
ExtVectorType - Extended vector type.
Definition: Type.h:4073
Represents difference between two FPOptions values.
Definition: LangOptions.h:956
bool isFPConstrained() const
Definition: LangOptions.h:884
RoundingMode getRoundingMode() const
Definition: LangOptions.h:890
Represents a member of a struct/union/class.
Definition: Decl.h:3060
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3151
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3221
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3273
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:72
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:98
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:1054
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1133
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1039
const Expr * getSubExpr() const
Definition: Expr.h:1052
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Represents a function declaration or definition.
Definition: Decl.h:1972
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3717
bool isImmediateFunction() const
Definition: Decl.cpp:3292
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3877
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3636
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3735
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2833
QualType getReturnType() const
Definition: Decl.h:2757
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2408
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2161
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3496
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2686
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3983
bool isConsteval() const
Definition: Decl.h:2447
size_t param_size() const
Definition: Decl.h:2702
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3160
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3893
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2793
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2709
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4641
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4671
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4668
QualType desugar() const
Definition: Type.h:5135
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4908
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5113
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4927
bool isParamConsumed(unsigned I) const
Definition: Type.h:5127
ArrayRef< QualType > param_types() const
Definition: Type.h:5056
unsigned getNumParams() const
Definition: Type.h:4901
QualType getParamType(unsigned i) const
Definition: Type.h:4903
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5024
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4912
Declaration of a template function.
Definition: DeclTemplate.h:957
unsigned getNumParams() const
Definition: TypeLoc.h:1500
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1452
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1444
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4379
bool getCmseNSCall() const
Definition: Type.h:4429
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4453
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4268
ExtInfo getExtInfo() const
Definition: Type.h:4597
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4593
QualType getReturnType() const
Definition: Type.h:4585
bool getCmseNSCallAttr() const
Definition: Type.h:4595
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4609
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4685
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition: Expr.cpp:4532
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3707
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2129
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3344
Describes an C or C++ initializer list.
Definition: Expr.h:4888
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8585
Describes an entity that is being initialized.
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
Represents the declaration of a label.
Definition: Decl.h:500
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1950
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition: ExprCXX.cpp:1336
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:299
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:308
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:306
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Definition: LangOptions.h:313
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:304
@ None
Permit no implicit vector bitcasts.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:517
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:661
bool isSignedOverflowDefined() const
Definition: LangOptions.h:657
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition: Lexer.h:399
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition: Lexer.cpp:310
Represents the results of name lookup.
Definition: Lookup.h:46
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:488
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
A global _GUID constant.
Definition: DeclCXX.h:4289
MS property subscript expression.
Definition: ExprCXX.h:1000
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2794
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4143
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4157
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3224
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3413
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3307
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1809
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3442
Expr * getBase() const
Definition: Expr.h:3301
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1853
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:637
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:463
std::string getQualifiedNameAsString(bool WithGlobalNsPrefix=false) const
Definition: Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool isExternallyVisible() const
Definition: Decl.h:409
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:373
Represent a C++ namespace.
Definition: Decl.h:548
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1452
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6964
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1491
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:595
SourceLocation getLocation() const
Definition: ExprObjC.h:592
SourceLocation getOpLoc() const
Definition: ExprObjC.h:600
const Expr * getBase() const
Definition: ExprObjC.h:583
bool isArrow() const
Definition: ExprObjC.h:587
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:579
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:598
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
QualType getReturnType() const
Definition: DeclObjC.h:329
bool isClassMethod() const
Definition: DeclObjC.h:434
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
Represents a pointer to an Objective C object.
Definition: Type.h:7020
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1798
qual_range quals() const
Definition: Type.h:7139
Represents a class type in Objective C.
Definition: Type.h:6766
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:332
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:340
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1712
Helper class for OffsetOfExpr.
Definition: Expr.h:2411
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
void * getAsOpaquePtr() const
Definition: Ownership.h:90
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2978
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3038
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2182
const Expr * getSubExpr() const
Definition: Expr.h:2197
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2201
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4785
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5694
SourceLocation getLParenLoc() const
Definition: Expr.h:5711
SourceLocation getRParenLoc() const
Definition: Expr.h:5712
Expr * getExpr(unsigned Init)
Definition: Expr.h:5696
Represents a parameter to a function.
Definition: Decl.h:1762
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1891
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1795
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1895
QualType getOriginalType() const
Definition: Decl.cpp:2928
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2919
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3020
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3151
QualType getPointeeType() const
Definition: Type.h:3161
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:693
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:733
IdentifierTable & getIdentifierTable()
bool isMacroDefined(StringRef Id)
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6346
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7455
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7460
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:7518
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3493
@ DK_nontrivial_c_struct
Definition: Type.h:1523
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2841
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7553
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7371
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7497
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:7512
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7411
bool isAddressSpaceOverlapping(QualType T) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition: Type.h:1411
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2600
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7572
QualType getCanonicalType() const
Definition: Type.h:7423
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7465
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2859
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1174
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition: Type.h:7579
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7444
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7492
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1629
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
bool isCanonical() const
Definition: Type.h:7428
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2592
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7403
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:7506
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:481
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
void removeObjCLifetime()
Definition: Type.h:537
void removeAddressSpace()
Definition: Type.h:582
void addConst()
Definition: Type.h:446
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
Qualifiers withoutObjCLifetime() const
Definition: Type.h:519
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:514
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:754
Represents a struct/union/class.
Definition: Decl.h:4171
field_range fields() const
Definition: Decl.h:4377
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5561
RecordDecl * getDecl() const
Definition: Type.h:5571
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5166
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3392
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition: Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:175
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
@ Sycl
SYCL specific diagnostic.
@ Esimd
ESIMD specific diagnostic.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: SemaCUDA.h:110
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
const DeclContext * getCurObjCLexicalContext() const
Definition: SemaObjC.cpp:1256
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: SemaObjC.h:841
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:578
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: SemaOpenMP.h:369
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
static bool isTypeDecoratedWithDeclAttribute(QualType Ty)
Definition: SemaSYCL.h:363
@ KernelNonConstStaticDataVariable
Definition: SemaSYCL.h:302
@ KernelGlobalVariable
Definition: SemaSYCL.h:300
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6674
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9610
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9649
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5904
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17090
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17096
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:462
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
Definition: SemaExpr.cpp:14543
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
SemaObjC & ObjC()
Definition: Sema.h:1012
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2547
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15775
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3717
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15448
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition: Sema.cpp:846
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:6485
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7487
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:493
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19530
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13177
VariadicCallType
Definition: Sema.h:2031
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7127
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3027
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7642
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:2422
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15795
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:17380
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15801
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1632
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12188
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17315
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:20279
ConditionKind
Definition: Sema.h:6026
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2763
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:806
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2219
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12751
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition: Sema.h:6561
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3657
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:18344
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17101
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6750
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10255
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7614
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt=std::nullopt)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:20064
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:15814
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16467
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1547
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:867
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:1117
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13885
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5114
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:2074
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7736
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14171
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15333
ASTContext & Context
Definition: Sema.h:857
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:6387
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:9950
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
Definition: SemaExpr.cpp:20075
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11585
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:8003
Preprocessor & getPreprocessor() const
Definition: Sema.h:525
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:21057
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13016
AllowFoldKind
Definition: Sema.h:5918
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19543
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:833
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:845
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15730
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:18835
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:19794
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15245
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17740
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9693
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:678
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:950
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3605
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6277
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3213
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:7141
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15782
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:4625
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:8019
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:13062
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1552
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2277
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16070
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
Definition: SemaExpr.cpp:1746
AssumedTemplateKind
Definition: Sema.h:8966
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:2044
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:588
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:647
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:226
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20310
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:68
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12215
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:7382
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12991
ReuseLambdaContextDecl_t
Definition: Sema.h:5392
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17415
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2325
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:19941
Preprocessor & PP
Definition: Sema.h:856
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11037
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5802
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6548
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14136
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16741
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4829
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7631
const LangOptions & LangOpts
Definition: Sema.h:855
const LangOptions & getLangOpts() const
Definition: Sema.h:519
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15884
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2472
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:6816
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17436
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
Definition: SemaExpr.cpp:17400
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:206
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:73
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19951
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Definition: SemaExpr.cpp:9977
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition: Sema.h:10641
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:1015
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15693
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3756
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10505
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9745
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:721
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3301
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7367
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
Definition: SemaExpr.cpp:1714
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16259
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7777
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:995
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:20775
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:6430
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16623
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:8028
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:20004
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6408
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1527
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6215
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:6259
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:6283
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:6288
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6254
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6233
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6217
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:6244
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:6229
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:6238
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6250
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:6271
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:6265
SourceManager & getSourceManager() const
Definition: Sema.h:524
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8565
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:6059
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:6069
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:6067
@ ACK_Comparison
A comparison.
Definition: Sema.h:6065
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19898
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2988
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4220
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16708
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:5164
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20867
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17295
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10604
TryCaptureKind
Definition: Sema.h:5434
@ TryCapture_Implicit
Definition: Sema.h:5435
@ TryCapture_ExplicitByRef
Definition: Sema.h:5437
AssignmentAction
Definition: Sema.h:5355
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6783
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4493
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:8892
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:12767
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10680
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19507
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13724
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20145
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5588
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7662
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7708
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:5162
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:229
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
Definition: SemaExpr.cpp:2129
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15232
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:7810
@ CTK_ErrorRecovery
Definition: Sema.h:7727
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3217
ASTContext & getASTContext() const
Definition: Sema.h:526
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:122
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:10633
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5237
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3653
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:12708
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:8516
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:5106
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:2046
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:6775
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4723
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20151
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4330
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16460
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8923
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:829
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20795
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
Definition: SemaExpr.cpp:19141
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7845
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:6398
FPOptions & getCurFPFeatures()
Definition: Sema.h:521
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17818
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19133
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6558
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7757
SourceManager & SourceMgr
Definition: Sema.h:860
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4814
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7918
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2485
DiagnosticsEngine & Diags
Definition: Sema.h:859
FPOptions CurFPFeatures
Definition: Sema.h:853
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:597
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector,...
Definition: SemaExpr.cpp:7692
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5661
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20194
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13113
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4968
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15809
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:1070
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6151
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12828
SemaOpenMP & OpenMP()
Definition: Sema.h:1022
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8996
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16271
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:553
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:19921
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:16768
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18001
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15853
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4874
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:6029
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20252
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1999
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21065
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15295
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3790
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:3081
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7341
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16109
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:891
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4947
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14759
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9271
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6515
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4797
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:7538
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16138
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10719
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:10629
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:523
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11152
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:6802
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:20799
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:5891
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16051
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17826
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7273
SemaCUDA & CUDA()
Definition: Sema.h:1002
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5449
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Definition: SemaExpr.cpp:5122
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4779
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition: Expr.h:4820
SourceLocation getBeginLoc() const
Definition: Expr.h:4824
SourceLocation getEndLoc() const
Definition: Expr.h:4825
SourceLocIdentKind getIdentKind() const
Definition: Expr.h:4799
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:267
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4435
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
unsigned getLength() const
Definition: Expr.h:1890
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1865
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1246
StringRef getString() const
Definition: Expr.h:1850
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3690
bool isUnion() const
Definition: Decl.h:3793
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3811
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:218
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:321
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:672
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:992
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:509
IntType getSizeType() const
Definition: TargetInfo.h:371
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:519
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1561
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1654
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:1033
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:869
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1472
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
unsigned getLength() const
Definition: Token.h:135
void setKind(tok::TokenKind K)
Definition: Token.h:95
tok::TokenKind getKind() const
Definition: Token.h:94
void setLocation(SourceLocation L)
Definition: Token.h:140
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents a declaration of a type.
Definition: Decl.h:3393
const Type * getTypeForDecl() const
Definition: Decl.h:3417
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3420
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7342
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7353
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1813
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2400
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1881
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:8000
bool isBlockPointerType() const
Definition: Type.h:7632
bool isVoidType() const
Definition: Type.h:7939
bool isBooleanType() const
Definition: Type.h:8067
bool isObjCBuiltinType() const
Definition: Type.h:7811
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1898
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8117
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:7915
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:677
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2070
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8097
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2020
bool isVoidPointerType() const
Definition: Type.cpp:665
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:7690
bool isCharType() const
Definition: Type.cpp:2088
bool isFunctionPointerType() const
Definition: Type.h:7658
bool isArithmeticType() const
Definition: Type.cpp:2280
bool isConstantMatrixType() const
Definition: Type.h:7752
bool isPointerType() const
Definition: Type.h:7624
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7979
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2479
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8227
bool isReferenceType() const
Definition: Type.h:7636
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8020
bool isEnumeralType() const
Definition: Type.h:7722
bool isScalarType() const
Definition: Type.h:8038
bool isVariableArrayType() const
Definition: Type.h:7702
bool isSizelessBuiltinType() const
Definition: Type.cpp:2440
bool isClkEventT() const
Definition: Type.h:7841
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2506
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2057
bool isObjCQualifiedIdType() const
Definition: Type.h:7781
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8054
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2235
bool isExtVectorType() const
Definition: Type.h:7734
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2124
bool isExtVectorBoolType() const
Definition: Type.h:7738
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2544
bool isImageType() const
Definition: Type.h:7853
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:7933
bool isPipeType() const
Definition: Type.h:7870
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2669
bool isBitIntType() const
Definition: Type.h:7874
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7908
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7714
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2661
bool isAnyComplexType() const
Definition: Type.h:7726
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7992
bool isHalfType() const
Definition: Type.h:7943
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8008
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2295
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7921
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2185
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2463
bool isQueueT() const
Definition: Type.h:7845
bool isMemberPointerType() const
Definition: Type.h:7672
bool isAtomicType() const
Definition: Type.h:7773
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8080
bool isObjCIdType() const
Definition: Type.h:7793
bool isMatrixType() const
Definition: Type.h:7748
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2679
bool isComplexIntegerType() const
Definition: Type.cpp:683
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2081
bool isObjCObjectType() const
Definition: Type.h:7764
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4837
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8213
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4927
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8073
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2361
bool isFunctionType() const
Definition: Type.h:7620
bool isObjCObjectPointerType() const
Definition: Type.h:7760
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2257
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8034
bool isVectorType() const
Definition: Type.h:7730
bool isObjCQualifiedClassType() const
Definition: Type.h:7787
bool isObjCClassType() const
Definition: Type.h:7799
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2265
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2493
ScalarTypeKind
Definition: Type.h:2634
@ STK_FloatingComplex
Definition: Type.h:2643
@ STK_Floating
Definition: Type.h:2641
@ STK_BlockPointer
Definition: Type.h:2636
@ STK_Bool
Definition: Type.h:2639
@ STK_ObjCObjectPointer
Definition: Type.h:2637
@ STK_FixedPoint
Definition: Type.h:2644
@ STK_IntegralComplex
Definition: Type.h:2642
@ STK_CPointer
Definition: Type.h:2635
@ STK_Integral
Definition: Type.h:2640
@ STK_MemberPointer
Definition: Type.h:2638
bool isFloatingType() const
Definition: Type.cpp:2248
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2195
bool isAnyPointerType() const
Definition: Type.h:7628
bool isRealType() const
Definition: Type.cpp:2271
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isSubscriptableVectorType() const
Definition: Type.h:7744
bool isSamplerT() const
Definition: Type.h:7833
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
bool isNullPtrType() const
Definition: Type.h:7972
bool isRecordType() const
Definition: Type.h:7718
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4649
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2475
Simple class containing the result of Sema::CorrectTypo.
DeclClass * getCorrectionDeclAs() const
std::string getAsString(const LangOptions &LO) const
IdentifierInfo * getCorrectionAsIdentifierInfo() const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
bool isOverloaded() const
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6626
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2620
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2235
void setSubExpr(Expr *E)
Definition: Expr.h:2281
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2284
Opcode getOpcode() const
Definition: Expr.h:2275
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1484
Expr * getSubExpr() const
Definition: Expr.h:2280
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4900
bool isIncrementDecrementOp() const
Definition: Expr.h:2336
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4346
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3197
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3936
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1617
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition: ExprCXX.cpp:1579
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition: ExprCXX.h:637
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4719
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:707
void setType(QualType newType)
Definition: Decl.h:719
QualType getType() const
Definition: Decl.h:718
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5369
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3324
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:919
bool hasInit() const
Definition: Decl.cpp:2399
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2258
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1271
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1214
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2467
const Expr * getInit() const
Definition: Decl.h:1356
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2880
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1532
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1205
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1172
@ TLS_None
Not a TLS variable.
Definition: Decl.h:939
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1283
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2376
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2509
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2781
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1250
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2760
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2871
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3759
Expr * getSizeExpr() const
Definition: Type.h:3778
Represents a GCC generic vector type.
Definition: Type.h:3981
unsigned getNumElements() const
Definition: Type.h:3996
VectorKind getVectorKind() const
Definition: Type.h:4001
QualType getElementType() const
Definition: Type.h:3995
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:784
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition: ScopeInfo.h:790
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:794
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:668
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
bool isNested() const
Definition: ScopeInfo.h:659
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
Retains information about a captured region.
Definition: ScopeInfo.h:810
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:825
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:765
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition: ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:752
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:228
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:251
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition: ScopeInfo.h:989
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:995
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
Defines the clang::TargetInfo interface.
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
constexpr Variable var(Literal L)
Returns the variable of L.
Definition: CNFFormula.h:64
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
static Base getBase(const StringRef IntegerLiteral)
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: Integral.h:29
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1903
bool InitField(InterpState &S, CodePtr OpPC, uint32_t I)
1) Pops the value from the stack 2) Peeks a pointer from the stack 3) Pushes the value to field I of ...
Definition: Interp.h:1183
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1717
std::string toString(const til::SExpr *E)
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isa(CodeGen::Address addr)
Definition: Address.h:294
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ GVA_StrongExternal
Definition: Linkage.h:76
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
CUDAFunctionTarget
Definition: Cuda.h:132
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:333
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:146
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:154
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:166
BinaryOperatorKind
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Extern
Definition: Specifiers.h:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
ExprResult ExprEmpty()
Definition: Ownership.h:271
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
@ AR_Unavailable
Definition: DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
StringLiteralKind
Definition: Expr.h:1744
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecVector
is AltiVec vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Neon
is ARM Neon vector
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
SourceLocIdentKind
Definition: Expr.h:4766
@ None
No keyword precedes the qualified type name.
void runWithSufficientStackSpace(llvm::function_ref< void()> Diag, llvm::function_ref< void()> Fn)
Run a given function on a stack with "sufficient" space.
Definition: Stack.h:40
@ Other
Other implicit parameter.
PredefinedIdentKind
Definition: Expr.h:1970
@ Implicit
An implicit conversion.
CharacterLiteralKind
Definition: Expr.h:1584
@ AS_none
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:170
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:180
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:174
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:172
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:177
unsigned long uint64_t
long int64_t
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5579
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5576
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5563
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5571
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5570
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5556
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5521
bool VisitCXXConstructExpr(CXXConstructExpr *E)
Definition: SemaExpr.cpp:5527
const ASTContext & Context
Definition: SemaExpr.cpp:5515
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5548
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5552
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5537
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5519
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5516
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:4747
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4748
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:5168
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:5202
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:5248
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:5207
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition: Sema.h:5215
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:5211
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:5221
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition: Sema.h:5187
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:5225
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:5173
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:5181
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:5170
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:5177
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6499
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:156