clang  17.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"
39 #include "clang/Lex/Preprocessor.h"
41 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/Designator.h"
45 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Overload.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
52 #include "clang/Sema/Template.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TypeSize.h"
59 #include <optional>
60 
61 using namespace clang;
62 using namespace sema;
63 
64 /// Determine whether the use of this declaration is valid, without
65 /// emitting diagnostics.
66 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
67  // See if this is an auto-typed variable whose initializer we are parsing.
68  if (ParsingInitForAutoVars.count(D))
69  return false;
70 
71  // See if this is a deleted function.
72  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73  if (FD->isDeleted())
74  return false;
75 
76  // If the function has a deduced return type, and we can't deduce it,
77  // then we can't use it either.
78  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
79  DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
80  return false;
81 
82  // See if this is an aligned allocation/deallocation function that is
83  // unavailable.
84  if (TreatUnavailableAsInvalid &&
85  isUnavailableAlignedAllocationFunction(*FD))
86  return false;
87  }
88 
89  // See if this function is unavailable.
90  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
91  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
92  return false;
93 
94  if (isa<UnresolvedUsingIfExistsDecl>(D))
95  return false;
96 
97  return true;
98 }
99 
101  // Warn if this is used but marked unused.
102  if (const auto *A = D->getAttr<UnusedAttr>()) {
103  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
104  // should diagnose them.
105  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
106  A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
107  const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
108  if (DC && !DC->hasAttr<UnusedAttr>())
109  S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
110  }
111  }
112 }
113 
114 /// Emit a note explaining that this function is deleted.
116  assert(Decl && Decl->isDeleted());
117 
118  if (Decl->isDefaulted()) {
119  // If the method was explicitly defaulted, point at that declaration.
120  if (!Decl->isImplicit())
121  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
122 
123  // Try to diagnose why this special member function was implicitly
124  // deleted. This might fail, if that reason no longer applies.
125  DiagnoseDeletedDefaultedFunction(Decl);
126  return;
127  }
128 
129  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
130  if (Ctor && Ctor->isInheritingConstructor())
131  return NoteDeletedInheritingConstructor(Ctor);
132 
133  Diag(Decl->getLocation(), diag::note_availability_specified_here)
134  << Decl << 1;
135 }
136 
137 /// Determine whether a FunctionDecl was ever declared with an
138 /// explicit storage class.
140  for (auto *I : D->redecls()) {
141  if (I->getStorageClass() != SC_None)
142  return true;
143  }
144  return false;
145 }
146 
147 /// Check whether we're in an extern inline function and referring to a
148 /// variable or function with internal linkage (C11 6.7.4p3).
149 ///
150 /// This is only a warning because we used to silently accept this code, but
151 /// in many cases it will not behave correctly. This is not enabled in C++ mode
152 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
153 /// and so while there may still be user mistakes, most of the time we can't
154 /// prove that there are errors.
156  const NamedDecl *D,
157  SourceLocation Loc) {
158  // This is disabled under C++; there are too many ways for this to fire in
159  // contexts where the warning is a false positive, or where it is technically
160  // correct but benign.
161  if (S.getLangOpts().CPlusPlus)
162  return;
163 
164  // Check if this is an inlined function or method.
165  FunctionDecl *Current = S.getCurFunctionDecl();
166  if (!Current)
167  return;
168  if (!Current->isInlined())
169  return;
170  if (!Current->isExternallyVisible())
171  return;
172 
173  // Check if the decl has internal linkage.
174  if (D->getFormalLinkage() != InternalLinkage)
175  return;
176 
177  // Downgrade from ExtWarn to Extension if
178  // (1) the supposedly external inline function is in the main file,
179  // and probably won't be included anywhere else.
180  // (2) the thing we're referencing is a pure function.
181  // (3) the thing we're referencing is another inline function.
182  // This last can give us false negatives, but it's better than warning on
183  // wrappers for simple C library functions.
184  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
185  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
186  if (!DowngradeWarning && UsedFn)
187  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
188 
189  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
190  : diag::ext_internal_in_extern_inline)
191  << /*IsVar=*/!UsedFn << D;
192 
194 
195  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
196  << D;
197 }
198 
200  const FunctionDecl *First = Cur->getFirstDecl();
201 
202  // Suggest "static" on the function, if possible.
204  SourceLocation DeclBegin = First->getSourceRange().getBegin();
205  Diag(DeclBegin, diag::note_convert_inline_to_static)
206  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
207  }
208 }
209 
210 /// Determine whether the use of this declaration is valid, and
211 /// emit any corresponding diagnostics.
212 ///
213 /// This routine diagnoses various problems with referencing
214 /// declarations that can occur when using a declaration. For example,
215 /// it might warn if a deprecated or unavailable declaration is being
216 /// used, or produce an error (and return true) if a C++0x deleted
217 /// function is being used.
218 ///
219 /// \returns true if there was an error (this declaration cannot be
220 /// referenced), false otherwise.
221 ///
223  const ObjCInterfaceDecl *UnknownObjCClass,
224  bool ObjCPropertyAccess,
225  bool AvoidPartialAvailabilityChecks,
226  ObjCInterfaceDecl *ClassReceiver,
227  bool SkipTrailingRequiresClause) {
228  SourceLocation Loc = Locs.front();
229  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
230  // If there were any diagnostics suppressed by template argument deduction,
231  // emit them now.
232  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
233  if (Pos != SuppressedDiagnostics.end()) {
234  for (const PartialDiagnosticAt &Suppressed : Pos->second)
235  Diag(Suppressed.first, Suppressed.second);
236 
237  // Clear out the list of suppressed diagnostics, so that we don't emit
238  // them again for this specialization. However, we don't obsolete this
239  // entry from the table, because we want to avoid ever emitting these
240  // diagnostics again.
241  Pos->second.clear();
242  }
243 
244  // C++ [basic.start.main]p3:
245  // The function 'main' shall not be used within a program.
246  if (cast<FunctionDecl>(D)->isMain())
247  Diag(Loc, diag::ext_main_used);
248 
249  diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
250  }
251 
252  // See if this is an auto-typed variable whose initializer we are parsing.
253  if (ParsingInitForAutoVars.count(D)) {
254  if (isa<BindingDecl>(D)) {
255  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
256  << D->getDeclName();
257  } else {
258  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
259  << D->getDeclName() << cast<VarDecl>(D)->getType();
260  }
261  return true;
262  }
263 
264  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265  // See if this is a deleted function.
266  if (FD->isDeleted()) {
267  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
268  if (Ctor && Ctor->isInheritingConstructor())
269  Diag(Loc, diag::err_deleted_inherited_ctor_use)
270  << Ctor->getParent()
271  << Ctor->getInheritedConstructor().getConstructor()->getParent();
272  else
273  Diag(Loc, diag::err_deleted_function_use);
274  NoteDeletedFunction(FD);
275  return true;
276  }
277 
278  // [expr.prim.id]p4
279  // A program that refers explicitly or implicitly to a function with a
280  // trailing requires-clause whose constraint-expression is not satisfied,
281  // other than to declare it, is ill-formed. [...]
282  //
283  // See if this is a function with constraints that need to be satisfied.
284  // Check this before deducing the return type, as it might instantiate the
285  // definition.
286  if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
287  ConstraintSatisfaction Satisfaction;
288  if (CheckFunctionConstraints(FD, Satisfaction, Loc,
289  /*ForOverloadResolution*/ true))
290  // A diagnostic will have already been generated (non-constant
291  // constraint expression, for example)
292  return true;
293  if (!Satisfaction.IsSatisfied) {
294  Diag(Loc,
295  diag::err_reference_to_function_with_unsatisfied_constraints)
296  << D;
297  DiagnoseUnsatisfiedConstraint(Satisfaction);
298  return true;
299  }
300  }
301 
302  // If the function has a deduced return type, and we can't deduce it,
303  // then we can't use it either.
304  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
305  DeduceReturnType(FD, Loc))
306  return true;
307 
308  if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
309  return true;
310 
311  if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
312  return true;
313  }
314 
315  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
316  // Lambdas are only default-constructible or assignable in C++2a onwards.
317  if (MD->getParent()->isLambda() &&
318  ((isa<CXXConstructorDecl>(MD) &&
319  cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
320  MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
321  Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
322  << !isa<CXXConstructorDecl>(MD);
323  }
324  }
325 
326  auto getReferencedObjCProp = [](const NamedDecl *D) ->
327  const ObjCPropertyDecl * {
328  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
329  return MD->findPropertyDecl();
330  return nullptr;
331  };
332  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
334  return true;
335  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
336  return true;
337  }
338 
339  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340  // Only the variables omp_in and omp_out are allowed in the combiner.
341  // Only the variables omp_priv and omp_orig are allowed in the
342  // initializer-clause.
343  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
344  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
345  isa<VarDecl>(D)) {
346  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347  << getCurFunction()->HasOMPDeclareReductionCombiner;
348  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
349  return true;
350  }
351 
352  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353  // List-items in map clauses on this construct may only refer to the declared
354  // variable var and entities that could be referenced by a procedure defined
355  // at the same location.
356  // [OpenMP 5.2] Also allow iterator declared variables.
357  if (LangOpts.OpenMP && isa<VarDecl>(D) &&
358  !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
359  Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360  << getOpenMPDeclareMapperVarName();
361  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362  return true;
363  }
364 
365  if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
366  Diag(Loc, diag::err_use_of_empty_using_if_exists);
367  Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
368  return true;
369  }
370 
371  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
372  AvoidPartialAvailabilityChecks, ClassReceiver);
373 
374  DiagnoseUnusedOfDecl(*this, D, Loc);
375 
377 
378  if (auto *VD = dyn_cast<ValueDecl>(D))
379  checkTypeSupport(VD->getType(), Loc, VD);
380 
381  if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
382  if (!Context.getTargetInfo().isTLSSupported())
383  if (const auto *VD = dyn_cast<VarDecl>(D))
384  if (VD->getTLSKind() != VarDecl::TLS_None)
385  targetDiag(*Locs.begin(), diag::err_thread_unsupported);
386  }
387 
388  if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
389  !isUnevaluatedContext()) {
390  // C++ [expr.prim.req.nested] p3
391  // A local parameter shall only appear as an unevaluated operand
392  // (Clause 8) within the constraint-expression.
393  Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
394  << D;
395  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
396  return true;
397  }
398 
399  return false;
400 }
401 
402 /// DiagnoseSentinelCalls - This routine checks whether a call or
403 /// message-send is to a declaration with the sentinel attribute, and
404 /// if so, it checks that the requirements of the sentinel are
405 /// satisfied.
407  ArrayRef<Expr *> Args) {
408  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
409  if (!attr)
410  return;
411 
412  // The number of formal parameters of the declaration.
413  unsigned numFormalParams;
414 
415  // The kind of declaration. This is also an index into a %select in
416  // the diagnostic.
417  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
418 
419  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
420  numFormalParams = MD->param_size();
421  calleeType = CT_Method;
422  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
423  numFormalParams = FD->param_size();
424  calleeType = CT_Function;
425  } else if (isa<VarDecl>(D)) {
426  QualType type = cast<ValueDecl>(D)->getType();
427  const FunctionType *fn = nullptr;
428  if (const PointerType *ptr = type->getAs<PointerType>()) {
429  fn = ptr->getPointeeType()->getAs<FunctionType>();
430  if (!fn) return;
431  calleeType = CT_Function;
432  } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
433  fn = ptr->getPointeeType()->castAs<FunctionType>();
434  calleeType = CT_Block;
435  } else {
436  return;
437  }
438 
439  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
440  numFormalParams = proto->getNumParams();
441  } else {
442  numFormalParams = 0;
443  }
444  } else {
445  return;
446  }
447 
448  // "nullPos" is the number of formal parameters at the end which
449  // effectively count as part of the variadic arguments. This is
450  // useful if you would prefer to not have *any* formal parameters,
451  // but the language forces you to have at least one.
452  unsigned nullPos = attr->getNullPos();
453  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
454  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
455 
456  // The number of arguments which should follow the sentinel.
457  unsigned numArgsAfterSentinel = attr->getSentinel();
458 
459  // If there aren't enough arguments for all the formal parameters,
460  // the sentinel, and the args after the sentinel, complain.
461  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
462  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
463  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
464  return;
465  }
466 
467  // Otherwise, find the sentinel expression.
468  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
469  if (!sentinelExpr) return;
470  if (sentinelExpr->isValueDependent()) return;
471  if (Context.isSentinelNullExpr(sentinelExpr)) return;
472 
473  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
474  // or 'NULL' if those are actually defined in the context. Only use
475  // 'nil' for ObjC methods, where it's much more likely that the
476  // variadic arguments form a list of object pointers.
477  SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
478  std::string NullValue;
479  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
480  NullValue = "nil";
481  else if (getLangOpts().CPlusPlus11)
482  NullValue = "nullptr";
483  else if (PP.isMacroDefined("NULL"))
484  NullValue = "NULL";
485  else
486  NullValue = "(void*) 0";
487 
488  if (MissingNilLoc.isInvalid())
489  Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
490  else
491  Diag(MissingNilLoc, diag::warn_missing_sentinel)
492  << int(calleeType)
493  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
494  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
495 }
496 
498  return E ? E->getSourceRange() : SourceRange();
499 }
500 
501 //===----------------------------------------------------------------------===//
502 // Standard Promotions and Conversions
503 //===----------------------------------------------------------------------===//
504 
505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
507  // Handle any placeholder expressions which made it here.
508  if (E->hasPlaceholderType()) {
509  ExprResult result = CheckPlaceholderExpr(E);
510  if (result.isInvalid()) return ExprError();
511  E = result.get();
512  }
513 
514  QualType Ty = E->getType();
515  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
516 
517  if (Ty->isFunctionType()) {
518  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
519  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
520  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
521  return ExprError();
522 
523  E = ImpCastExprToType(E, Context.getPointerType(Ty),
524  CK_FunctionToPointerDecay).get();
525  } else if (Ty->isArrayType()) {
526  // In C90 mode, arrays only promote to pointers if the array expression is
527  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
528  // type 'array of type' is converted to an expression that has type 'pointer
529  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
530  // that has type 'array of type' ...". The relevant change is "an lvalue"
531  // (C90) to "an expression" (C99).
532  //
533  // C++ 4.2p1:
534  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
535  // T" can be converted to an rvalue of type "pointer to T".
536  //
537  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
538  ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
539  CK_ArrayToPointerDecay);
540  if (Res.isInvalid())
541  return ExprError();
542  E = Res.get();
543  }
544  }
545  return E;
546 }
547 
549  // Check to see if we are dereferencing a null pointer. If so,
550  // and if not volatile-qualified, this is undefined behavior that the
551  // optimizer will delete, so warn about it. People sometimes try to use this
552  // to get a deterministic trap and are surprised by clang's behavior. This
553  // only handles the pattern "*null", which is a very syntactic check.
554  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
555  if (UO && UO->getOpcode() == UO_Deref &&
556  UO->getSubExpr()->getType()->isPointerType()) {
557  const LangAS AS =
558  UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
559  if ((!isTargetAddressSpace(AS) ||
560  (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
561  UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
563  !UO->getType().isVolatileQualified()) {
564  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
565  S.PDiag(diag::warn_indirection_through_null)
566  << UO->getSubExpr()->getSourceRange());
567  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568  S.PDiag(diag::note_indirection_through_null));
569  }
570  }
571 }
572 
573 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
574  SourceLocation AssignLoc,
575  const Expr* RHS) {
576  const ObjCIvarDecl *IV = OIRE->getDecl();
577  if (!IV)
578  return;
579 
580  DeclarationName MemberName = IV->getDeclName();
581  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
582  if (!Member || !Member->isStr("isa"))
583  return;
584 
585  const Expr *Base = OIRE->getBase();
586  QualType BaseType = Base->getType();
587  if (OIRE->isArrow())
588  BaseType = BaseType->getPointeeType();
589  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
590  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
591  ObjCInterfaceDecl *ClassDeclared = nullptr;
592  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
593  if (!ClassDeclared->getSuperClass()
594  && (*ClassDeclared->ivar_begin()) == IV) {
595  if (RHS) {
596  NamedDecl *ObjectSetClass =
598  &S.Context.Idents.get("object_setClass"),
600  if (ObjectSetClass) {
601  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
602  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
604  "object_setClass(")
606  SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
607  << FixItHint::CreateInsertion(RHSLocEnd, ")");
608  }
609  else
610  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
611  } else {
612  NamedDecl *ObjectGetClass =
614  &S.Context.Idents.get("object_getClass"),
616  if (ObjectGetClass)
617  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
619  "object_getClass(")
621  SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
622  else
623  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
624  }
625  S.Diag(IV->getLocation(), diag::note_ivar_decl);
626  }
627  }
628 }
629 
631  // Handle any placeholder expressions which made it here.
632  if (E->hasPlaceholderType()) {
633  ExprResult result = CheckPlaceholderExpr(E);
634  if (result.isInvalid()) return ExprError();
635  E = result.get();
636  }
637 
638  // C++ [conv.lval]p1:
639  // A glvalue of a non-function, non-array type T can be
640  // converted to a prvalue.
641  if (!E->isGLValue()) return E;
642 
643  QualType T = E->getType();
644  assert(!T.isNull() && "r-value conversion on typeless expression?");
645 
646  // lvalue-to-rvalue conversion cannot be applied to function or array types.
647  if (T->isFunctionType() || T->isArrayType())
648  return E;
649 
650  // We don't want to throw lvalue-to-rvalue casts on top of
651  // expressions of certain types in C++.
652  if (getLangOpts().CPlusPlus &&
653  (E->getType() == Context.OverloadTy ||
654  T->isDependentType() ||
655  T->isRecordType()))
656  return E;
657 
658  // The C standard is actually really unclear on this point, and
659  // DR106 tells us what the result should be but not why. It's
660  // generally best to say that void types just doesn't undergo
661  // lvalue-to-rvalue at all. Note that expressions of unqualified
662  // 'void' type are never l-values, but qualified void can be.
663  if (T->isVoidType())
664  return E;
665 
666  // OpenCL usually rejects direct accesses to values of 'half' type.
667  if (getLangOpts().OpenCL &&
668  !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
669  T->isHalfType()) {
670  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
671  << 0 << T;
672  return ExprError();
673  }
674 
676  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
677  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
678  &Context.Idents.get("object_getClass"),
679  SourceLocation(), LookupOrdinaryName);
680  if (ObjectGetClass)
681  Diag(E->getExprLoc(), diag::warn_objc_isa_use)
682  << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
684  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
685  else
686  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
687  }
688  else if (const ObjCIvarRefExpr *OIRE =
689  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
690  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
691 
692  // C++ [conv.lval]p1:
693  // [...] If T is a non-class type, the type of the prvalue is the
694  // cv-unqualified version of T. Otherwise, the type of the
695  // rvalue is T.
696  //
697  // C99 6.3.2.1p2:
698  // If the lvalue has qualified type, the value has the unqualified
699  // version of the type of the lvalue; otherwise, the value has the
700  // type of the lvalue.
701  if (T.hasQualifiers())
702  T = T.getUnqualifiedType();
703 
704  // Under the MS ABI, lock down the inheritance model now.
705  if (T->isMemberPointerType() &&
706  Context.getTargetInfo().getCXXABI().isMicrosoft())
707  (void)isCompleteType(E->getExprLoc(), T);
708 
709  ExprResult Res = CheckLValueToRValueConversionOperand(E);
710  if (Res.isInvalid())
711  return Res;
712  E = Res.get();
713 
714  // Loading a __weak object implicitly retains the value, so we need a cleanup to
715  // balance that.
717  Cleanup.setExprNeedsCleanups(true);
718 
720  Cleanup.setExprNeedsCleanups(true);
721 
722  // C++ [conv.lval]p3:
723  // If T is cv std::nullptr_t, the result is a null pointer constant.
724  CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
725  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
726  CurFPFeatureOverrides());
727 
728  // C11 6.3.2.1p2:
729  // ... if the lvalue has atomic type, the value has the non-atomic version
730  // of the type of the lvalue ...
731  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
732  T = Atomic->getValueType().getUnqualifiedType();
733  Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
734  nullptr, VK_PRValue, FPOptionsOverride());
735  }
736 
737  return Res;
738 }
739 
741  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
742  if (Res.isInvalid())
743  return ExprError();
744  Res = DefaultLvalueConversion(Res.get());
745  if (Res.isInvalid())
746  return ExprError();
747  return Res;
748 }
749 
750 /// CallExprUnaryConversions - a special case of an unary conversion
751 /// performed on a function designator of a call expression.
753  QualType Ty = E->getType();
754  ExprResult Res = E;
755  // Only do implicit cast for a function type, but not for a pointer
756  // to function type.
757  if (Ty->isFunctionType()) {
758  Res = ImpCastExprToType(E, Context.getPointerType(Ty),
759  CK_FunctionToPointerDecay);
760  if (Res.isInvalid())
761  return ExprError();
762  }
763  Res = DefaultLvalueConversion(Res.get());
764  if (Res.isInvalid())
765  return ExprError();
766  return Res.get();
767 }
768 
769 /// UsualUnaryConversions - Performs various conversions that are common to most
770 /// operators (C99 6.3). The conversions of array and function types are
771 /// sometimes suppressed. For example, the array->pointer conversion doesn't
772 /// apply if the array is an argument to the sizeof or address (&) operators.
773 /// In these instances, this routine should *not* be called.
775  // First, convert to an r-value.
776  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
777  if (Res.isInvalid())
778  return ExprError();
779  E = Res.get();
780 
781  QualType Ty = E->getType();
782  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
783 
784  LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
785  if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
786  (getLangOpts().getFPEvalMethod() !=
787  LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
788  PP.getLastFPEvalPragmaLocation().isValid())) {
789  switch (EvalMethod) {
790  default:
791  llvm_unreachable("Unrecognized float evaluation method");
792  break;
794  llvm_unreachable("Float evaluation method should be set by now");
795  break;
797  if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
798  // Widen the expression to double.
799  return Ty->isComplexType()
800  ? ImpCastExprToType(E,
801  Context.getComplexType(Context.DoubleTy),
802  CK_FloatingComplexCast)
803  : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
804  break;
806  if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
807  // Widen the expression to long double.
808  return Ty->isComplexType()
809  ? ImpCastExprToType(
810  E, Context.getComplexType(Context.LongDoubleTy),
811  CK_FloatingComplexCast)
812  : ImpCastExprToType(E, Context.LongDoubleTy,
813  CK_FloatingCast);
814  break;
815  }
816  }
817 
818  // Half FP have to be promoted to float unless it is natively supported
819  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
820  return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
821 
822  // Try to perform integral promotions if the object has a theoretically
823  // promotable type.
825  // C99 6.3.1.1p2:
826  //
827  // The following may be used in an expression wherever an int or
828  // unsigned int may be used:
829  // - an object or expression with an integer type whose integer
830  // conversion rank is less than or equal to the rank of int
831  // and unsigned int.
832  // - A bit-field of type _Bool, int, signed int, or unsigned int.
833  //
834  // If an int can represent all values of the original type, the
835  // value is converted to an int; otherwise, it is converted to an
836  // unsigned int. These are called the integer promotions. All
837  // other types are unchanged by the integer promotions.
838 
839  QualType PTy = Context.isPromotableBitField(E);
840  if (!PTy.isNull()) {
841  E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
842  return E;
843  }
844  if (Context.isPromotableIntegerType(Ty)) {
845  QualType PT = Context.getPromotedIntegerType(Ty);
846  E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
847  return E;
848  }
849  }
850  return E;
851 }
852 
853 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
854 /// do not have a prototype. Arguments that have type float or __fp16
855 /// are promoted to double. All other argument types are converted by
856 /// UsualUnaryConversions().
858  QualType Ty = E->getType();
859  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
860 
861  ExprResult Res = UsualUnaryConversions(E);
862  if (Res.isInvalid())
863  return ExprError();
864  E = Res.get();
865 
866  // If this is a 'float' or '__fp16' (CVR qualified or typedef)
867  // promote to double.
868  // Note that default argument promotion applies only to float (and
869  // half/fp16); it does not apply to _Float16.
870  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
871  if (BTy && (BTy->getKind() == BuiltinType::Half ||
872  BTy->getKind() == BuiltinType::Float)) {
873  if (getLangOpts().OpenCL &&
874  !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
875  if (BTy->getKind() == BuiltinType::Half) {
876  E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
877  }
878  } else {
879  E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
880  }
881  }
882  if (BTy &&
883  getLangOpts().getExtendIntArgs() ==
885  Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
886  Context.getTypeSizeInChars(BTy) <
887  Context.getTypeSizeInChars(Context.LongLongTy)) {
888  E = (Ty->isUnsignedIntegerType())
889  ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
890  .get()
891  : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
892  assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
893  "Unexpected typesize for LongLongTy");
894  }
895 
896  // C++ performs lvalue-to-rvalue conversion as a default argument
897  // promotion, even on class types, but note:
898  // C++11 [conv.lval]p2:
899  // When an lvalue-to-rvalue conversion occurs in an unevaluated
900  // operand or a subexpression thereof the value contained in the
901  // referenced object is not accessed. Otherwise, if the glvalue
902  // has a class type, the conversion copy-initializes a temporary
903  // of type T from the glvalue and the result of the conversion
904  // is a prvalue for the temporary.
905  // FIXME: add some way to gate this entire thing for correctness in
906  // potentially potentially evaluated contexts.
907  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
908  ExprResult Temp = PerformCopyInitialization(
910  E->getExprLoc(), E);
911  if (Temp.isInvalid())
912  return ExprError();
913  E = Temp.get();
914  }
915 
916  return E;
917 }
918 
919 /// Determine the degree of POD-ness for an expression.
920 /// Incomplete types are considered POD, since this check can be performed
921 /// when we're in an unevaluated context.
923  if (Ty->isIncompleteType()) {
924  // C++11 [expr.call]p7:
925  // After these conversions, if the argument does not have arithmetic,
926  // enumeration, pointer, pointer to member, or class type, the program
927  // is ill-formed.
928  //
929  // Since we've already performed array-to-pointer and function-to-pointer
930  // decay, the only such type in C++ is cv void. This also handles
931  // initializer lists as variadic arguments.
932  if (Ty->isVoidType())
933  return VAK_Invalid;
934 
935  if (Ty->isObjCObjectType())
936  return VAK_Invalid;
937  return VAK_Valid;
938  }
939 
941  return VAK_Invalid;
942 
943  if (Ty.isCXX98PODType(Context))
944  return VAK_Valid;
945 
946  // C++11 [expr.call]p7:
947  // Passing a potentially-evaluated argument of class type (Clause 9)
948  // having a non-trivial copy constructor, a non-trivial move constructor,
949  // or a non-trivial destructor, with no corresponding parameter,
950  // is conditionally-supported with implementation-defined semantics.
951  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
952  if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
953  if (!Record->hasNonTrivialCopyConstructor() &&
954  !Record->hasNonTrivialMoveConstructor() &&
955  !Record->hasNonTrivialDestructor())
956  return VAK_ValidInCXX11;
957 
958  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
959  return VAK_Valid;
960 
961  if (Ty->isObjCObjectType())
962  return VAK_Invalid;
963 
964  if (getLangOpts().MSVCCompat)
965  return VAK_MSVCUndefined;
966 
967  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
968  // permitted to reject them. We should consider doing so.
969  return VAK_Undefined;
970 }
971 
973  // Don't allow one to pass an Objective-C interface to a vararg.
974  const QualType &Ty = E->getType();
975  VarArgKind VAK = isValidVarArgType(Ty);
976 
977  // Complain about passing non-POD types through varargs.
978  switch (VAK) {
979  case VAK_ValidInCXX11:
980  DiagRuntimeBehavior(
981  E->getBeginLoc(), nullptr,
982  PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
983  [[fallthrough]];
984  case VAK_Valid:
985  if (Ty->isRecordType()) {
986  // This is unlikely to be what the user intended. If the class has a
987  // 'c_str' member function, the user probably meant to call that.
988  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
989  PDiag(diag::warn_pass_class_arg_to_vararg)
990  << Ty << CT << hasCStrMethod(E) << ".c_str()");
991  }
992  break;
993 
994  case VAK_Undefined:
995  case VAK_MSVCUndefined:
996  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
997  PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
998  << getLangOpts().CPlusPlus11 << Ty << CT);
999  break;
1000 
1001  case VAK_Invalid:
1003  Diag(E->getBeginLoc(),
1004  diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1005  << Ty << CT;
1006  else if (Ty->isObjCObjectType())
1007  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1008  PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1009  << Ty << CT);
1010  else
1011  Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1012  << isa<InitListExpr>(E) << Ty << CT;
1013  break;
1014  }
1015 }
1016 
1017 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1018 /// will create a trap if the resulting type is not a POD type.
1020  FunctionDecl *FDecl) {
1021  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1022  // Strip the unbridged-cast placeholder expression off, if applicable.
1023  if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1024  (CT == VariadicMethod ||
1025  (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1026  E = stripARCUnbridgedCast(E);
1027 
1028  // Otherwise, do normal placeholder checking.
1029  } else {
1030  ExprResult ExprRes = CheckPlaceholderExpr(E);
1031  if (ExprRes.isInvalid())
1032  return ExprError();
1033  E = ExprRes.get();
1034  }
1035  }
1036 
1037  ExprResult ExprRes = DefaultArgumentPromotion(E);
1038  if (ExprRes.isInvalid())
1039  return ExprError();
1040 
1041  // Copy blocks to the heap.
1042  if (ExprRes.get()->getType()->isBlockPointerType())
1043  maybeExtendBlockObject(ExprRes);
1044 
1045  E = ExprRes.get();
1046 
1047  // Diagnostics regarding non-POD argument types are
1048  // emitted along with format string checking in Sema::CheckFunctionCall().
1049  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1050  // Turn this into a trap.
1051  CXXScopeSpec SS;
1052  SourceLocation TemplateKWLoc;
1053  UnqualifiedId Name;
1054  Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1055  E->getBeginLoc());
1056  ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1057  /*HasTrailingLParen=*/true,
1058  /*IsAddressOfOperand=*/false);
1059  if (TrapFn.isInvalid())
1060  return ExprError();
1061 
1062  ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1063  std::nullopt, E->getEndLoc());
1064  if (Call.isInvalid())
1065  return ExprError();
1066 
1067  ExprResult Comma =
1068  ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1069  if (Comma.isInvalid())
1070  return ExprError();
1071  return Comma.get();
1072  }
1073 
1074  if (!getLangOpts().CPlusPlus &&
1075  RequireCompleteType(E->getExprLoc(), E->getType(),
1076  diag::err_call_incomplete_argument))
1077  return ExprError();
1078 
1079  return E;
1080 }
1081 
1082 /// Converts an integer to complex float type. Helper function of
1083 /// UsualArithmeticConversions()
1084 ///
1085 /// \return false if the integer expression is an integer type and is
1086 /// successfully converted to the complex type.
1088  ExprResult &ComplexExpr,
1089  QualType IntTy,
1090  QualType ComplexTy,
1091  bool SkipCast) {
1092  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1093  if (SkipCast) return false;
1094  if (IntTy->isIntegerType()) {
1095  QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1096  IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1097  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098  CK_FloatingRealToComplex);
1099  } else {
1100  assert(IntTy->isComplexIntegerType());
1101  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1102  CK_IntegralComplexToFloatingComplex);
1103  }
1104  return false;
1105 }
1106 
1107 // This handles complex/complex, complex/float, or float/complex.
1108 // When both operands are complex, the shorter operand is converted to the
1109 // type of the longer, and that is the type of the result. This corresponds
1110 // to what is done when combining two real floating-point operands.
1111 // The fun begins when size promotion occur across type domains.
1112 // From H&S 6.3.4: When one operand is complex and the other is a real
1113 // floating-point type, the less precise type is converted, within it's
1114 // real or complex domain, to the precision of the other type. For example,
1115 // when combining a "long double" with a "double _Complex", the
1116 // "double _Complex" is promoted to "long double _Complex".
1118  QualType ShorterType,
1119  QualType LongerType,
1120  bool PromotePrecision) {
1121  bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1122  QualType Result =
1123  LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1124 
1125  if (PromotePrecision) {
1126  if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1127  Shorter =
1128  S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1129  } else {
1130  if (LongerIsComplex)
1131  LongerType = LongerType->castAs<ComplexType>()->getElementType();
1132  Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1133  }
1134  }
1135  return Result;
1136 }
1137 
1138 /// Handle arithmetic conversion with complex types. Helper function of
1139 /// UsualArithmeticConversions()
1141  ExprResult &RHS, QualType LHSType,
1142  QualType RHSType, bool IsCompAssign) {
1143  // if we have an integer operand, the result is the complex type.
1144  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1145  /*SkipCast=*/false))
1146  return LHSType;
1147  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1148  /*SkipCast=*/IsCompAssign))
1149  return RHSType;
1150 
1151  // Compute the rank of the two types, regardless of whether they are complex.
1152  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1153  if (Order < 0)
1154  // Promote the precision of the LHS if not an assignment.
1155  return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1156  /*PromotePrecision=*/!IsCompAssign);
1157  // Promote the precision of the RHS unless it is already the same as the LHS.
1158  return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1159  /*PromotePrecision=*/Order > 0);
1160 }
1161 
1162 /// Handle arithmetic conversion from integer to float. Helper function
1163 /// of UsualArithmeticConversions()
1165  ExprResult &IntExpr,
1166  QualType FloatTy, QualType IntTy,
1167  bool ConvertFloat, bool ConvertInt) {
1168  if (IntTy->isIntegerType()) {
1169  if (ConvertInt)
1170  // Convert intExpr to the lhs floating point type.
1171  IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1172  CK_IntegralToFloating);
1173  return FloatTy;
1174  }
1175 
1176  // Convert both sides to the appropriate complex float.
1177  assert(IntTy->isComplexIntegerType());
1178  QualType result = S.Context.getComplexType(FloatTy);
1179 
1180  // _Complex int -> _Complex float
1181  if (ConvertInt)
1182  IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1183  CK_IntegralComplexToFloatingComplex);
1184 
1185  // float -> _Complex float
1186  if (ConvertFloat)
1187  FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1188  CK_FloatingRealToComplex);
1189 
1190  return result;
1191 }
1192 
1193 /// Handle arithmethic conversion with floating point types. Helper
1194 /// function of UsualArithmeticConversions()
1196  ExprResult &RHS, QualType LHSType,
1197  QualType RHSType, bool IsCompAssign) {
1198  bool LHSFloat = LHSType->isRealFloatingType();
1199  bool RHSFloat = RHSType->isRealFloatingType();
1200 
1201  // N1169 4.1.4: If one of the operands has a floating type and the other
1202  // operand has a fixed-point type, the fixed-point operand
1203  // is converted to the floating type [...]
1204  if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1205  if (LHSFloat)
1206  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1207  else if (!IsCompAssign)
1208  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1209  return LHSFloat ? LHSType : RHSType;
1210  }
1211 
1212  // If we have two real floating types, convert the smaller operand
1213  // to the bigger result.
1214  if (LHSFloat && RHSFloat) {
1215  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1216  if (order > 0) {
1217  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1218  return LHSType;
1219  }
1220 
1221  assert(order < 0 && "illegal float comparison");
1222  if (!IsCompAssign)
1223  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1224  return RHSType;
1225  }
1226 
1227  if (LHSFloat) {
1228  // Half FP has to be promoted to float unless it is natively supported
1229  if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1230  LHSType = S.Context.FloatTy;
1231 
1232  return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1233  /*ConvertFloat=*/!IsCompAssign,
1234  /*ConvertInt=*/ true);
1235  }
1236  assert(RHSFloat);
1237  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1238  /*ConvertFloat=*/ true,
1239  /*ConvertInt=*/!IsCompAssign);
1240 }
1241 
1242 /// Diagnose attempts to convert between __float128, __ibm128 and
1243 /// long double if there is no support for such conversion.
1244 /// Helper function of UsualArithmeticConversions().
1245 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1246  QualType RHSType) {
1247  // No issue if either is not a floating point type.
1248  if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1249  return false;
1250 
1251  // No issue if both have the same 128-bit float semantics.
1252  auto *LHSComplex = LHSType->getAs<ComplexType>();
1253  auto *RHSComplex = RHSType->getAs<ComplexType>();
1254 
1255  QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1256  QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1257 
1258  const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1259  const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1260 
1261  if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1262  &RHSSem != &llvm::APFloat::IEEEquad()) &&
1263  (&LHSSem != &llvm::APFloat::IEEEquad() ||
1264  &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1265  return false;
1266 
1267  return true;
1268 }
1269 
1270 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1271 
1272 namespace {
1273 /// These helper callbacks are placed in an anonymous namespace to
1274 /// permit their use as function template parameters.
1275 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1276  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1277 }
1278 
1279 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1280  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1281  CK_IntegralComplexCast);
1282 }
1283 }
1284 
1285 /// Handle integer arithmetic conversions. Helper function of
1286 /// UsualArithmeticConversions()
1287 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1289  ExprResult &RHS, QualType LHSType,
1290  QualType RHSType, bool IsCompAssign) {
1291  // The rules for this case are in C99 6.3.1.8
1292  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1293  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1294  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1295  if (LHSSigned == RHSSigned) {
1296  // Same signedness; use the higher-ranked type
1297  if (order >= 0) {
1298  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1299  return LHSType;
1300  } else if (!IsCompAssign)
1301  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1302  return RHSType;
1303  } else if (order != (LHSSigned ? 1 : -1)) {
1304  // The unsigned type has greater than or equal rank to the
1305  // signed type, so use the unsigned type
1306  if (RHSSigned) {
1307  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1308  return LHSType;
1309  } else if (!IsCompAssign)
1310  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1311  return RHSType;
1312  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1313  // The two types are different widths; if we are here, that
1314  // means the signed type is larger than the unsigned type, so
1315  // use the signed type.
1316  if (LHSSigned) {
1317  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1318  return LHSType;
1319  } else if (!IsCompAssign)
1320  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1321  return RHSType;
1322  } else {
1323  // The signed type is higher-ranked than the unsigned type,
1324  // but isn't actually any bigger (like unsigned int and long
1325  // on most 32-bit systems). Use the unsigned type corresponding
1326  // to the signed type.
1327  QualType result =
1328  S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1329  RHS = (*doRHSCast)(S, RHS.get(), result);
1330  if (!IsCompAssign)
1331  LHS = (*doLHSCast)(S, LHS.get(), result);
1332  return result;
1333  }
1334 }
1335 
1336 /// Handle conversions with GCC complex int extension. Helper function
1337 /// of UsualArithmeticConversions()
1339  ExprResult &RHS, QualType LHSType,
1340  QualType RHSType,
1341  bool IsCompAssign) {
1342  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1343  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1344 
1345  if (LHSComplexInt && RHSComplexInt) {
1346  QualType LHSEltType = LHSComplexInt->getElementType();
1347  QualType RHSEltType = RHSComplexInt->getElementType();
1348  QualType ScalarType =
1349  handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1350  (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1351 
1352  return S.Context.getComplexType(ScalarType);
1353  }
1354 
1355  if (LHSComplexInt) {
1356  QualType LHSEltType = LHSComplexInt->getElementType();
1357  QualType ScalarType =
1358  handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1359  (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1360  QualType ComplexType = S.Context.getComplexType(ScalarType);
1361  RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1362  CK_IntegralRealToComplex);
1363 
1364  return ComplexType;
1365  }
1366 
1367  assert(RHSComplexInt);
1368 
1369  QualType RHSEltType = RHSComplexInt->getElementType();
1370  QualType ScalarType =
1371  handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1372  (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1373  QualType ComplexType = S.Context.getComplexType(ScalarType);
1374 
1375  if (!IsCompAssign)
1376  LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1377  CK_IntegralRealToComplex);
1378  return ComplexType;
1379 }
1380 
1381 /// Return the rank of a given fixed point or integer type. The value itself
1382 /// doesn't matter, but the values must be increasing with proper increasing
1383 /// rank as described in N1169 4.1.1.
1384 static unsigned GetFixedPointRank(QualType Ty) {
1385  const auto *BTy = Ty->getAs<BuiltinType>();
1386  assert(BTy && "Expected a builtin type.");
1387 
1388  switch (BTy->getKind()) {
1389  case BuiltinType::ShortFract:
1390  case BuiltinType::UShortFract:
1391  case BuiltinType::SatShortFract:
1392  case BuiltinType::SatUShortFract:
1393  return 1;
1394  case BuiltinType::Fract:
1395  case BuiltinType::UFract:
1396  case BuiltinType::SatFract:
1397  case BuiltinType::SatUFract:
1398  return 2;
1399  case BuiltinType::LongFract:
1400  case BuiltinType::ULongFract:
1401  case BuiltinType::SatLongFract:
1402  case BuiltinType::SatULongFract:
1403  return 3;
1404  case BuiltinType::ShortAccum:
1405  case BuiltinType::UShortAccum:
1406  case BuiltinType::SatShortAccum:
1407  case BuiltinType::SatUShortAccum:
1408  return 4;
1409  case BuiltinType::Accum:
1410  case BuiltinType::UAccum:
1411  case BuiltinType::SatAccum:
1412  case BuiltinType::SatUAccum:
1413  return 5;
1414  case BuiltinType::LongAccum:
1415  case BuiltinType::ULongAccum:
1416  case BuiltinType::SatLongAccum:
1417  case BuiltinType::SatULongAccum:
1418  return 6;
1419  default:
1420  if (BTy->isInteger())
1421  return 0;
1422  llvm_unreachable("Unexpected fixed point or integer type");
1423  }
1424 }
1425 
1426 /// handleFixedPointConversion - Fixed point operations between fixed
1427 /// point types and integers or other fixed point types do not fall under
1428 /// usual arithmetic conversion since these conversions could result in loss
1429 /// of precsision (N1169 4.1.4). These operations should be calculated with
1430 /// the full precision of their result type (N1169 4.1.6.2.1).
1432  QualType RHSTy) {
1433  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1434  "Expected at least one of the operands to be a fixed point type");
1435  assert((LHSTy->isFixedPointOrIntegerType() ||
1436  RHSTy->isFixedPointOrIntegerType()) &&
1437  "Special fixed point arithmetic operation conversions are only "
1438  "applied to ints or other fixed point types");
1439 
1440  // If one operand has signed fixed-point type and the other operand has
1441  // unsigned fixed-point type, then the unsigned fixed-point operand is
1442  // converted to its corresponding signed fixed-point type and the resulting
1443  // type is the type of the converted operand.
1444  if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1446  else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1448 
1449  // The result type is the type with the highest rank, whereby a fixed-point
1450  // conversion rank is always greater than an integer conversion rank; if the
1451  // type of either of the operands is a saturating fixedpoint type, the result
1452  // type shall be the saturating fixed-point type corresponding to the type
1453  // with the highest rank; the resulting value is converted (taking into
1454  // account rounding and overflow) to the precision of the resulting type.
1455  // Same ranks between signed and unsigned types are resolved earlier, so both
1456  // types are either signed or both unsigned at this point.
1457  unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1458  unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1459 
1460  QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1461 
1462  if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1463  ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1464 
1465  return ResultTy;
1466 }
1467 
1468 /// Check that the usual arithmetic conversions can be performed on this pair of
1469 /// expressions that might be of enumeration type.
1470 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1471  SourceLocation Loc,
1472  Sema::ArithConvKind ACK) {
1473  // C++2a [expr.arith.conv]p1:
1474  // If one operand is of enumeration type and the other operand is of a
1475  // different enumeration type or a floating-point type, this behavior is
1476  // deprecated ([depr.arith.conv.enum]).
1477  //
1478  // Warn on this in all language modes. Produce a deprecation warning in C++20.
1479  // Eventually we will presumably reject these cases (in C++23 onwards?).
1480  QualType L = LHS->getType(), R = RHS->getType();
1481  bool LEnum = L->isUnscopedEnumerationType(),
1482  REnum = R->isUnscopedEnumerationType();
1483  bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1484  if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1485  (REnum && L->isFloatingType())) {
1486  S.Diag(Loc, S.getLangOpts().CPlusPlus20
1487  ? diag::warn_arith_conv_enum_float_cxx20
1488  : diag::warn_arith_conv_enum_float)
1489  << LHS->getSourceRange() << RHS->getSourceRange()
1490  << (int)ACK << LEnum << L << R;
1491  } else if (!IsCompAssign && LEnum && REnum &&
1492  !S.Context.hasSameUnqualifiedType(L, R)) {
1493  unsigned DiagID;
1494  if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1495  !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1496  // If either enumeration type is unnamed, it's less likely that the
1497  // user cares about this, but this situation is still deprecated in
1498  // C++2a. Use a different warning group.
1499  DiagID = S.getLangOpts().CPlusPlus20
1500  ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1501  : diag::warn_arith_conv_mixed_anon_enum_types;
1502  } else if (ACK == Sema::ACK_Conditional) {
1503  // Conditional expressions are separated out because they have
1504  // historically had a different warning flag.
1505  DiagID = S.getLangOpts().CPlusPlus20
1506  ? diag::warn_conditional_mixed_enum_types_cxx20
1507  : diag::warn_conditional_mixed_enum_types;
1508  } else if (ACK == Sema::ACK_Comparison) {
1509  // Comparison expressions are separated out because they have
1510  // historically had a different warning flag.
1511  DiagID = S.getLangOpts().CPlusPlus20
1512  ? diag::warn_comparison_mixed_enum_types_cxx20
1513  : diag::warn_comparison_mixed_enum_types;
1514  } else {
1515  DiagID = S.getLangOpts().CPlusPlus20
1516  ? diag::warn_arith_conv_mixed_enum_types_cxx20
1517  : diag::warn_arith_conv_mixed_enum_types;
1518  }
1519  S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1520  << (int)ACK << L << R;
1521  }
1522 }
1523 
1524 /// UsualArithmeticConversions - Performs various conversions that are common to
1525 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1526 /// routine returns the first non-arithmetic type found. The client is
1527 /// responsible for emitting appropriate error diagnostics.
1529  SourceLocation Loc,
1530  ArithConvKind ACK) {
1531  checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1532 
1533  if (ACK != ACK_CompAssign) {
1534  LHS = UsualUnaryConversions(LHS.get());
1535  if (LHS.isInvalid())
1536  return QualType();
1537  }
1538 
1539  RHS = UsualUnaryConversions(RHS.get());
1540  if (RHS.isInvalid())
1541  return QualType();
1542 
1543  // For conversion purposes, we ignore any qualifiers.
1544  // For example, "const float" and "float" are equivalent.
1545  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1546  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1547 
1548  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1549  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1550  LHSType = AtomicLHS->getValueType();
1551 
1552  // If both types are identical, no conversion is needed.
1553  if (Context.hasSameType(LHSType, RHSType))
1554  return Context.getCommonSugaredType(LHSType, RHSType);
1555 
1556  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1557  // The caller can deal with this (e.g. pointer + int).
1558  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1559  return QualType();
1560 
1561  // Apply unary and bitfield promotions to the LHS's type.
1562  QualType LHSUnpromotedType = LHSType;
1563  if (Context.isPromotableIntegerType(LHSType))
1564  LHSType = Context.getPromotedIntegerType(LHSType);
1565  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1566  if (!LHSBitfieldPromoteTy.isNull())
1567  LHSType = LHSBitfieldPromoteTy;
1568  if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1569  LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1570 
1571  // If both types are identical, no conversion is needed.
1572  if (Context.hasSameType(LHSType, RHSType))
1573  return Context.getCommonSugaredType(LHSType, RHSType);
1574 
1575  // At this point, we have two different arithmetic types.
1576 
1577  // Diagnose attempts to convert between __ibm128, __float128 and long double
1578  // where such conversions currently can't be handled.
1579  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1580  return QualType();
1581 
1582  // Handle complex types first (C99 6.3.1.8p1).
1583  if (LHSType->isComplexType() || RHSType->isComplexType())
1584  return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1585  ACK == ACK_CompAssign);
1586 
1587  // Now handle "real" floating types (i.e. float, double, long double).
1588  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1589  return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1590  ACK == ACK_CompAssign);
1591 
1592  // Handle GCC complex int extension.
1593  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1594  return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1595  ACK == ACK_CompAssign);
1596 
1597  if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1598  return handleFixedPointConversion(*this, LHSType, RHSType);
1599 
1600  // Finally, we have two differing integer types.
1601  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1602  (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1603 }
1604 
1605 //===----------------------------------------------------------------------===//
1606 // Semantic Analysis for various Expression Types
1607 //===----------------------------------------------------------------------===//
1608 
1609 
1610 ExprResult
1612  SourceLocation DefaultLoc,
1613  SourceLocation RParenLoc,
1614  Expr *ControllingExpr,
1615  ArrayRef<ParsedType> ArgTypes,
1616  ArrayRef<Expr *> ArgExprs) {
1617  unsigned NumAssocs = ArgTypes.size();
1618  assert(NumAssocs == ArgExprs.size());
1619 
1620  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1621  for (unsigned i = 0; i < NumAssocs; ++i) {
1622  if (ArgTypes[i])
1623  (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1624  else
1625  Types[i] = nullptr;
1626  }
1627 
1628  ExprResult ER =
1629  CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr,
1630  llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1631  delete [] Types;
1632  return ER;
1633 }
1634 
1635 ExprResult
1637  SourceLocation DefaultLoc,
1638  SourceLocation RParenLoc,
1639  Expr *ControllingExpr,
1641  ArrayRef<Expr *> Exprs) {
1642  unsigned NumAssocs = Types.size();
1643  assert(NumAssocs == Exprs.size());
1644 
1645  // Decay and strip qualifiers for the controlling expression type, and handle
1646  // placeholder type replacement. See committee discussion from WG14 DR423.
1647  {
1650  ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651  if (R.isInvalid())
1652  return ExprError();
1653  ControllingExpr = R.get();
1654  }
1655 
1656  bool TypeErrorFound = false,
1657  IsResultDependent = ControllingExpr->isTypeDependent(),
1658  ContainsUnexpandedParameterPack
1659  = ControllingExpr->containsUnexpandedParameterPack();
1660 
1661  // The controlling expression is an unevaluated operand, so side effects are
1662  // likely unintended.
1663  if (!inTemplateInstantiation() && !IsResultDependent &&
1664  ControllingExpr->HasSideEffects(Context, false))
1665  Diag(ControllingExpr->getExprLoc(),
1666  diag::warn_side_effects_unevaluated_context);
1667 
1668  for (unsigned i = 0; i < NumAssocs; ++i) {
1669  if (Exprs[i]->containsUnexpandedParameterPack())
1670  ContainsUnexpandedParameterPack = true;
1671 
1672  if (Types[i]) {
1673  if (Types[i]->getType()->containsUnexpandedParameterPack())
1674  ContainsUnexpandedParameterPack = true;
1675 
1676  if (Types[i]->getType()->isDependentType()) {
1677  IsResultDependent = true;
1678  } else {
1679  // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680  // complete object type other than a variably modified type."
1681  unsigned D = 0;
1682  if (Types[i]->getType()->isIncompleteType())
1683  D = diag::err_assoc_type_incomplete;
1684  else if (!Types[i]->getType()->isObjectType())
1685  D = diag::err_assoc_type_nonobject;
1686  else if (Types[i]->getType()->isVariablyModifiedType())
1687  D = diag::err_assoc_type_variably_modified;
1688  else {
1689  // Because the controlling expression undergoes lvalue conversion,
1690  // array conversion, and function conversion, an association which is
1691  // of array type, function type, or is qualified can never be
1692  // reached. We will warn about this so users are less surprised by
1693  // the unreachable association. However, we don't have to handle
1694  // function types; that's not an object type, so it's handled above.
1695  //
1696  // The logic is somewhat different for C++ because C++ has different
1697  // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1698  // If T is a non-class type, the type of the prvalue is the cv-
1699  // unqualified version of T. Otherwise, the type of the prvalue is T.
1700  // The result of these rules is that all qualified types in an
1701  // association in C are unreachable, and in C++, only qualified non-
1702  // class types are unreachable.
1703  unsigned Reason = 0;
1704  QualType QT = Types[i]->getType();
1705  if (QT->isArrayType())
1706  Reason = 1;
1707  else if (QT.hasQualifiers() &&
1708  (!LangOpts.CPlusPlus || !QT->isRecordType()))
1709  Reason = 2;
1710 
1711  if (Reason)
1712  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1713  diag::warn_unreachable_association)
1714  << QT << (Reason - 1);
1715  }
1716 
1717  if (D != 0) {
1718  Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1719  << Types[i]->getTypeLoc().getSourceRange()
1720  << Types[i]->getType();
1721  TypeErrorFound = true;
1722  }
1723 
1724  // C11 6.5.1.1p2 "No two generic associations in the same generic
1725  // selection shall specify compatible types."
1726  for (unsigned j = i+1; j < NumAssocs; ++j)
1727  if (Types[j] && !Types[j]->getType()->isDependentType() &&
1728  Context.typesAreCompatible(Types[i]->getType(),
1729  Types[j]->getType())) {
1730  Diag(Types[j]->getTypeLoc().getBeginLoc(),
1731  diag::err_assoc_compatible_types)
1732  << Types[j]->getTypeLoc().getSourceRange()
1733  << Types[j]->getType()
1734  << Types[i]->getType();
1735  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1736  diag::note_compat_assoc)
1737  << Types[i]->getTypeLoc().getSourceRange()
1738  << Types[i]->getType();
1739  TypeErrorFound = true;
1740  }
1741  }
1742  }
1743  }
1744  if (TypeErrorFound)
1745  return ExprError();
1746 
1747  // If we determined that the generic selection is result-dependent, don't
1748  // try to compute the result expression.
1749  if (IsResultDependent)
1750  return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1751  Exprs, DefaultLoc, RParenLoc,
1752  ContainsUnexpandedParameterPack);
1753 
1754  SmallVector<unsigned, 1> CompatIndices;
1755  unsigned DefaultIndex = -1U;
1756  // Look at the canonical type of the controlling expression in case it was a
1757  // deduced type like __auto_type. However, when issuing diagnostics, use the
1758  // type the user wrote in source rather than the canonical one.
1759  for (unsigned i = 0; i < NumAssocs; ++i) {
1760  if (!Types[i])
1761  DefaultIndex = i;
1762  else if (Context.typesAreCompatible(
1763  ControllingExpr->getType().getCanonicalType(),
1764  Types[i]->getType()))
1765  CompatIndices.push_back(i);
1766  }
1767 
1768  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1769  // type compatible with at most one of the types named in its generic
1770  // association list."
1771  if (CompatIndices.size() > 1) {
1772  // We strip parens here because the controlling expression is typically
1773  // parenthesized in macro definitions.
1774  ControllingExpr = ControllingExpr->IgnoreParens();
1775  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1776  << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1777  << (unsigned)CompatIndices.size();
1778  for (unsigned I : CompatIndices) {
1779  Diag(Types[I]->getTypeLoc().getBeginLoc(),
1780  diag::note_compat_assoc)
1781  << Types[I]->getTypeLoc().getSourceRange()
1782  << Types[I]->getType();
1783  }
1784  return ExprError();
1785  }
1786 
1787  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1788  // its controlling expression shall have type compatible with exactly one of
1789  // the types named in its generic association list."
1790  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1791  // We strip parens here because the controlling expression is typically
1792  // parenthesized in macro definitions.
1793  ControllingExpr = ControllingExpr->IgnoreParens();
1794  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1795  << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1796  return ExprError();
1797  }
1798 
1799  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1800  // type name that is compatible with the type of the controlling expression,
1801  // then the result expression of the generic selection is the expression
1802  // in that generic association. Otherwise, the result expression of the
1803  // generic selection is the expression in the default generic association."
1804  unsigned ResultIndex =
1805  CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1806 
1808  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1809  ContainsUnexpandedParameterPack, ResultIndex);
1810 }
1811 
1812 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1813 /// location of the token and the offset of the ud-suffix within it.
1815  unsigned Offset) {
1817  S.getLangOpts());
1818 }
1819 
1820 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1821 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1823  IdentifierInfo *UDSuffix,
1824  SourceLocation UDSuffixLoc,
1825  ArrayRef<Expr*> Args,
1826  SourceLocation LitEndLoc) {
1827  assert(Args.size() <= 2 && "too many arguments for literal operator");
1828 
1829  QualType ArgTy[2];
1830  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1831  ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1832  if (ArgTy[ArgIdx]->isArrayType())
1833  ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1834  }
1835 
1836  DeclarationName OpName =
1838  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1839  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1840 
1841  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1842  if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1843  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1844  /*AllowStringTemplatePack*/ false,
1845  /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1846  return ExprError();
1847 
1848  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1849 }
1850 
1851 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1852 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1853 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1854 /// multiple tokens. However, the common case is that StringToks points to one
1855 /// string.
1856 ///
1857 ExprResult
1859  assert(!StringToks.empty() && "Must have at least one string!");
1860 
1861  StringLiteralParser Literal(StringToks, PP);
1862  if (Literal.hadError)
1863  return ExprError();
1864 
1865  SmallVector<SourceLocation, 4> StringTokLocs;
1866  for (const Token &Tok : StringToks)
1867  StringTokLocs.push_back(Tok.getLocation());
1868 
1869  QualType CharTy = Context.CharTy;
1871  if (Literal.isWide()) {
1872  CharTy = Context.getWideCharType();
1874  } else if (Literal.isUTF8()) {
1875  if (getLangOpts().Char8)
1876  CharTy = Context.Char8Ty;
1878  } else if (Literal.isUTF16()) {
1879  CharTy = Context.Char16Ty;
1881  } else if (Literal.isUTF32()) {
1882  CharTy = Context.Char32Ty;
1884  } else if (Literal.isPascal()) {
1885  CharTy = Context.UnsignedCharTy;
1886  }
1887 
1888  // Warn on initializing an array of char from a u8 string literal; this
1889  // becomes ill-formed in C++2a.
1890  if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1891  !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1892  Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1893 
1894  // Create removals for all 'u8' prefixes in the string literal(s). This
1895  // ensures C++2a compatibility (but may change the program behavior when
1896  // built by non-Clang compilers for which the execution character set is
1897  // not always UTF-8).
1898  auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1899  SourceLocation RemovalDiagLoc;
1900  for (const Token &Tok : StringToks) {
1901  if (Tok.getKind() == tok::utf8_string_literal) {
1902  if (RemovalDiagLoc.isInvalid())
1903  RemovalDiagLoc = Tok.getLocation();
1905  Tok.getLocation(),
1906  Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1907  getSourceManager(), getLangOpts())));
1908  }
1909  }
1910  Diag(RemovalDiagLoc, RemovalDiag);
1911  }
1912 
1913  QualType StrTy =
1914  Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1915 
1916  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1917  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1918  Kind, Literal.Pascal, StrTy,
1919  &StringTokLocs[0],
1920  StringTokLocs.size());
1921  if (Literal.getUDSuffix().empty())
1922  return Lit;
1923 
1924  // We're building a user-defined literal.
1925  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1926  SourceLocation UDSuffixLoc =
1927  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1928  Literal.getUDSuffixOffset());
1929 
1930  // Make sure we're allowed user-defined literals here.
1931  if (!UDLScope)
1932  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1933 
1934  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1935  // operator "" X (str, len)
1936  QualType SizeType = Context.getSizeType();
1937 
1938  DeclarationName OpName =
1939  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1940  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1941  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1942 
1943  QualType ArgTy[] = {
1944  Context.getArrayDecayedType(StrTy), SizeType
1945  };
1946 
1947  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1948  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1949  /*AllowRaw*/ false, /*AllowTemplate*/ true,
1950  /*AllowStringTemplatePack*/ true,
1951  /*DiagnoseMissing*/ true, Lit)) {
1952 
1953  case LOLR_Cooked: {
1954  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1955  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1956  StringTokLocs[0]);
1957  Expr *Args[] = { Lit, LenArg };
1958 
1959  return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1960  }
1961 
1962  case LOLR_Template: {
1963  TemplateArgumentListInfo ExplicitArgs;
1964  TemplateArgument Arg(Lit);
1965  TemplateArgumentLocInfo ArgInfo(Lit);
1966  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1967  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1968  StringTokLocs.back(), &ExplicitArgs);
1969  }
1970 
1971  case LOLR_StringTemplatePack: {
1972  TemplateArgumentListInfo ExplicitArgs;
1973 
1974  unsigned CharBits = Context.getIntWidth(CharTy);
1975  bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1976  llvm::APSInt Value(CharBits, CharIsUnsigned);
1977 
1978  TemplateArgument TypeArg(CharTy);
1979  TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1980  ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1981 
1982  for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1983  Value = Lit->getCodeUnit(I);
1984  TemplateArgument Arg(Context, Value, CharTy);
1985  TemplateArgumentLocInfo ArgInfo;
1986  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1987  }
1988  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1989  StringTokLocs.back(), &ExplicitArgs);
1990  }
1991  case LOLR_Raw:
1992  case LOLR_ErrorNoDiagnostic:
1993  llvm_unreachable("unexpected literal operator lookup result");
1994  case LOLR_Error:
1995  return ExprError();
1996  }
1997  llvm_unreachable("unexpected literal operator lookup result");
1998 }
1999 
2000 DeclRefExpr *
2002  SourceLocation Loc,
2003  const CXXScopeSpec *SS) {
2004  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2005  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2006 }
2007 
2008 DeclRefExpr *
2010  const DeclarationNameInfo &NameInfo,
2011  const CXXScopeSpec *SS, NamedDecl *FoundD,
2012  SourceLocation TemplateKWLoc,
2013  const TemplateArgumentListInfo *TemplateArgs) {
2015  SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2016  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2017  TemplateArgs);
2018 }
2019 
2020 // CUDA/HIP: Check whether a captured reference variable is referencing a
2021 // host variable in a device or host device lambda.
2023  VarDecl *VD) {
2024  if (!S.getLangOpts().CUDA || !VD->hasInit())
2025  return false;
2026  assert(VD->getType()->isReferenceType());
2027 
2028  // Check whether the reference variable is referencing a host variable.
2029  auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2030  if (!DRE)
2031  return false;
2032  auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2033  if (!Referee || !Referee->hasGlobalStorage() ||
2034  Referee->hasAttr<CUDADeviceAttr>())
2035  return false;
2036 
2037  // Check whether the current function is a device or host device lambda.
2038  // Check whether the reference variable is a capture by getDeclContext()
2039  // since refersToEnclosingVariableOrCapture() is not ready at this point.
2040  auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2041  if (MD && MD->getParent()->isLambda() &&
2042  MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2043  VD->getDeclContext() != MD)
2044  return true;
2045 
2046  return false;
2047 }
2048 
2050  // A declaration named in an unevaluated operand never constitutes an odr-use.
2051  if (isUnevaluatedContext())
2052  return NOUR_Unevaluated;
2053 
2054  // C++2a [basic.def.odr]p4:
2055  // A variable x whose name appears as a potentially-evaluated expression e
2056  // is odr-used by e unless [...] x is a reference that is usable in
2057  // constant expressions.
2058  // CUDA/HIP:
2059  // If a reference variable referencing a host variable is captured in a
2060  // device or host device lambda, the value of the referee must be copied
2061  // to the capture and the reference variable must be treated as odr-use
2062  // since the value of the referee is not known at compile time and must
2063  // be loaded from the captured.
2064  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2065  if (VD->getType()->isReferenceType() &&
2066  !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2068  VD->isUsableInConstantExpressions(Context))
2069  return NOUR_Constant;
2070  }
2071 
2072  // All remaining non-variable cases constitute an odr-use. For variables, we
2073  // need to wait and see how the expression is used.
2074  return NOUR_None;
2075 }
2076 
2077 /// BuildDeclRefExpr - Build an expression that references a
2078 /// declaration that does not require a closure capture.
2079 DeclRefExpr *
2081  const DeclarationNameInfo &NameInfo,
2082  NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2083  SourceLocation TemplateKWLoc,
2084  const TemplateArgumentListInfo *TemplateArgs) {
2085  bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2086  NeedToCaptureVariable(D, NameInfo.getLoc());
2087 
2089  Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2090  VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2091  MarkDeclRefReferenced(E);
2092 
2093  // C++ [except.spec]p17:
2094  // An exception-specification is considered to be needed when:
2095  // - in an expression, the function is the unique lookup result or
2096  // the selected member of a set of overloaded functions.
2097  //
2098  // We delay doing this until after we've built the function reference and
2099  // marked it as used so that:
2100  // a) if the function is defaulted, we get errors from defining it before /
2101  // instead of errors from computing its exception specification, and
2102  // b) if the function is a defaulted comparison, we can use the body we
2103  // build when defining it as input to the exception specification
2104  // computation rather than computing a new body.
2105  if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2106  if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2107  if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2108  E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2109  }
2110  }
2111 
2112  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2113  Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2114  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2115  getCurFunction()->recordUseOfWeak(E);
2116 
2117  FieldDecl *FD = dyn_cast<FieldDecl>(D);
2118  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2119  FD = IFD->getAnonField();
2120  if (FD) {
2121  UnusedPrivateFields.remove(FD);
2122  // Just in case we're building an illegal pointer-to-member.
2123  if (FD->isBitField())
2125  }
2126 
2127  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2128  // designates a bit-field.
2129  if (auto *BD = dyn_cast<BindingDecl>(D))
2130  if (auto *BE = BD->getBinding())
2131  E->setObjectKind(BE->getObjectKind());
2132 
2133  return E;
2134 }
2135 
2136 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2137 /// possibly a list of template arguments.
2138 ///
2139 /// If this produces template arguments, it is permitted to call
2140 /// DecomposeTemplateName.
2141 ///
2142 /// This actually loses a lot of source location information for
2143 /// non-standard name kinds; we should consider preserving that in
2144 /// some way.
2145 void
2147  TemplateArgumentListInfo &Buffer,
2148  DeclarationNameInfo &NameInfo,
2149  const TemplateArgumentListInfo *&TemplateArgs) {
2150  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2151  Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2152  Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2153 
2154  ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2155  Id.TemplateId->NumArgs);
2156  translateTemplateArguments(TemplateArgsPtr, Buffer);
2157 
2158  TemplateName TName = Id.TemplateId->Template.get();
2159  SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2160  NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2161  TemplateArgs = &Buffer;
2162  } else {
2163  NameInfo = GetNameFromUnqualifiedId(Id);
2164  TemplateArgs = nullptr;
2165  }
2166 }
2167 
2169  const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2170  DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2171  unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2172  DeclContext *Ctx =
2173  SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2174  if (!TC) {
2175  // Emit a special diagnostic for failed member lookups.
2176  // FIXME: computing the declaration context might fail here (?)
2177  if (Ctx)
2178  SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2179  << SS.getRange();
2180  else
2181  SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2182  return;
2183  }
2184 
2185  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2186  bool DroppedSpecifier =
2187  TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2188  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2189  ? diag::note_implicit_param_decl
2190  : diag::note_previous_decl;
2191  if (!Ctx)
2192  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2193  SemaRef.PDiag(NoteID));
2194  else
2195  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2196  << Typo << Ctx << DroppedSpecifier
2197  << SS.getRange(),
2198  SemaRef.PDiag(NoteID));
2199 }
2200 
2201 /// Diagnose a lookup that found results in an enclosing class during error
2202 /// recovery. This usually indicates that the results were found in a dependent
2203 /// base class that could not be searched as part of a template definition.
2204 /// Always issues a diagnostic (though this may be only a warning in MS
2205 /// compatibility mode).
2206 ///
2207 /// Return \c true if the error is unrecoverable, or \c false if the caller
2208 /// should attempt to recover using these lookup results.
2210  // During a default argument instantiation the CurContext points
2211  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2212  // function parameter list, hence add an explicit check.
2213  bool isDefaultArgument =
2214  !CodeSynthesisContexts.empty() &&
2215  CodeSynthesisContexts.back().Kind ==
2216  CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2217  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2218  bool isInstance = CurMethod && CurMethod->isInstance() &&
2219  R.getNamingClass() == CurMethod->getParent() &&
2220  !isDefaultArgument;
2221 
2222  // There are two ways we can find a class-scope declaration during template
2223  // instantiation that we did not find in the template definition: if it is a
2224  // member of a dependent base class, or if it is declared after the point of
2225  // use in the same class. Distinguish these by comparing the class in which
2226  // the member was found to the naming class of the lookup.
2227  unsigned DiagID = diag::err_found_in_dependent_base;
2228  unsigned NoteID = diag::note_member_declared_at;
2230  DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2231  : diag::err_found_later_in_class;
2232  } else if (getLangOpts().MSVCCompat) {
2233  DiagID = diag::ext_found_in_dependent_base;
2234  NoteID = diag::note_dependent_member_use;
2235  }
2236 
2237  if (isInstance) {
2238  // Give a code modification hint to insert 'this->'.
2239  Diag(R.getNameLoc(), DiagID)
2240  << R.getLookupName()
2241  << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2242  CheckCXXThisCapture(R.getNameLoc());
2243  } else {
2244  // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2245  // they're not shadowed).
2246  Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2247  }
2248 
2249  for (NamedDecl *D : R)
2250  Diag(D->getLocation(), NoteID);
2251 
2252  // Return true if we are inside a default argument instantiation
2253  // and the found name refers to an instance member function, otherwise
2254  // the caller will try to create an implicit member call and this is wrong
2255  // for default arguments.
2256  //
2257  // FIXME: Is this special case necessary? We could allow the caller to
2258  // diagnose this.
2259  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2260  Diag(R.getNameLoc(), diag::err_member_call_without_object);
2261  return true;
2262  }
2263 
2264  // Tell the callee to try to recover.
2265  return false;
2266 }
2267 
2268 /// Diagnose an empty lookup.
2269 ///
2270 /// \return false if new lookup candidates were found
2273  TemplateArgumentListInfo *ExplicitTemplateArgs,
2274  ArrayRef<Expr *> Args, TypoExpr **Out) {
2275  DeclarationName Name = R.getLookupName();
2276 
2277  unsigned diagnostic = diag::err_undeclared_var_use;
2278  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2279  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2280  Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2281  Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2282  diagnostic = diag::err_undeclared_use;
2283  diagnostic_suggest = diag::err_undeclared_use_suggest;
2284  }
2285 
2286  // If the original lookup was an unqualified lookup, fake an
2287  // unqualified lookup. This is useful when (for example) the
2288  // original lookup would not have found something because it was a
2289  // dependent name.
2290  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2291  while (DC) {
2292  if (isa<CXXRecordDecl>(DC)) {
2293  LookupQualifiedName(R, DC);
2294 
2295  if (!R.empty()) {
2296  // Don't give errors about ambiguities in this lookup.
2297  R.suppressDiagnostics();
2298 
2299  // If there's a best viable function among the results, only mention
2300  // that one in the notes.
2301  OverloadCandidateSet Candidates(R.getNameLoc(),
2303  AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2305  if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2306  OR_Success) {
2307  R.clear();
2308  R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2309  R.resolveKind();
2310  }
2311 
2312  return DiagnoseDependentMemberLookup(R);
2313  }
2314 
2315  R.clear();
2316  }
2317 
2318  DC = DC->getLookupParent();
2319  }
2320 
2321  // We didn't find anything, so try to correct for a typo.
2322  TypoCorrection Corrected;
2323  if (S && Out) {
2324  SourceLocation TypoLoc = R.getNameLoc();
2325  assert(!ExplicitTemplateArgs &&
2326  "Diagnosing an empty lookup with explicit template args!");
2327  *Out = CorrectTypoDelayed(
2328  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2329  [=](const TypoCorrection &TC) {
2330  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2331  diagnostic, diagnostic_suggest);
2332  },
2333  nullptr, CTK_ErrorRecovery);
2334  if (*Out)
2335  return true;
2336  } else if (S &&
2337  (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2338  S, &SS, CCC, CTK_ErrorRecovery))) {
2339  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2340  bool DroppedSpecifier =
2341  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2342  R.setLookupName(Corrected.getCorrection());
2343 
2344  bool AcceptableWithRecovery = false;
2345  bool AcceptableWithoutRecovery = false;
2346  NamedDecl *ND = Corrected.getFoundDecl();
2347  if (ND) {
2348  if (Corrected.isOverloaded()) {
2352  for (NamedDecl *CD : Corrected) {
2353  if (FunctionTemplateDecl *FTD =
2354  dyn_cast<FunctionTemplateDecl>(CD))
2355  AddTemplateOverloadCandidate(
2356  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2357  Args, OCS);
2358  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2359  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2360  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2361  Args, OCS);
2362  }
2363  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2364  case OR_Success:
2365  ND = Best->FoundDecl;
2366  Corrected.setCorrectionDecl(ND);
2367  break;
2368  default:
2369  // FIXME: Arbitrarily pick the first declaration for the note.
2370  Corrected.setCorrectionDecl(ND);
2371  break;
2372  }
2373  }
2374  R.addDecl(ND);
2375  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2376  CXXRecordDecl *Record = nullptr;
2377  if (Corrected.getCorrectionSpecifier()) {
2378  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2379  Record = Ty->getAsCXXRecordDecl();
2380  }
2381  if (!Record)
2382  Record = cast<CXXRecordDecl>(
2383  ND->getDeclContext()->getRedeclContext());
2384  R.setNamingClass(Record);
2385  }
2386 
2387  auto *UnderlyingND = ND->getUnderlyingDecl();
2388  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2389  isa<FunctionTemplateDecl>(UnderlyingND);
2390  // FIXME: If we ended up with a typo for a type name or
2391  // Objective-C class name, we're in trouble because the parser
2392  // is in the wrong place to recover. Suggest the typo
2393  // correction, but don't make it a fix-it since we're not going
2394  // to recover well anyway.
2395  AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2396  getAsTypeTemplateDecl(UnderlyingND) ||
2397  isa<ObjCInterfaceDecl>(UnderlyingND);
2398  } else {
2399  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2400  // because we aren't able to recover.
2401  AcceptableWithoutRecovery = true;
2402  }
2403 
2404  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2405  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2406  ? diag::note_implicit_param_decl
2407  : diag::note_previous_decl;
2408  if (SS.isEmpty())
2409  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2410  PDiag(NoteID), AcceptableWithRecovery);
2411  else
2412  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2413  << Name << computeDeclContext(SS, false)
2414  << DroppedSpecifier << SS.getRange(),
2415  PDiag(NoteID), AcceptableWithRecovery);
2416 
2417  // Tell the callee whether to try to recover.
2418  return !AcceptableWithRecovery;
2419  }
2420  }
2421  R.clear();
2422 
2423  // Emit a special diagnostic for failed member lookups.
2424  // FIXME: computing the declaration context might fail here (?)
2425  if (!SS.isEmpty()) {
2426  Diag(R.getNameLoc(), diag::err_no_member)
2427  << Name << computeDeclContext(SS, false)
2428  << SS.getRange();
2429  return true;
2430  }
2431 
2432  // Give up, we can't recover.
2433  Diag(R.getNameLoc(), diagnostic) << Name;
2434  return true;
2435 }
2436 
2437 /// In Microsoft mode, if we are inside a template class whose parent class has
2438 /// dependent base classes, and we can't resolve an unqualified identifier, then
2439 /// assume the identifier is a member of a dependent base class. We can only
2440 /// recover successfully in static methods, instance methods, and other contexts
2441 /// where 'this' is available. This doesn't precisely match MSVC's
2442 /// instantiation model, but it's close enough.
2443 static Expr *
2445  DeclarationNameInfo &NameInfo,
2446  SourceLocation TemplateKWLoc,
2447  const TemplateArgumentListInfo *TemplateArgs) {
2448  // Only try to recover from lookup into dependent bases in static methods or
2449  // contexts where 'this' is available.
2450  QualType ThisType = S.getCurrentThisType();
2451  const CXXRecordDecl *RD = nullptr;
2452  if (!ThisType.isNull())
2453  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2454  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2455  RD = MD->getParent();
2456  if (!RD || !RD->hasAnyDependentBases())
2457  return nullptr;
2458 
2459  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2460  // is available, suggest inserting 'this->' as a fixit.
2461  SourceLocation Loc = NameInfo.getLoc();
2462  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2463  DB << NameInfo.getName() << RD;
2464 
2465  if (!ThisType.isNull()) {
2466  DB << FixItHint::CreateInsertion(Loc, "this->");
2468  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2469  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2470  /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2471  }
2472 
2473  // Synthesize a fake NNS that points to the derived class. This will
2474  // perform name lookup during template instantiation.
2475  CXXScopeSpec SS;
2476  auto *NNS =
2477  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2478  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2480  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2481  TemplateArgs);
2482 }
2483 
2484 ExprResult
2486  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2487  bool HasTrailingLParen, bool IsAddressOfOperand,
2489  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2490  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2491  "cannot be direct & operand and have a trailing lparen");
2492  if (SS.isInvalid())
2493  return ExprError();
2494 
2495  TemplateArgumentListInfo TemplateArgsBuffer;
2496 
2497  // Decompose the UnqualifiedId into the following data.
2498  DeclarationNameInfo NameInfo;
2499  const TemplateArgumentListInfo *TemplateArgs;
2500  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2501 
2502  DeclarationName Name = NameInfo.getName();
2503  IdentifierInfo *II = Name.getAsIdentifierInfo();
2504  SourceLocation NameLoc = NameInfo.getLoc();
2505 
2506  if (II && II->isEditorPlaceholder()) {
2507  // FIXME: When typed placeholders are supported we can create a typed
2508  // placeholder expression node.
2509  return ExprError();
2510  }
2511 
2512  // C++ [temp.dep.expr]p3:
2513  // An id-expression is type-dependent if it contains:
2514  // -- an identifier that was declared with a dependent type,
2515  // (note: handled after lookup)
2516  // -- a template-id that is dependent,
2517  // (note: handled in BuildTemplateIdExpr)
2518  // -- a conversion-function-id that specifies a dependent type,
2519  // -- a nested-name-specifier that contains a class-name that
2520  // names a dependent type.
2521  // Determine whether this is a member of an unknown specialization;
2522  // we need to handle these differently.
2523  bool DependentID = false;
2524  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2525  Name.getCXXNameType()->isDependentType()) {
2526  DependentID = true;
2527  } else if (SS.isSet()) {
2528  if (DeclContext *DC = computeDeclContext(SS, false)) {
2529  if (RequireCompleteDeclContext(SS, DC))
2530  return ExprError();
2531  } else {
2532  DependentID = true;
2533  }
2534  }
2535 
2536  if (DependentID)
2537  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2538  IsAddressOfOperand, TemplateArgs);
2539 
2540  // Perform the required lookup.
2541  LookupResult R(*this, NameInfo,
2543  ? LookupObjCImplicitSelfParam
2544  : LookupOrdinaryName);
2545  if (TemplateKWLoc.isValid() || TemplateArgs) {
2546  // Lookup the template name again to correctly establish the context in
2547  // which it was found. This is really unfortunate as we already did the
2548  // lookup to determine that it was a template name in the first place. If
2549  // this becomes a performance hit, we can work harder to preserve those
2550  // results until we get here but it's likely not worth it.
2551  bool MemberOfUnknownSpecialization;
2552  AssumedTemplateKind AssumedTemplate;
2553  if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2554  MemberOfUnknownSpecialization, TemplateKWLoc,
2555  &AssumedTemplate))
2556  return ExprError();
2557 
2558  if (MemberOfUnknownSpecialization ||
2560  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2561  IsAddressOfOperand, TemplateArgs);
2562  } else {
2563  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2564  LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2565 
2566  // If the result might be in a dependent base class, this is a dependent
2567  // id-expression.
2569  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2570  IsAddressOfOperand, TemplateArgs);
2571 
2572  // If this reference is in an Objective-C method, then we need to do
2573  // some special Objective-C lookup, too.
2574  if (IvarLookupFollowUp) {
2575  ExprResult E(LookupInObjCMethod(R, S, II, true));
2576  if (E.isInvalid())
2577  return ExprError();
2578 
2579  if (Expr *Ex = E.getAs<Expr>())
2580  return Ex;
2581  }
2582  }
2583 
2584  if (R.isAmbiguous())
2585  return ExprError();
2586 
2587  // This could be an implicitly declared function reference if the language
2588  // mode allows it as a feature.
2589  if (R.empty() && HasTrailingLParen && II &&
2590  getLangOpts().implicitFunctionsAllowed()) {
2591  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2592  if (D) R.addDecl(D);
2593  }
2594 
2595  // Determine whether this name might be a candidate for
2596  // argument-dependent lookup.
2597  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2598 
2599  if (R.empty() && !ADL) {
2600  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2601  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2602  TemplateKWLoc, TemplateArgs))
2603  return E;
2604  }
2605 
2606  // Don't diagnose an empty lookup for inline assembly.
2607  if (IsInlineAsmIdentifier)
2608  return ExprError();
2609 
2610  // If this name wasn't predeclared and if this is not a function
2611  // call, diagnose the problem.
2612  TypoExpr *TE = nullptr;
2613  DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2614  : nullptr);
2615  DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2616  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2617  "Typo correction callback misconfigured");
2618  if (CCC) {
2619  // Make sure the callback knows what the typo being diagnosed is.
2620  CCC->setTypoName(II);
2621  if (SS.isValid())
2622  CCC->setTypoNNS(SS.getScopeRep());
2623  }
2624  // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2625  // a template name, but we happen to have always already looked up the name
2626  // before we get here if it must be a template name.
2627  if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2628  std::nullopt, &TE)) {
2629  if (TE && KeywordReplacement) {
2630  auto &State = getTypoExprState(TE);
2631  auto BestTC = State.Consumer->getNextCorrection();
2632  if (BestTC.isKeyword()) {
2633  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2634  if (State.DiagHandler)
2635  State.DiagHandler(BestTC);
2636  KeywordReplacement->startToken();
2637  KeywordReplacement->setKind(II->getTokenID());
2638  KeywordReplacement->setIdentifierInfo(II);
2639  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2640  // Clean up the state associated with the TypoExpr, since it has
2641  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2642  clearDelayedTypo(TE);
2643  // Signal that a correction to a keyword was performed by returning a
2644  // valid-but-null ExprResult.
2645  return (Expr*)nullptr;
2646  }
2647  State.Consumer->resetCorrectionStream();
2648  }
2649  return TE ? TE : ExprError();
2650  }
2651 
2652  assert(!R.empty() &&
2653  "DiagnoseEmptyLookup returned false but added no results");
2654 
2655  // If we found an Objective-C instance variable, let
2656  // LookupInObjCMethod build the appropriate expression to
2657  // reference the ivar.
2658  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2659  R.clear();
2660  ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2661  // In a hopelessly buggy code, Objective-C instance variable
2662  // lookup fails and no expression will be built to reference it.
2663  if (!E.isInvalid() && !E.get())
2664  return ExprError();
2665  return E;
2666  }
2667  }
2668 
2669  // This is guaranteed from this point on.
2670  assert(!R.empty() || ADL);
2671 
2672  // Check whether this might be a C++ implicit instance member access.
2673  // C++ [class.mfct.non-static]p3:
2674  // When an id-expression that is not part of a class member access
2675  // syntax and not used to form a pointer to member is used in the
2676  // body of a non-static member function of class X, if name lookup
2677  // resolves the name in the id-expression to a non-static non-type
2678  // member of some class C, the id-expression is transformed into a
2679  // class member access expression using (*this) as the
2680  // postfix-expression to the left of the . operator.
2681  //
2682  // But we don't actually need to do this for '&' operands if R
2683  // resolved to a function or overloaded function set, because the
2684  // expression is ill-formed if it actually works out to be a
2685  // non-static member function:
2686  //
2687  // C++ [expr.ref]p4:
2688  // Otherwise, if E1.E2 refers to a non-static member function. . .
2689  // [t]he expression can be used only as the left-hand operand of a
2690  // member function call.
2691  //
2692  // There are other safeguards against such uses, but it's important
2693  // to get this right here so that we don't end up making a
2694  // spuriously dependent expression if we're inside a dependent
2695  // instance method.
2696  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2697  bool MightBeImplicitMember;
2698  if (!IsAddressOfOperand)
2699  MightBeImplicitMember = true;
2700  else if (!SS.isEmpty())
2701  MightBeImplicitMember = false;
2702  else if (R.isOverloadedResult())
2703  MightBeImplicitMember = false;
2704  else if (R.isUnresolvableResult())
2705  MightBeImplicitMember = true;
2706  else
2707  MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2708  isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2709  isa<MSPropertyDecl>(R.getFoundDecl());
2710 
2711  if (MightBeImplicitMember)
2712  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2713  R, TemplateArgs, S);
2714  }
2715 
2716  if (TemplateArgs || TemplateKWLoc.isValid()) {
2717 
2718  // In C++1y, if this is a variable template id, then check it
2719  // in BuildTemplateIdExpr().
2720  // The single lookup result must be a variable template declaration.
2721  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2722  Id.TemplateId->Kind == TNK_Var_template) {
2723  assert(R.getAsSingle<VarTemplateDecl>() &&
2724  "There should only be one declaration found.");
2725  }
2726 
2727  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2728  }
2729 
2730  return BuildDeclarationNameExpr(SS, R, ADL);
2731 }
2732 
2733 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2734 /// declaration name, generally during template instantiation.
2735 /// There's a large number of things which don't need to be done along
2736 /// this path.
2738  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2739  bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2740  if (NameInfo.getName().isDependentName())
2741  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2742  NameInfo, /*TemplateArgs=*/nullptr);
2743 
2744  DeclContext *DC = computeDeclContext(SS, false);
2745  if (!DC)
2746  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2747  NameInfo, /*TemplateArgs=*/nullptr);
2748 
2749  if (RequireCompleteDeclContext(SS, DC))
2750  return ExprError();
2751 
2752  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2753  LookupQualifiedName(R, DC);
2754 
2755  if (R.isAmbiguous())
2756  return ExprError();
2757 
2759  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2760  NameInfo, /*TemplateArgs=*/nullptr);
2761 
2762  if (R.empty()) {
2763  // Don't diagnose problems with invalid record decl, the secondary no_member
2764  // diagnostic during template instantiation is likely bogus, e.g. if a class
2765  // is invalid because it's derived from an invalid base class, then missing
2766  // members were likely supposed to be inherited.
2767  if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2768  if (CD->isInvalidDecl())
2769  return ExprError();
2770  Diag(NameInfo.getLoc(), diag::err_no_member)
2771  << NameInfo.getName() << DC << SS.getRange();
2772  return ExprError();
2773  }
2774 
2775  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2776  // Diagnose a missing typename if this resolved unambiguously to a type in
2777  // a dependent context. If we can recover with a type, downgrade this to
2778  // a warning in Microsoft compatibility mode.
2779  unsigned DiagID = diag::err_typename_missing;
2780  if (RecoveryTSI && getLangOpts().MSVCCompat)
2781  DiagID = diag::ext_typename_missing;
2782  SourceLocation Loc = SS.getBeginLoc();
2783  auto D = Diag(Loc, DiagID);
2784  D << SS.getScopeRep() << NameInfo.getName().getAsString()
2785  << SourceRange(Loc, NameInfo.getEndLoc());
2786 
2787  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2788  // context.
2789  if (!RecoveryTSI)
2790  return ExprError();
2791 
2792  // Only issue the fixit if we're prepared to recover.
2793  D << FixItHint::CreateInsertion(Loc, "typename ");
2794 
2795  // Recover by pretending this was an elaborated type.
2796  QualType Ty = Context.getTypeDeclType(TD);
2797  TypeLocBuilder TLB;
2798  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2799 
2800  QualType ET = getElaboratedType(ETK_None, SS, Ty);
2801  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2803  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2804 
2805  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2806 
2807  return ExprEmpty();
2808  }
2809 
2810  // Defend against this resolving to an implicit member access. We usually
2811  // won't get here if this might be a legitimate a class member (we end up in
2812  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2813  // a pointer-to-member or in an unevaluated context in C++11.
2814  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2815  return BuildPossibleImplicitMemberExpr(SS,
2816  /*TemplateKWLoc=*/SourceLocation(),
2817  R, /*TemplateArgs=*/nullptr, S);
2818 
2819  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2820 }
2821 
2822 /// The parser has read a name in, and Sema has detected that we're currently
2823 /// inside an ObjC method. Perform some additional checks and determine if we
2824 /// should form a reference to an ivar.
2825 ///
2826 /// Ideally, most of this would be done by lookup, but there's
2827 /// actually quite a lot of extra work involved.
2829  IdentifierInfo *II) {
2830  SourceLocation Loc = Lookup.getNameLoc();
2831  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2832 
2833  // Check for error condition which is already reported.
2834  if (!CurMethod)
2835  return DeclResult(true);
2836 
2837  // There are two cases to handle here. 1) scoped lookup could have failed,
2838  // in which case we should look for an ivar. 2) scoped lookup could have
2839  // found a decl, but that decl is outside the current instance method (i.e.
2840  // a global variable). In these two cases, we do a lookup for an ivar with
2841  // this name, if the lookup sucedes, we replace it our current decl.
2842 
2843  // If we're in a class method, we don't normally want to look for
2844  // ivars. But if we don't find anything else, and there's an
2845  // ivar, that's an error.
2846  bool IsClassMethod = CurMethod->isClassMethod();
2847 
2848  bool LookForIvars;
2849  if (Lookup.empty())
2850  LookForIvars = true;
2851  else if (IsClassMethod)
2852  LookForIvars = false;
2853  else
2854  LookForIvars = (Lookup.isSingleResult() &&
2856  ObjCInterfaceDecl *IFace = nullptr;
2857  if (LookForIvars) {
2858  IFace = CurMethod->getClassInterface();
2859  ObjCInterfaceDecl *ClassDeclared;
2860  ObjCIvarDecl *IV = nullptr;
2861  if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2862  // Diagnose using an ivar in a class method.
2863  if (IsClassMethod) {
2864  Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2865  return DeclResult(true);
2866  }
2867 
2868  // Diagnose the use of an ivar outside of the declaring class.
2869  if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2870  !declaresSameEntity(ClassDeclared, IFace) &&
2871  !getLangOpts().DebuggerSupport)
2872  Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2873 
2874  // Success.
2875  return IV;
2876  }
2877  } else if (CurMethod->isInstanceMethod()) {
2878  // We should warn if a local variable hides an ivar.
2879  if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2880  ObjCInterfaceDecl *ClassDeclared;
2881  if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2882  if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2883  declaresSameEntity(IFace, ClassDeclared))
2884  Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2885  }
2886  }
2887  } else if (Lookup.isSingleResult() &&
2889  // If accessing a stand-alone ivar in a class method, this is an error.
2890  if (const ObjCIvarDecl *IV =
2891  dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2892  Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2893  return DeclResult(true);
2894  }
2895  }
2896 
2897  // Didn't encounter an error, didn't find an ivar.
2898  return DeclResult(false);
2899 }
2900 
2902  ObjCIvarDecl *IV) {
2903  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2904  assert(CurMethod && CurMethod->isInstanceMethod() &&
2905  "should not reference ivar from this context");
2906 
2907  ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2908  assert(IFace && "should not reference ivar from this context");
2909 
2910  // If we're referencing an invalid decl, just return this as a silent
2911  // error node. The error diagnostic was already emitted on the decl.
2912  if (IV->isInvalidDecl())
2913  return ExprError();
2914 
2915  // Check if referencing a field with __attribute__((deprecated)).
2916  if (DiagnoseUseOfDecl(IV, Loc))
2917  return ExprError();
2918 
2919  // FIXME: This should use a new expr for a direct reference, don't
2920  // turn this into Self->ivar, just return a BareIVarExpr or something.
2921  IdentifierInfo &II = Context.Idents.get("self");
2922  UnqualifiedId SelfName;
2923  SelfName.setImplicitSelfParam(&II);
2924  CXXScopeSpec SelfScopeSpec;
2925  SourceLocation TemplateKWLoc;
2926  ExprResult SelfExpr =
2927  ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2928  /*HasTrailingLParen=*/false,
2929  /*IsAddressOfOperand=*/false);
2930  if (SelfExpr.isInvalid())
2931  return ExprError();
2932 
2933  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2934  if (SelfExpr.isInvalid())
2935  return ExprError();
2936 
2937  MarkAnyDeclReferenced(Loc, IV, true);
2938 
2939  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2940  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2941  !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2942  Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2943 
2944  ObjCIvarRefExpr *Result = new (Context)
2945  ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2946  IV->getLocation(), SelfExpr.get(), true, true);
2947 
2948  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2949  if (!isUnevaluatedContext() &&
2950  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2951  getCurFunction()->recordUseOfWeak(Result);
2952  }
2953  if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
2954  if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2955  ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2956 
2957  return Result;
2958 }
2959 
2960 /// The parser has read a name in, and Sema has detected that we're currently
2961 /// inside an ObjC method. Perform some additional checks and determine if we
2962 /// should form a reference to an ivar. If so, build an expression referencing
2963 /// that ivar.
2964 ExprResult
2966  IdentifierInfo *II, bool AllowBuiltinCreation) {
2967  // FIXME: Integrate this lookup step into LookupParsedName.
2968  DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2969  if (Ivar.isInvalid())
2970  return ExprError();
2971  if (Ivar.isUsable())
2972  return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2973  cast<ObjCIvarDecl>(Ivar.get()));
2974 
2975  if (Lookup.empty() && II && AllowBuiltinCreation)
2976  LookupBuiltin(Lookup);
2977 
2978  // Sentinel value saying that we didn't do anything special.
2979  return ExprResult(false);
2980 }
2981 
2982 /// Cast a base object to a member's actual type.
2983 ///
2984 /// There are two relevant checks:
2985 ///
2986 /// C++ [class.access.base]p7:
2987 ///
2988 /// If a class member access operator [...] is used to access a non-static
2989 /// data member or non-static member function, the reference is ill-formed if
2990 /// the left operand [...] cannot be implicitly converted to a pointer to the
2991 /// naming class of the right operand.
2992 ///
2993 /// C++ [expr.ref]p7:
2994 ///
2995 /// If E2 is a non-static data member or a non-static member function, the
2996 /// program is ill-formed if the class of which E2 is directly a member is an
2997 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2998 ///
2999 /// Note that the latter check does not consider access; the access of the
3000 /// "real" base class is checked as appropriate when checking the access of the
3001 /// member name.
3002 ExprResult
3004  NestedNameSpecifier *Qualifier,
3005  NamedDecl *FoundDecl,
3006  NamedDecl *Member) {
3007  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3008  if (!RD)
3009  return From;
3010 
3011  QualType DestRecordType;
3012  QualType DestType;
3013  QualType FromRecordType;
3014  QualType FromType = From->getType();
3015  bool PointerConversions = false;
3016  if (isa<FieldDecl>(Member)) {
3017  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3018  auto FromPtrType = FromType->getAs<PointerType>();
3019  DestRecordType = Context.getAddrSpaceQualType(
3020  DestRecordType, FromPtrType
3021  ? FromType->getPointeeType().getAddressSpace()
3022  : FromType.getAddressSpace());
3023 
3024  if (FromPtrType) {
3025  DestType = Context.getPointerType(DestRecordType);
3026  FromRecordType = FromPtrType->getPointeeType();
3027  PointerConversions = true;
3028  } else {
3029  DestType = DestRecordType;
3030  FromRecordType = FromType;
3031  }
3032  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3033  if (Method->isStatic())
3034  return From;
3035 
3036  DestType = Method->getThisType();
3037  DestRecordType = DestType->getPointeeType();
3038 
3039  if (FromType->getAs<PointerType>()) {
3040  FromRecordType = FromType->getPointeeType();
3041  PointerConversions = true;
3042  } else {
3043  FromRecordType = FromType;
3044  DestType = DestRecordType;
3045  }
3046 
3047  LangAS FromAS = FromRecordType.getAddressSpace();
3048  LangAS DestAS = DestRecordType.getAddressSpace();
3049  if (FromAS != DestAS) {
3050  QualType FromRecordTypeWithoutAS =
3051  Context.removeAddrSpaceQualType(FromRecordType);
3052  QualType FromTypeWithDestAS =
3053  Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3054  if (PointerConversions)
3055  FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3056  From = ImpCastExprToType(From, FromTypeWithDestAS,
3057  CK_AddressSpaceConversion, From->getValueKind())
3058  .get();
3059  }
3060  } else {
3061  // No conversion necessary.
3062  return From;
3063  }
3064 
3065  if (DestType->isDependentType() || FromType->isDependentType())
3066  return From;
3067 
3068  // If the unqualified types are the same, no conversion is necessary.
3069  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3070  return From;
3071 
3072  SourceRange FromRange = From->getSourceRange();
3073  SourceLocation FromLoc = FromRange.getBegin();
3074 
3075  ExprValueKind VK = From->getValueKind();
3076 
3077  // C++ [class.member.lookup]p8:
3078  // [...] Ambiguities can often be resolved by qualifying a name with its
3079  // class name.
3080  //
3081  // If the member was a qualified name and the qualified referred to a
3082  // specific base subobject type, we'll cast to that intermediate type
3083  // first and then to the object in which the member is declared. That allows
3084  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3085  //
3086  // class Base { public: int x; };
3087  // class Derived1 : public Base { };
3088  // class Derived2 : public Base { };
3089  // class VeryDerived : public Derived1, public Derived2 { void f(); };
3090  //
3091  // void VeryDerived::f() {
3092  // x = 17; // error: ambiguous base subobjects
3093  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3094  // }
3095  if (Qualifier && Qualifier->getAsType()) {
3096  QualType QType = QualType(Qualifier->getAsType(), 0);
3097  assert(QType->isRecordType() && "lookup done with non-record type");
3098 
3099  QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3100 
3101  // In C++98, the qualifier type doesn't actually have to be a base
3102  // type of the object type, in which case we just ignore it.
3103  // Otherwise build the appropriate casts.
3104  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3105  CXXCastPath BasePath;
3106  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3107  FromLoc, FromRange, &BasePath))
3108  return ExprError();
3109 
3110  if (PointerConversions)
3111  QType = Context.getPointerType(QType);
3112  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3113  VK, &BasePath).get();
3114 
3115  FromType = QType;
3116  FromRecordType = QRecordType;
3117 
3118  // If the qualifier type was the same as the destination type,
3119  // we're done.
3120  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3121  return From;
3122  }
3123  }
3124 
3125  CXXCastPath BasePath;
3126  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3127  FromLoc, FromRange, &BasePath,
3128  /*IgnoreAccess=*/true))
3129  return ExprError();
3130 
3131  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3132  VK, &BasePath);
3133 }
3134 
3136  const LookupResult &R,
3137  bool HasTrailingLParen) {
3138  // Only when used directly as the postfix-expression of a call.
3139  if (!HasTrailingLParen)
3140  return false;
3141 
3142  // Never if a scope specifier was provided.
3143  if (SS.isSet())
3144  return false;
3145 
3146  // Only in C++ or ObjC++.
3147  if (!getLangOpts().CPlusPlus)
3148  return false;
3149 
3150  // Turn off ADL when we find certain kinds of declarations during
3151  // normal lookup:
3152  for (NamedDecl *D : R) {
3153  // C++0x [basic.lookup.argdep]p3:
3154  // -- a declaration of a class member
3155  // Since using decls preserve this property, we check this on the
3156  // original decl.
3157  if (D->isCXXClassMember())
3158  return false;
3159 
3160  // C++0x [basic.lookup.argdep]p3:
3161  // -- a block-scope function declaration that is not a
3162  // using-declaration
3163  // NOTE: we also trigger this for function templates (in fact, we
3164  // don't check the decl type at all, since all other decl types
3165  // turn off ADL anyway).
3166  if (isa<UsingShadowDecl>(D))
3167  D = cast<UsingShadowDecl>(D)->getTargetDecl();
3168  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3169  return false;
3170 
3171  // C++0x [basic.lookup.argdep]p3:
3172  // -- a declaration that is neither a function or a function
3173  // template
3174  // And also for builtin functions.
3175  if (isa<FunctionDecl>(D)) {
3176  FunctionDecl *FDecl = cast<FunctionDecl>(D);
3177 
3178  // But also builtin functions.
3179  if (FDecl->getBuiltinID() && FDecl->isImplicit())
3180  return false;
3181  } else if (!isa<FunctionTemplateDecl>(D))
3182  return false;
3183  }
3184 
3185  return true;
3186 }
3187 
3188 
3189 /// Diagnoses obvious problems with the use of the given declaration
3190 /// as an expression. This is only actually called for lookups that
3191 /// were not overloaded, and it doesn't promise that the declaration
3192 /// will in fact be used.
3194  bool AcceptInvalid) {
3195  if (D->isInvalidDecl() && !AcceptInvalid)
3196  return true;
3197 
3198  if (isa<TypedefNameDecl>(D)) {
3199  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3200  return true;
3201  }
3202 
3203  if (isa<ObjCInterfaceDecl>(D)) {
3204  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3205  return true;
3206  }
3207 
3208  if (isa<NamespaceDecl>(D)) {
3209  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3210  return true;
3211  }
3212 
3213  return false;
3214 }
3215 
3216 // Certain multiversion types should be treated as overloaded even when there is
3217 // only one result.
3219  assert(R.isSingleResult() && "Expected only a single result");
3220  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3221  return FD &&
3222  (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3223 }
3224 
3226  LookupResult &R, bool NeedsADL,
3227  bool AcceptInvalidDecl) {
3228  // If this is a single, fully-resolved result and we don't need ADL,
3229  // just build an ordinary singleton decl ref.
3230  if (!NeedsADL && R.isSingleResult() &&
3234  R.getRepresentativeDecl(), nullptr,
3235  AcceptInvalidDecl);
3236 
3237  // We only need to check the declaration if there's exactly one
3238  // result, because in the overloaded case the results can only be
3239  // functions and function templates.
3241  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3242  AcceptInvalidDecl))
3243  return ExprError();
3244 
3245  // Otherwise, just build an unresolved lookup expression. Suppress
3246  // any lookup-related diagnostics; we'll hash these out later, when
3247  // we've picked a target.
3248  R.suppressDiagnostics();
3249 
3253  R.getLookupNameInfo(),
3254  NeedsADL, R.isOverloadedResult(),
3255  R.begin(), R.end());
3256 
3257  return ULE;
3258 }
3259 
3261  SourceLocation loc,
3262  ValueDecl *var);
3263 
3264 /// Complete semantic analysis for a reference to the given declaration.
3266  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3267  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3268  bool AcceptInvalidDecl) {
3269  assert(D && "Cannot refer to a NULL declaration");
3270  assert(!isa<FunctionTemplateDecl>(D) &&
3271  "Cannot refer unambiguously to a function template");
3272 
3273  SourceLocation Loc = NameInfo.getLoc();
3274  if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3275  // Recovery from invalid cases (e.g. D is an invalid Decl).
3276  // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3277  // diagnostics, as invalid decls use int as a fallback type.
3278  return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3279  }
3280 
3281  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3282  // Specifically diagnose references to class templates that are missing
3283  // a template argument list.
3285  return ExprError();
3286  }
3287 
3288  // Make sure that we're referring to a value.
3289  if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3290  Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3291  Diag(D->getLocation(), diag::note_declared_at);
3292  return ExprError();
3293  }
3294 
3295  // Check whether this declaration can be used. Note that we suppress
3296  // this check when we're going to perform argument-dependent lookup
3297  // on this function name, because this might not be the function
3298  // that overload resolution actually selects.
3299  if (DiagnoseUseOfDecl(D, Loc))
3300  return ExprError();
3301 
3302  auto *VD = cast<ValueDecl>(D);
3303 
3304  // Only create DeclRefExpr's for valid Decl's.
3305  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3306  return ExprError();
3307 
3308  // Handle members of anonymous structs and unions. If we got here,
3309  // and the reference is to a class member indirect field, then this
3310  // must be the subject of a pointer-to-member expression.
3311  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3312  if (!indirectField->isCXXClassMember())
3313  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3314  indirectField);
3315 
3316  QualType type = VD->getType();
3317  if (type.isNull())
3318  return ExprError();
3319  ExprValueKind valueKind = VK_PRValue;
3320 
3321  // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3322  // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3323  // is expanded by some outer '...' in the context of the use.
3324  type = type.getNonPackExpansionType();
3325 
3326  switch (D->getKind()) {
3327  // Ignore all the non-ValueDecl kinds.
3328 #define ABSTRACT_DECL(kind)
3329 #define VALUE(type, base)
3330 #define DECL(type, base) case Decl::type:
3331 #include "clang/AST/DeclNodes.inc"
3332  llvm_unreachable("invalid value decl kind");
3333 
3334  // These shouldn't make it here.
3335  case Decl::ObjCAtDefsField:
3336  llvm_unreachable("forming non-member reference to ivar?");
3337 
3338  // Enum constants are always r-values and never references.
3339  // Unresolved using declarations are dependent.
3340  case Decl::EnumConstant:
3341  case Decl::UnresolvedUsingValue:
3342  case Decl::OMPDeclareReduction:
3343  case Decl::OMPDeclareMapper:
3344  valueKind = VK_PRValue;
3345  break;
3346 
3347  // Fields and indirect fields that got here must be for
3348  // pointer-to-member expressions; we just call them l-values for
3349  // internal consistency, because this subexpression doesn't really
3350  // exist in the high-level semantics.
3351  case Decl::Field:
3352  case Decl::IndirectField:
3353  case Decl::ObjCIvar:
3354  assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3355 
3356  // These can't have reference type in well-formed programs, but
3357  // for internal consistency we do this anyway.
3358  type = type.getNonReferenceType();
3359  valueKind = VK_LValue;
3360  break;
3361 
3362  // Non-type template parameters are either l-values or r-values
3363  // depending on the type.
3364  case Decl::NonTypeTemplateParm: {
3365  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3366  type = reftype->getPointeeType();
3367  valueKind = VK_LValue; // even if the parameter is an r-value reference
3368  break;
3369  }
3370 
3371  // [expr.prim.id.unqual]p2:
3372  // If the entity is a template parameter object for a template
3373  // parameter of type T, the type of the expression is const T.
3374  // [...] The expression is an lvalue if the entity is a [...] template
3375  // parameter object.
3376  if (type->isRecordType()) {
3377  type = type.getUnqualifiedType().withConst();
3378  valueKind = VK_LValue;
3379  break;
3380  }
3381 
3382  // For non-references, we need to strip qualifiers just in case
3383  // the template parameter was declared as 'const int' or whatever.
3384  valueKind = VK_PRValue;
3385  type = type.getUnqualifiedType();
3386  break;
3387  }
3388 
3389  case Decl::Var:
3390  case Decl::VarTemplateSpecialization:
3391  case Decl::VarTemplatePartialSpecialization:
3392  case Decl::Decomposition:
3393  case Decl::OMPCapturedExpr:
3394  // In C, "extern void blah;" is valid and is an r-value.
3395  if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3396  type->isVoidType()) {
3397  valueKind = VK_PRValue;
3398  break;
3399  }
3400  [[fallthrough]];
3401 
3402  case Decl::ImplicitParam:
3403  case Decl::ParmVar: {
3404  // These are always l-values.
3405  valueKind = VK_LValue;
3406  type = type.getNonReferenceType();
3407 
3408  // FIXME: Does the addition of const really only apply in
3409  // potentially-evaluated contexts? Since the variable isn't actually
3410  // captured in an unevaluated context, it seems that the answer is no.
3411  if (!isUnevaluatedContext()) {
3412  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3413  if (!CapturedType.isNull())
3414  type = CapturedType;
3415  }
3416 
3417  break;
3418  }
3419 
3420  case Decl::Binding:
3421  // These are always lvalues.
3422  valueKind = VK_LValue;
3423  type = type.getNonReferenceType();
3424  break;
3425 
3426  case Decl::Function: {
3427  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3430  valueKind = VK_PRValue;
3431  break;
3432  }
3433  }
3434 
3435  const FunctionType *fty = type->castAs<FunctionType>();
3436 
3437  // If we're referring to a function with an __unknown_anytype
3438  // result type, make the entire expression __unknown_anytype.
3439  if (fty->getReturnType() == Context.UnknownAnyTy) {
3441  valueKind = VK_PRValue;
3442  break;
3443  }
3444 
3445  // Functions are l-values in C++.
3446  if (getLangOpts().CPlusPlus) {
3447  valueKind = VK_LValue;
3448  break;
3449  }
3450 
3451  // C99 DR 316 says that, if a function type comes from a
3452  // function definition (without a prototype), that type is only
3453  // used for checking compatibility. Therefore, when referencing
3454  // the function, we pretend that we don't have the full function
3455  // type.
3456  if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3458  fty->getExtInfo());
3459 
3460  // Functions are r-values in C.
3461  valueKind = VK_PRValue;
3462  break;
3463  }
3464 
3465  case Decl::CXXDeductionGuide:
3466  llvm_unreachable("building reference to deduction guide");
3467 
3468  case Decl::MSProperty:
3469  case Decl::MSGuid:
3470  case Decl::TemplateParamObject:
3471  // FIXME: Should MSGuidDecl and template parameter objects be subject to
3472  // capture in OpenMP, or duplicated between host and device?
3473  valueKind = VK_LValue;
3474  break;
3475 
3476  case Decl::UnnamedGlobalConstant:
3477  valueKind = VK_LValue;
3478  break;
3479 
3480  case Decl::CXXMethod:
3481  // If we're referring to a method with an __unknown_anytype
3482  // result type, make the entire expression __unknown_anytype.
3483  // This should only be possible with a type written directly.
3484  if (const FunctionProtoType *proto =
3485  dyn_cast<FunctionProtoType>(VD->getType()))
3486  if (proto->getReturnType() == Context.UnknownAnyTy) {
3488  valueKind = VK_PRValue;
3489  break;
3490  }
3491 
3492  // C++ methods are l-values if static, r-values if non-static.
3493  if (cast<CXXMethodDecl>(VD)->isStatic()) {
3494  valueKind = VK_LValue;
3495  break;
3496  }
3497  [[fallthrough]];
3498 
3499  case Decl::CXXConversion:
3500  case Decl::CXXDestructor:
3501  case Decl::CXXConstructor:
3502  valueKind = VK_PRValue;
3503  break;
3504  }
3505 
3506  auto *E =
3507  BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3508  /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3509  // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3510  // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3511  // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3512  // diagnostics).
3513  if (VD->isInvalidDecl() && E)
3514  return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3515  return E;
3516 }
3517 
3518 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3519  SmallString<32> &Target) {
3520  Target.resize(CharByteWidth * (Source.size() + 1));
3521  char *ResultPtr = &Target[0];
3522  const llvm::UTF8 *ErrorPtr;
3523  bool success =
3524  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3525  (void)success;
3526  assert(success);
3527  Target.resize(ResultPtr - &Target[0]);
3528 }
3529 
3532  // Pick the current block, lambda, captured statement or function.
3533  Decl *currentDecl = nullptr;
3534  if (const BlockScopeInfo *BSI = getCurBlock())
3535  currentDecl = BSI->TheDecl;
3536  else if (const LambdaScopeInfo *LSI = getCurLambda())
3537  currentDecl = LSI->CallOperator;
3538  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3539  currentDecl = CSI->TheCapturedDecl;
3540  else
3541  currentDecl = getCurFunctionOrMethodDecl();
3542 
3543  if (!currentDecl) {
3544  Diag(Loc, diag::ext_predef_outside_function);
3545  currentDecl = Context.getTranslationUnitDecl();
3546  }
3547 
3548  QualType ResTy;
3549  StringLiteral *SL = nullptr;
3550  if (cast<DeclContext>(currentDecl)->isDependentContext())
3551  ResTy = Context.DependentTy;
3552  else {
3553  // Pre-defined identifiers are of type char[x], where x is the length of
3554  // the string.
3555  auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3556  unsigned Length = Str.length();
3557 
3558  llvm::APInt LengthI(32, Length + 1);
3560  ResTy =
3562  SmallString<32> RawChars;
3564  Str, RawChars);
3565  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3567  /*IndexTypeQuals*/ 0);
3569  /*Pascal*/ false, ResTy, Loc);
3570  } else {
3572  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3574  /*IndexTypeQuals*/ 0);
3576  /*Pascal*/ false, ResTy, Loc);
3577  }
3578  }
3579 
3580  return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3581 }
3582 
3584  SourceLocation LParen,
3585  SourceLocation RParen,
3586  TypeSourceInfo *TSI) {
3587  return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3588 }
3589 
3591  SourceLocation LParen,
3592  SourceLocation RParen,
3593  ParsedType ParsedTy) {
3594  TypeSourceInfo *TSI = nullptr;
3595  QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3596 
3597  if (Ty.isNull())
3598  return ExprError();
3599  if (!TSI)
3600  TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3601 
3602  return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3603 }
3604 
3607 
3608  switch (Kind) {
3609  default: llvm_unreachable("Unknown simple primary expr!");
3610  case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3611  case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3612  case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3613  case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3614  case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3615  case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3616  case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3617  }
3618 
3619  return BuildPredefinedExpr(Loc, IK);
3620 }
3621 
3623  SmallString<16> CharBuffer;
3624  bool Invalid = false;
3625  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3626  if (Invalid)
3627  return ExprError();
3628 
3629  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3630  PP, Tok.getKind());
3631  if (Literal.hadError())
3632  return ExprError();
3633 
3634  QualType Ty;
3635  if (Literal.isWide())
3636  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3637  else if (Literal.isUTF8() && getLangOpts().C2x)
3638  Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3639  else if (Literal.isUTF8() && getLangOpts().Char8)
3640  Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3641  else if (Literal.isUTF16())
3642  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3643  else if (Literal.isUTF32())
3644  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3645  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3646  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3647  else
3648  Ty = Context.CharTy; // 'x' -> char in C++;
3649  // u8'x' -> char in C11-C17 and in C++ without char8_t.
3650 
3652  if (Literal.isWide())
3654  else if (Literal.isUTF16())
3656  else if (Literal.isUTF32())
3658  else if (Literal.isUTF8())
3660 
3661  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3662  Tok.getLocation());
3663 
3664  if (Literal.getUDSuffix().empty())
3665  return Lit;
3666 
3667  // We're building a user-defined literal.
3668  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3669  SourceLocation UDSuffixLoc =
3670  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3671 
3672  // Make sure we're allowed user-defined literals here.
3673  if (!UDLScope)
3674  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3675 
3676  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3677  // operator "" X (ch)
3678  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3679  Lit, Tok.getLocation());
3680 }
3681 
3683  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3684  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3685  Context.IntTy, Loc);
3686 }
3687 
3689  QualType Ty, SourceLocation Loc) {
3690  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3691 
3692  using llvm::APFloat;
3693  APFloat Val(Format);
3694 
3695  APFloat::opStatus result = Literal.GetFloatValue(Val);
3696 
3697  // Overflow is always an error, but underflow is only an error if
3698  // we underflowed to zero (APFloat reports denormals as underflow).
3699  if ((result & APFloat::opOverflow) ||
3700  ((result & APFloat::opUnderflow) && Val.isZero())) {
3701  unsigned diagnostic;
3702  SmallString<20> buffer;
3703  if (result & APFloat::opOverflow) {
3704  diagnostic = diag::warn_float_overflow;
3705  APFloat::getLargest(Format).toString(buffer);
3706  } else {
3707  diagnostic = diag::warn_float_underflow;
3708  APFloat::getSmallest(Format).toString(buffer);
3709  }
3710 
3711  S.Diag(Loc, diagnostic)
3712  << Ty
3713  << StringRef(buffer.data(), buffer.size());
3714  }
3715 
3716  bool isExact = (result == APFloat::opOK);
3717  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3718 }
3719 
3721  assert(E && "Invalid expression");
3722 
3723  if (E->isValueDependent())
3724  return false;
3725 
3726  QualType QT = E->getType();
3727  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3728  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3729  return true;
3730  }
3731 
3732  llvm::APSInt ValueAPS;
3733  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3734 
3735  if (R.isInvalid())
3736  return true;
3737 
3738  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3739  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3740  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3741  << toString(ValueAPS, 10) << ValueIsPositive;
3742  return true;
3743  }
3744 
3745  return false;
3746 }
3747 
3749  // Fast path for a single digit (which is quite common). A single digit
3750  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3751  if (Tok.getLength() == 1) {
3752  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3753  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3754  }
3755 
3756  SmallString<128> SpellingBuffer;
3757  // NumericLiteralParser wants to overread by one character. Add padding to
3758  // the buffer in case the token is copied to the buffer. If getSpelling()
3759  // returns a StringRef to the memory buffer, it should have a null char at
3760  // the EOF, so it is also safe.
3761  SpellingBuffer.resize(Tok.getLength() + 1);
3762 
3763  // Get the spelling of the token, which eliminates trigraphs, etc.
3764  bool Invalid = false;
3765  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3766  if (Invalid)
3767  return ExprError();
3768 
3769  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3772  if (Literal.hadError)
3773  return ExprError();
3774 
3775  if (Literal.hasUDSuffix()) {
3776  // We're building a user-defined literal.
3777  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3778  SourceLocation UDSuffixLoc =
3779  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3780 
3781  // Make sure we're allowed user-defined literals here.
3782  if (!UDLScope)
3783  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3784 
3785  QualType CookedTy;
3786  if (Literal.isFloatingLiteral()) {
3787  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3788  // long double, the literal is treated as a call of the form
3789  // operator "" X (f L)
3790  CookedTy = Context.LongDoubleTy;
3791  } else {
3792  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3793  // unsigned long long, the literal is treated as a call of the form
3794  // operator "" X (n ULL)
3795  CookedTy = Context.UnsignedLongLongTy;
3796  }
3797 
3798  DeclarationName OpName =
3800  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3801  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3802 
3803  SourceLocation TokLoc = Tok.getLocation();
3804 
3805  // Perform literal operator lookup to determine if we're building a raw
3806  // literal or a cooked one.
3807  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3808  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3809  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3810  /*AllowStringTemplatePack*/ false,
3811  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3813  // Lookup failure for imaginary constants isn't fatal, there's still the
3814  // GNU extension producing _Complex types.
3815  break;
3816  case LOLR_Error:
3817  return ExprError();
3818  case LOLR_Cooked: {
3819  Expr *Lit;
3820  if (Literal.isFloatingLiteral()) {
3821  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3822  } else {
3824  if (Literal.GetIntegerValue(ResultVal))
3825  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3826  << /* Unsigned */ 1;
3827  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3828  Tok.getLocation());
3829  }
3830  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3831  }
3832 
3833  case LOLR_Raw: {
3834  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3835  // literal is treated as a call of the form
3836  // operator "" X ("n")
3837  unsigned Length = Literal.getUDSuffixOffset();
3840  llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3841  Expr *Lit =
3842  StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3844  /*Pascal*/ false, StrTy, &TokLoc, 1);
3845  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3846  }
3847 
3848  case LOLR_Template: {
3849  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3850  // template), L is treated as a call fo the form
3851  // operator "" X <'c1', 'c2', ... 'ck'>()
3852  // where n is the source character sequence c1 c2 ... ck.
3853  TemplateArgumentListInfo ExplicitArgs;
3854  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3855  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3856  llvm::APSInt Value(CharBits, CharIsUnsigned);
3857  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3858  Value = TokSpelling[I];
3860  TemplateArgumentLocInfo ArgInfo;
3861  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3862  }
3863  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3864  &ExplicitArgs);
3865  }
3867  llvm_unreachable("unexpected literal operator lookup result");
3868  }
3869  }
3870 
3871  Expr *Res;
3872 
3873  if (Literal.isFixedPointLiteral()) {
3874  QualType Ty;
3875 
3876  if (Literal.isAccum) {
3877  if (Literal.isHalf) {
3878  Ty = Context.ShortAccumTy;
3879  } else if (Literal.isLong) {
3880  Ty = Context.LongAccumTy;
3881  } else {
3882  Ty = Context.AccumTy;
3883  }
3884  } else if (Literal.isFract) {
3885  if (Literal.isHalf) {
3886  Ty = Context.ShortFractTy;
3887  } else if (Literal.isLong) {
3888  Ty = Context.LongFractTy;
3889  } else {
3890  Ty = Context.FractTy;
3891  }
3892  }
3893 
3894  if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3895 
3896  bool isSigned = !Literal.isUnsigned;
3897  unsigned scale = Context.getFixedPointScale(Ty);
3898  unsigned bit_width = Context.getTypeInfo(Ty).Width;
3899 
3900  llvm::APInt Val(bit_width, 0, isSigned);
3901  bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3902  bool ValIsZero = Val.isZero() && !Overflowed;
3903 
3904  auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3905  if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3906  // Clause 6.4.4 - The value of a constant shall be in the range of
3907  // representable values for its type, with exception for constants of a
3908  // fract type with a value of exactly 1; such a constant shall denote
3909  // the maximal value for the type.
3910  --Val;
3911  else if (Val.ugt(MaxVal) || Overflowed)
3912  Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3913 
3915  Tok.getLocation(), scale);
3916  } else if (Literal.isFloatingLiteral()) {
3917  QualType Ty;
3918  if (Literal.isHalf){
3919  if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3920  Ty = Context.HalfTy;
3921  else {
3922  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3923  return ExprError();
3924  }
3925  } else if (Literal.isFloat)
3926  Ty = Context.FloatTy;
3927  else if (Literal.isLong)
3928  Ty = Context.LongDoubleTy;
3929  else if (Literal.isFloat16)
3930  Ty = Context.Float16Ty;
3931  else if (Literal.isFloat128)
3932  Ty = Context.Float128Ty;
3933  else
3934  Ty = Context.DoubleTy;
3935 
3936  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3937 
3938  if (Ty == Context.DoubleTy) {
3939  if (getLangOpts().SinglePrecisionConstants) {
3940  if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3941  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3942  }
3943  } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3944  "cl_khr_fp64", getLangOpts())) {
3945  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3946  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3947  << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3948  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3949  }
3950  }
3951  } else if (!Literal.isIntegerLiteral()) {
3952  return ExprError();
3953  } else {
3954  QualType Ty;
3955 
3956  // 'z/uz' literals are a C++2b feature.
3957  if (Literal.isSizeT)
3960  ? diag::warn_cxx20_compat_size_t_suffix
3961  : diag::ext_cxx2b_size_t_suffix
3962  : diag::err_cxx2b_size_t_suffix);
3963 
3964  // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3965  // but we do not currently support the suffix in C++ mode because it's not
3966  // entirely clear whether WG21 will prefer this suffix to return a library
3967  // type such as std::bit_int instead of returning a _BitInt.
3968  if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3969  PP.Diag(Tok.getLocation(), getLangOpts().C2x
3970  ? diag::warn_c2x_compat_bitint_suffix
3971  : diag::ext_c2x_bitint_suffix);
3972 
3973  // Get the value in the widest-possible width. What is "widest" depends on
3974  // whether the literal is a bit-precise integer or not. For a bit-precise
3975  // integer type, try to scan the source to determine how many bits are
3976  // needed to represent the value. This may seem a bit expensive, but trying
3977  // to get the integer value from an overly-wide APInt is *extremely*
3978  // expensive, so the naive approach of assuming
3979  // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3980  unsigned BitsNeeded =
3981  Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3982  Literal.getLiteralDigits(), Literal.getRadix())
3984  llvm::APInt ResultVal(BitsNeeded, 0);
3985 
3986  if (Literal.GetIntegerValue(ResultVal)) {
3987  // If this value didn't fit into uintmax_t, error and force to ull.
3988  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3989  << /* Unsigned */ 1;
3991  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3992  "long long is not intmax_t?");
3993  } else {
3994  // If this value fits into a ULL, try to figure out what else it fits into
3995  // according to the rules of C99 6.4.4.1p5.
3996 
3997  // Octal, Hexadecimal, and integers with a U suffix are allowed to
3998  // be an unsigned int.
3999  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4000 
4001  // Check from smallest to largest, picking the smallest type we can.
4002  unsigned Width = 0;
4003 
4004  // Microsoft specific integer suffixes are explicitly sized.
4005  if (Literal.MicrosoftInteger) {
4006  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4007  Width = 8;
4008  Ty = Context.CharTy;
4009  } else {
4010  Width = Literal.MicrosoftInteger;
4011  Ty = Context.getIntTypeForBitwidth(Width,
4012  /*Signed=*/!Literal.isUnsigned);
4013  }
4014  }
4015 
4016  // Bit-precise integer literals are automagically-sized based on the
4017  // width required by the literal.
4018  if (Literal.isBitInt) {
4019  // The signed version has one more bit for the sign value. There are no
4020  // zero-width bit-precise integers, even if the literal value is 0.
4021  Width = std::max(ResultVal.getActiveBits(), 1u) +
4022  (Literal.isUnsigned ? 0u : 1u);
4023 
4024  // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4025  // and reset the type to the largest supported width.
4026  unsigned int MaxBitIntWidth =
4028  if (Width > MaxBitIntWidth) {
4029  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4030  << Literal.isUnsigned;
4031  Width = MaxBitIntWidth;
4032  }
4033 
4034  // Reset the result value to the smaller APInt and select the correct
4035  // type to be used. Note, we zext even for signed values because the
4036  // literal itself is always an unsigned value (a preceeding - is a
4037  // unary operator, not part of the literal).
4038  ResultVal = ResultVal.zextOrTrunc(Width);
4039  Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4040  }
4041 
4042  // Check C++2b size_t literals.
4043  if (Literal.isSizeT) {
4044  assert(!Literal.MicrosoftInteger &&
4045  "size_t literals can't be Microsoft literals");
4046  unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4048 
4049  // Does it fit in size_t?
4050  if (ResultVal.isIntN(SizeTSize)) {
4051  // Does it fit in ssize_t?
4052  if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4053  Ty = Context.getSignedSizeType();
4054  else if (AllowUnsigned)
4055  Ty = Context.getSizeType();
4056  Width = SizeTSize;
4057  }
4058  }
4059 
4060  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4061  !Literal.isSizeT) {
4062  // Are int/unsigned possibilities?
4063  unsigned IntSize = Context.getTargetInfo().getIntWidth();
4064 
4065  // Does it fit in a unsigned int?
4066  if (ResultVal.isIntN(IntSize)) {
4067  // Does it fit in a signed int?
4068  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4069  Ty = Context.IntTy;
4070  else if (AllowUnsigned)
4071  Ty = Context.UnsignedIntTy;
4072  Width = IntSize;
4073  }
4074  }
4075 
4076  // Are long/unsigned long possibilities?
4077  if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4078  unsigned LongSize = Context.getTargetInfo().getLongWidth();
4079 
4080  // Does it fit in a unsigned long?
4081  if (ResultVal.isIntN(LongSize)) {
4082  // Does it fit in a signed long?
4083  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4084  Ty = Context.LongTy;
4085  else if (AllowUnsigned)
4086  Ty = Context.UnsignedLongTy;
4087  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4088  // is compatible.
4089  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4090  const unsigned LongLongSize =
4092  Diag(Tok.getLocation(),
4094  ? Literal.isLong
4095  ? diag::warn_old_implicitly_unsigned_long_cxx
4096  : /*C++98 UB*/ diag::
4097  ext_old_implicitly_unsigned_long_cxx
4098  : diag::warn_old_implicitly_unsigned_long)
4099  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4100  : /*will be ill-formed*/ 1);
4101  Ty = Context.UnsignedLongTy;
4102  }
4103  Width = LongSize;
4104  }
4105  }
4106 
4107  // Check long long if needed.
4108  if (Ty.isNull() && !Literal.isSizeT) {
4109  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4110 
4111  // Does it fit in a unsigned long long?
4112  if (ResultVal.isIntN(LongLongSize)) {
4113  // Does it fit in a signed long long?
4114  // To be compatible with MSVC, hex integer literals ending with the
4115  // LL or i64 suffix are always signed in Microsoft mode.
4116  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4117  (getLangOpts().MSVCCompat && Literal.isLongLong)))
4118  Ty = Context.LongLongTy;
4119  else if (AllowUnsigned)
4121  Width = LongLongSize;
4122 
4123  // 'long long' is a C99 or C++11 feature, whether the literal
4124  // explicitly specified 'long long' or we needed the extra width.
4125  if (getLangOpts().CPlusPlus)
4126  Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4127  ? diag::warn_cxx98_compat_longlong
4128  : diag::ext_cxx11_longlong);
4129  else if (!getLangOpts().C99)
4130  Diag(Tok.getLocation(), diag::ext_c99_longlong);
4131  }
4132  }
4133 
4134  // If we still couldn't decide a type, we either have 'size_t' literal
4135  // that is out of range, or a decimal literal that does not fit in a
4136  // signed long long and has no U suffix.
4137  if (Ty.isNull()) {
4138  if (Literal.isSizeT)
4139  Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4140  << Literal.isUnsigned;
4141  else
4142  Diag(Tok.getLocation(),
4143  diag::ext_integer_literal_too_large_for_signed);
4146  }
4147 
4148  if (ResultVal.getBitWidth() != Width)
4149  ResultVal = ResultVal.trunc(Width);
4150  }
4151  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4152  }
4153 
4154  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4155  if (Literal.isImaginary) {
4156  Res = new (Context) ImaginaryLiteral(Res,
4157  Context.getComplexType(Res->getType()));
4158 
4159  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4160  }
4161  return Res;
4162 }
4163 
4165  assert(E && "ActOnParenExpr() missing expr");
4166  QualType ExprTy = E->getType();
4167  if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4168  !E->isLValue() && ExprTy->hasFloatingRepresentation())
4169  return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4170  return new (Context) ParenExpr(L, R, E);
4171 }
4172 
4174  SourceLocation Loc,
4175  SourceRange ArgRange) {
4176  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4177  // scalar or vector data type argument..."
4178  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4179  // type (C99 6.2.5p18) or void.
4180  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4181  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4182  << T << ArgRange;
4183  return true;
4184  }
4185 
4186  assert((T->isVoidType() || !T->isIncompleteType()) &&
4187  "Scalar types should always be complete");
4188  return false;
4189 }
4190 
4192  SourceLocation Loc,
4193  SourceRange ArgRange,
4194  UnaryExprOrTypeTrait TraitKind) {
4195  // Invalid types must be hard errors for SFINAE in C++.
4196  if (S.LangOpts.CPlusPlus)
4197  return true;
4198 
4199  // C99 6.5.3.4p1:
4200  if (T->isFunctionType() &&
4201  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4202  TraitKind == UETT_PreferredAlignOf)) {
4203  // sizeof(function)/alignof(function) is allowed as an extension.
4204  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4205  << getTraitSpelling(TraitKind) << ArgRange;
4206  return false;
4207  }
4208 
4209  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4210  // this is an error (OpenCL v1.1 s6.3.k)
4211  if (T->isVoidType()) {
4212  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4213  : diag::ext_sizeof_alignof_void_type;
4214  S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4215  return false;
4216  }
4217 
4218  return true;
4219 }
4220 
4222  SourceLocation Loc,
4223  SourceRange ArgRange,
4224  UnaryExprOrTypeTrait TraitKind) {
4225  // Reject sizeof(interface) and sizeof(interface<proto>) if the
4226  // runtime doesn't allow it.
4228  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4229  << T << (TraitKind == UETT_SizeOf)
4230  << ArgRange;
4231  return true;
4232  }
4233 
4234  return false;
4235 }
4236 
4237 /// Check whether E is a pointer from a decayed array type (the decayed
4238 /// pointer type is equal to T) and emit a warning if it is.
4240  Expr *E) {
4241  // Don't warn if the operation changed the type.
4242  if (T != E->getType())
4243  return;
4244 
4245  // Now look for array decays.
4246  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4247  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4248  return;
4249 
4250  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4251  << ICE->getType()
4252  << ICE->getSubExpr()->getType();
4253 }
4254 
4255 /// Check the constraints on expression operands to unary type expression
4256 /// and type traits.
4257 ///
4258 /// Completes any types necessary and validates the constraints on the operand
4259 /// expression. The logic mostly mirrors the type-based overload, but may modify
4260 /// the expression as it completes the type for that expression through template
4261 /// instantiation, etc.
4263  UnaryExprOrTypeTrait ExprKind) {
4264  QualType ExprTy = E->getType();
4265  assert(!ExprTy->isReferenceType());
4266 
4267  bool IsUnevaluatedOperand =
4268  (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4269  ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4270  if (IsUnevaluatedOperand) {
4271  ExprResult Result = CheckUnevaluatedOperand(E);
4272  if (Result.isInvalid())
4273  return true;
4274  E = Result.get();
4275  }
4276 
4277  // The operand for sizeof and alignof is in an unevaluated expression context,
4278  // so side effects could result in unintended consequences.
4279  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4280  // used to build SFINAE gadgets.
4281  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4282  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4283  !E->isInstantiationDependent() &&
4284  !E->getType()->isVariableArrayType() &&
4285  E->HasSideEffects(Context, false))
4286  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4287 
4288  if (ExprKind == UETT_VecStep)
4289  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4290  E->getSourceRange());
4291 
4292  // Explicitly list some types as extensions.
4293  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4294  E->getSourceRange(), ExprKind))
4295  return false;
4296 
4297  // 'alignof' applied to an expression only requires the base element type of
4298  // the expression to be complete. 'sizeof' requires the expression's type to
4299  // be complete (and will attempt to complete it if it's an array of unknown
4300  // bound).
4301  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4304  diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4305  getTraitSpelling(ExprKind), E->getSourceRange()))
4306  return true;
4307  } else {
4309  E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4310  getTraitSpelling(ExprKind), E->getSourceRange()))
4311  return true;
4312  }
4313 
4314  // Completing the expression's type may have changed it.
4315  ExprTy = E->getType();
4316  assert(!ExprTy->isReferenceType());
4317 
4318  if (ExprTy->isFunctionType()) {
4319  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4320  << getTraitSpelling(ExprKind) << E->getSourceRange();
4321  return true;
4322  }
4323 
4324  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4325  E->getSourceRange(), ExprKind))
4326  return true;
4327 
4328  if (ExprKind == UETT_SizeOf) {
4329  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4330  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4331  QualType OType = PVD->getOriginalType();
4332  QualType Type = PVD->getType();
4333  if (Type->isPointerType() && OType->isArrayType()) {
4334  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4335  << Type << OType;
4336  Diag(PVD->getLocation(), diag::note_declared_at);
4337  }
4338  }
4339  }
4340 
4341  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4342  // decays into a pointer and returns an unintended result. This is most
4343  // likely a typo for "sizeof(array) op x".
4344  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4345  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4346  BO->getLHS());
4347  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4348  BO->getRHS());
4349  }
4350  }
4351 
4352  return false;
4353 }
4354 
4355 /// Check the constraints on operands to unary expression and type
4356 /// traits.
4357 ///
4358 /// This will complete any types necessary, and validate the various constraints
4359 /// on those operands.
4360 ///
4361 /// The UsualUnaryConversions() function is *not* called by this routine.
4362 /// C99 6.3.2.1p[2-4] all state:
4363 /// Except when it is the operand of the sizeof operator ...
4364 ///
4365 /// C++ [expr.sizeof]p4
4366 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4367 /// standard conversions are not applied to the operand of sizeof.
4368 ///
4369 /// This policy is followed for all of the unary trait expressions.
4371  SourceLocation OpLoc,
4372  SourceRange ExprRange,
4373  UnaryExprOrTypeTrait ExprKind) {
4374  if (ExprType->isDependentType())
4375  return false;
4376 
4377  // C++ [expr.sizeof]p2:
4378  // When applied to a reference or a reference type, the result
4379  // is the size of the referenced type.
4380  // C++11 [expr.alignof]p3:
4381  // When alignof is applied to a reference type, the result
4382  // shall be the alignment of the referenced type.
4383  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4384  ExprType = Ref->getPointeeType();
4385 
4386  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4387  // When alignof or _Alignof is applied to an array type, the result
4388  // is the alignment of the element type.
4389  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4390  ExprKind == UETT_OpenMPRequiredSimdAlign)
4391  ExprType = Context.getBaseElementType(ExprType);
4392 
4393  if (ExprKind == UETT_VecStep)
4394  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4395 
4396  // Explicitly list some types as extensions.
4397  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4398  ExprKind))
4399  return false;
4400 
4402  OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4403  getTraitSpelling(ExprKind), ExprRange))
4404  return true;
4405 
4406  if (ExprType->isFunctionType()) {
4407  Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4408  << getTraitSpelling(ExprKind) << ExprRange;
4409  return true;
4410  }
4411 
4412  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4413  ExprKind))
4414  return true;
4415 
4416  return false;
4417 }
4418 
4419 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4420  // Cannot know anything else if the expression is dependent.
4421  if (E->isTypeDependent())
4422  return false;
4423 
4424  if (E->getObjectKind() == OK_BitField) {
4425  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4426  << 1 << E->getSourceRange();
4427  return true;
4428  }
4429 
4430  ValueDecl *D = nullptr;
4431  Expr *Inner = E->IgnoreParens();
4432  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4433  D = DRE->getDecl();
4434  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4435  D = ME->getMemberDecl();
4436  }
4437 
4438  // If it's a field, require the containing struct to have a
4439  // complete definition so that we can compute the layout.
4440  //
4441  // This can happen in C++11 onwards, either by naming the member
4442  // in a way that is not transformed into a member access expression
4443  // (in an unevaluated operand, for instance), or by naming the member
4444  // in a trailing-return-type.
4445  //
4446  // For the record, since __alignof__ on expressions is a GCC
4447  // extension, GCC seems to permit this but always gives the
4448  // nonsensical answer 0.
4449  //
4450  // We don't really need the layout here --- we could instead just
4451  // directly check for all the appropriate alignment-lowing
4452  // attributes --- but that would require duplicating a lot of
4453  // logic that just isn't worth duplicating for such a marginal
4454  // use-case.
4455  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4456  // Fast path this check, since we at least know the record has a
4457  // definition if we can find a member of it.
4458  if (!FD->getParent()->isCompleteDefinition()) {
4459  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4460  << E->getSourceRange();
4461  return true;
4462  }
4463 
4464  // Otherwise, if it's a field, and the field doesn't have
4465  // reference type, then it must have a complete type (or be a
4466  // flexible array member, which we explicitly want to
4467  // white-list anyway), which makes the following checks trivial.
4468  if (!FD->getType()->isReferenceType())
4469  return false;
4470  }
4471 
4472  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4473 }
4474 
4476  E = E->IgnoreParens();
4477 
4478  // Cannot know anything else if the expression is dependent.
4479  if (E->isTypeDependent())
4480  return false;
4481 
4482  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4483 }
4484 
4486  CapturingScopeInfo *CSI) {
4487  assert(T->isVariablyModifiedType());
4488  assert(CSI != nullptr);
4489 
4490  // We're going to walk down into the type and look for VLA expressions.
4491  do {
4492  const Type *Ty = T.getTypePtr();
4493  switch (Ty->getTypeClass()) {
4494 #define TYPE(Class, Base)
4495 #define ABSTRACT_TYPE(Class, Base)
4496 #define NON_CANONICAL_TYPE(Class, Base)
4497 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4498 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4499 #include "clang/AST/TypeNodes.inc"
4500  T = QualType();
4501  break;
4502  // These types are never variably-modified.
4503  case Type::Builtin:
4504  case Type::Complex:
4505  case Type::Vector:
4506  case Type::ExtVector:
4507  case Type::ConstantMatrix:
4508  case Type::Record:
4509  case Type::Enum:
4510  case Type::TemplateSpecialization:
4511  case Type::ObjCObject:
4512  case Type::ObjCInterface:
4513  case Type::ObjCObjectPointer:
4514  case Type::ObjCTypeParam:
4515  case Type::Pipe:
4516  case Type::BitInt:
4517  llvm_unreachable("type class is never variably-modified!");
4518  case Type::Elaborated:
4519  T = cast<ElaboratedType>(Ty)->getNamedType();
4520  break;
4521  case Type::Adjusted:
4522  T = cast<AdjustedType>(Ty)->getOriginalType();
4523  break;
4524  case Type::Decayed:
4525  T = cast<DecayedType>(Ty)->getPointeeType();
4526  break;
4527  case Type::Pointer:
4528  T = cast<PointerType>(Ty)->getPointeeType();
4529  break;
4530  case Type::BlockPointer:
4531  T = cast<BlockPointerType>(Ty)->getPointeeType();
4532  break;
4533  case Type::LValueReference:
4534  case Type::RValueReference:
4535  T = cast<ReferenceType>(Ty)->getPointeeType();
4536  break;
4537  case Type::MemberPointer:
4538  T = cast<MemberPointerType>(Ty)->getPointeeType();
4539  break;
4540  case Type::ConstantArray:
4541  case Type::IncompleteArray:
4542  // Losing element qualification here is fine.
4543  T = cast<ArrayType>(Ty)->getElementType();
4544  break;
4545  case Type::VariableArray: {
4546  // Losing element qualification here is fine.
4547  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4548 
4549  // Unknown size indication requires no size computation.
4550  // Otherwise, evaluate and record it.
4551  auto Size = VAT->getSizeExpr();
4552  if (Size && !CSI->isVLATypeCaptured(VAT) &&
4553  (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4554  CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4555 
4556  T = VAT->getElementType();
4557  break;
4558  }
4559  case Type::FunctionProto:
4560  case Type::FunctionNoProto:
4561  T = cast<FunctionType>(Ty)->getReturnType();
4562  break;
4563  case Type::Paren:
4564  case Type::TypeOf:
4565  case Type::UnaryTransform:
4566  case Type::Attributed:
4567  case Type::BTFTagAttributed:
4568  case Type::SubstTemplateTypeParm:
4569  case Type::MacroQualified:
4570  // Keep walking after single level desugaring.
4571  T = T.getSingleStepDesugaredType(Context);
4572  break;
4573  case Type::Typedef:
4574  T = cast<TypedefType>(Ty)->desugar();
4575  break;
4576  case Type::Decltype:
4577  T = cast<DecltypeType>(Ty)->desugar();
4578  break;
4579  case Type::Using:
4580  T = cast<UsingType>(Ty)->desugar();
4581  break;
4582  case Type::Auto:
4583  case Type::DeducedTemplateSpecialization:
4584  T = cast<DeducedType>(Ty)->getDeducedType();
4585  break;
4586  case Type::TypeOfExpr:
4587  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4588  break;
4589  case Type::Atomic:
4590  T = cast<AtomicType>(Ty)->getValueType();
4591  break;
4592  }
4593  } while (!T.isNull() && T->isVariablyModifiedType());
4594 }
4595 
4596 /// Build a sizeof or alignof expression given a type operand.
4597 ExprResult
4599  SourceLocation OpLoc,
4600  UnaryExprOrTypeTrait ExprKind,
4601  SourceRange R) {
4602  if (!TInfo)
4603  return ExprError();
4604 
4605  QualType T = TInfo->getType();
4606 
4607  if (!T->isDependentType() &&
4608  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4609  return ExprError();
4610 
4611  if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4612  if (auto *TT = T->getAs<TypedefType>()) {
4613  for (auto I = FunctionScopes.rbegin(),
4614  E = std::prev(FunctionScopes.rend());
4615  I != E; ++I) {
4616  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4617  if (CSI == nullptr)
4618  break;
4619  DeclContext *DC = nullptr;
4620  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4621  DC = LSI->CallOperator;
4622  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4623  DC = CRSI->TheCapturedDecl;
4624  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4625  DC = BSI->TheDecl;
4626  if (DC) {
4627  if (DC->containsDecl(TT->getDecl()))
4628  break;
4630  }
4631  }
4632  }
4633  }
4634 
4635  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4636  if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4637  TInfo->getType()->isVariablyModifiedType())
4638  TInfo = TransformToPotentiallyEvaluated(TInfo);
4639 
4640  return new (Context) UnaryExprOrTypeTraitExpr(
4641  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4642 }
4643 
4644 /// Build a sizeof or alignof expression given an expression
4645 /// operand.
4646 ExprResult
4648  UnaryExprOrTypeTrait ExprKind) {
4650  if (PE.isInvalid())
4651  return ExprError();
4652 
4653  E = PE.get();
4654 
4655  // Verify that the operand is valid.
4656  bool isInvalid = false;
4657  if (E->isTypeDependent()) {
4658  // Delay type-checking for type-dependent expressions.
4659  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4660  isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4661  } else if (ExprKind == UETT_VecStep) {
4663  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4664  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4665  isInvalid = true;
4666  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4667  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4668  isInvalid = true;
4669  } else {
4670  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4671  }
4672 
4673  if (isInvalid)
4674  return ExprError();
4675 
4676  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4678  if (PE.isInvalid()) return ExprError();
4679  E = PE.get();
4680  }
4681 
4682  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4683  return new (Context) UnaryExprOrTypeTraitExpr(
4684  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4685 }
4686 
4687 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4688 /// expr and the same for @c alignof and @c __alignof
4689 /// Note that the ArgRange is invalid if isType is false.
4690 ExprResult
4692  UnaryExprOrTypeTrait ExprKind, bool IsType,
4693  void *TyOrEx, SourceRange ArgRange) {
4694  // If error parsing type, ignore.
4695  if (!TyOrEx) return ExprError();
4696 
4697  if (IsType) {
4698  TypeSourceInfo *TInfo;
4699  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4700  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4701  }
4702 
4703  Expr *ArgEx = (Expr *)TyOrEx;
4704  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4705  return Result;
4706 }
4707 
4709  bool IsReal) {
4710  if (V.get()->isTypeDependent())
4711  return S.Context.DependentTy;
4712 
4713  // _Real and _Imag are only l-values for normal l-values.
4714  if (V.get()->getObjectKind() != OK_Ordinary) {
4715  V = S.DefaultLvalueConversion(V.get());
4716  if (V.isInvalid())
4717  return QualType();
4718  }
4719 
4720  // These operators return the element type of a complex type.
4721  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4722  return CT->getElementType();
4723 
4724  // Otherwise they pass through real integer and floating point types here.
4725  if (V.get()->getType()->isArithmeticType())
4726  return V.get()->getType();
4727 
4728  // Test for placeholders.
4729  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4730  if (PR.isInvalid()) return QualType();
4731  if (PR.get() != V.get()) {
4732  V = PR;
4733  return CheckRealImagOperand(S, V, Loc, IsReal);
4734  }
4735 
4736  // Reject anything else.
4737  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4738  << (IsReal ? "__real" : "__imag");
4739  return QualType();
4740 }
4741 
4742 
4743 
4744 ExprResult
4746  tok::TokenKind Kind, Expr *Input) {
4747  UnaryOperatorKind Opc;
4748  switch (Kind) {
4749  default: llvm_unreachable("Unknown unary op!");
4750  case tok::plusplus: Opc = UO_PostInc; break;
4751  case tok::minusminus: Opc = UO_PostDec; break;
4752  }
4753 
4754  // Since this might is a postfix expression, get rid of ParenListExprs.
4756  if (Result.isInvalid()) return ExprError();
4757  Input = Result.get();
4758 
4759  return BuildUnaryOp(S, OpLoc, Opc, Input);
4760 }
4761 
4762 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4763 ///
4764 /// \return true on error
4766  SourceLocation opLoc,
4767  Expr *op) {
4768  assert(op->getType()->isObjCObjectPointerType());
4770  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4771  return false;
4772 
4773  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4774  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4775  << op->getSourceRange();
4776  return true;
4777 }
4778 
4780  auto *BaseNoParens = Base->IgnoreParens();
4781  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4782  return MSProp->getPropertyDecl()->getType()->isArrayType();
4783  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4784 }
4785 
4786 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4787 // Typically this is DependentTy, but can sometimes be more precise.
4788 //
4789 // There are cases when we could determine a non-dependent type:
4790 // - LHS and RHS may have non-dependent types despite being type-dependent
4791 // (e.g. unbounded array static members of the current instantiation)
4792 // - one may be a dependent-sized array with known element type
4793 // - one may be a dependent-typed valid index (enum in current instantiation)
4794 //
4795 // We *always* return a dependent type, in such cases it is DependentTy.
4796 // This avoids creating type-dependent expressions with non-dependent types.
4797 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4799  const ASTContext &Ctx) {
4800  assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4801  QualType LTy = LHS->getType(), RTy = RHS->getType();
4802  QualType Result = Ctx.DependentTy;
4803  if (RTy->isIntegralOrUnscopedEnumerationType()) {
4804  if (const PointerType *PT = LTy->getAs<PointerType>())
4805  Result = PT->getPointeeType();
4806  else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4807  Result = AT->getElementType();
4808  } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4809  if (const PointerType *PT = RTy->getAs<PointerType>())
4810  Result = PT->getPointeeType();
4811  else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4812  Result = AT->getElementType();
4813  }
4814  // Ensure we return a dependent type.
4815  return Result->isDependentType() ? Result : Ctx.DependentTy;
4816 }
4817 
4818 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4819 
4821  SourceLocation lbLoc,
4822  MultiExprArg ArgExprs,
4823  SourceLocation rbLoc) {
4824 
4825  if (base && !base->getType().isNull() &&
4826  base->hasPlaceholderType(BuiltinType::OMPArraySection))
4827  return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4828  SourceLocation(), /*Length*/ nullptr,
4829  /*Stride=*/nullptr, rbLoc);
4830 
4831  // Since this might be a postfix expression, get rid of ParenListExprs.
4832  if (isa<ParenListExpr>(base)) {
4834  if (result.isInvalid())
4835  return ExprError();
4836  base = result.get();
4837  }
4838 
4839  // Check if base and idx form a MatrixSubscriptExpr.
4840  //
4841  // Helper to check for comma expressions, which are not allowed as indices for
4842  // matrix subscript expressions.
4843  auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4844  if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4845  Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4846  << SourceRange(base->getBeginLoc(), rbLoc);
4847  return true;
4848  }
4849  return false;
4850  };
4851  // The matrix subscript operator ([][])is considered a single operator.
4852  // Separating the index expressions by parenthesis is not allowed.
4853  if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4854  !isa<MatrixSubscriptExpr>(base)) {
4855  Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4856  << SourceRange(base->getBeginLoc(), rbLoc);
4857  return ExprError();
4858  }
4859  // If the base is a MatrixSubscriptExpr, try to create a new
4860  // MatrixSubscriptExpr.
4861  auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4862  if (matSubscriptE) {
4863  assert(ArgExprs.size() == 1);
4864  if (CheckAndReportCommaError(ArgExprs.front()))
4865  return ExprError();
4866 
4867  assert(matSubscriptE->isIncomplete() &&
4868  "base has to be an incomplete matrix subscript");
4869  return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4870  matSubscriptE->getRowIdx(),
4871  ArgExprs.front(), rbLoc);
4872  }
4873 
4874  // Handle any non-overload placeholder types in the base and index
4875  // expressions. We can't handle overloads here because the other
4876  // operand might be an overloadable type, in which case the overload
4877  // resolution for the operator overload should get the first crack
4878  // at the overload.
4879  bool IsMSPropertySubscript = false;
4880  if (base->getType()->isNonOverloadPlaceholderType()) {
4881  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4882  if (!IsMSPropertySubscript) {
4883  ExprResult result = CheckPlaceholderExpr(base);
4884  if (result.isInvalid())
4885  return ExprError();
4886  base = result.get();
4887  }
4888  }
4889 
4890  // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4891  if (base->getType()->isMatrixType()) {
4892  assert(ArgExprs.size() == 1);
4893  if (CheckAndReportCommaError(ArgExprs.front()))
4894  return ExprError();
4895 
4896  return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4897  rbLoc);
4898  }
4899 
4900  if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4901  Expr *idx = ArgExprs[0];
4902  if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4903  (isa<CXXOperatorCallExpr>(idx) &&
4904  cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4905  Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4906  << SourceRange(base->getBeginLoc(), rbLoc);
4907  }
4908  }
4909 
4910  if (ArgExprs.size() == 1 &&
4911  ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4912  ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4913  if (result.isInvalid())
4914  return ExprError();
4915  ArgExprs[0] = result.get();
4916  } else {
4917  if (checkArgsForPlaceholders(*this, ArgExprs))
4918  return ExprError();
4919  }
4920 
4921  // Build an unanalyzed expression if either operand is type-dependent.
4922  if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4923  (base->isTypeDependent() ||
4925  return new (Context) ArraySubscriptExpr(
4926  base, ArgExprs.front(),
4927  getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4928  VK_LValue, OK_Ordinary, rbLoc);
4929  }
4930 
4931  // MSDN, property (C++)
4932  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4933  // This attribute can also be used in the declaration of an empty array in a
4934  // class or structure definition. For example:
4935  // __declspec(property(get=GetX, put=PutX)) int x[];
4936  // The above statement indicates that x[] can be used with one or more array
4937  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4938  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4939  if (IsMSPropertySubscript) {
4940  assert(ArgExprs.size() == 1);
4941  // Build MS property subscript expression if base is MS property reference
4942  // or MS property subscript.
4943  return new (Context)
4944  MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4945  VK_LValue, OK_Ordinary, rbLoc);
4946  }
4947 
4948  // Use C++ overloaded-operator rules if either operand has record
4949  // type. The spec says to do this if either type is *overloadable*,
4950  // but enum types can't declare subscript operators or conversion
4951  // operators, so there's nothing interesting for overload resolution
4952  // to do if there aren't any record types involved.
4953  //
4954  // ObjC pointers have their own subscripting logic that is not tied
4955  // to overload resolution and so should not take this path.
4956  if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4957  ((base->getType()->isRecordType() ||
4958  (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4959  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4960  }
4961 
4962  ExprResult Res =
4963  CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4964 
4965  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4966  CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4967 
4968  return Res;
4969 }
4970 
4975  InitializationSequence InitSeq(*this, Entity, Kind, E);
4976  return InitSeq.Perform(*this, Entity, Kind, E);
4977 }
4978 
4980  Expr *ColumnIdx,
4981  SourceLocation RBLoc) {
4983  if (BaseR.isInvalid())
4984  return BaseR;
4985  Base = BaseR.get();
4986 
4987  ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4988  if (RowR.isInvalid())
4989  return RowR;
4990  RowIdx = RowR.get();
4991 
4992  if (!ColumnIdx)
4993  return new (Context) MatrixSubscriptExpr(
4994  Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4995 
4996  // Build an unanalyzed expression if any of the operands is type-dependent.
4997  if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4998  ColumnIdx->isTypeDependent())
4999  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5000  Context.DependentTy, RBLoc);
5001 
5002  ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5003  if (ColumnR.isInvalid())
5004  return ColumnR;
5005  ColumnIdx = ColumnR.get();
5006 
5007  // Check that IndexExpr is an integer expression. If it is a constant
5008  // expression, check that it is less than Dim (= the number of elements in the
5009  // corresponding dimension).
5010  auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5011  bool IsColumnIdx) -> Expr * {
5012  if (!IndexExpr->getType()->isIntegerType() &&
5013  !IndexExpr->isTypeDependent()) {
5014  Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5015  << IsColumnIdx;
5016  return nullptr;
5017  }
5018 
5019  if (std::optional<llvm::APSInt> Idx =
5020  IndexExpr->getIntegerConstantExpr(Context)) {
5021  if ((*Idx < 0 || *Idx >= Dim)) {
5022  Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5023  << IsColumnIdx << Dim;
5024  return nullptr;
5025  }
5026  }
5027 
5028  ExprResult ConvExpr =
5030  assert(!ConvExpr.isInvalid() &&
5031  "should be able to convert any integer type to size type");
5032  return ConvExpr.get();
5033  };
5034 
5035  auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5036  RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5037  ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5038  if (!RowIdx || !ColumnIdx)
5039  return ExprError();
5040 
5041  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5042  MTy->getElementType(), RBLoc);
5043 }
5044 
5045 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5046  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5047  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5048 
5049  // For expressions like `&(*s).b`, the base is recorded and what should be
5050  // checked.
5051  const MemberExpr *Member = nullptr;
5052  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5053  StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5054 
5055  LastRecord.PossibleDerefs.erase(StrippedExpr);
5056 }
5057 
5058 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5059  if (isUnevaluatedContext())
5060  return;
5061 
5062  QualType ResultTy = E->getType();
5063  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5064 
5065  // Bail if the element is an array since it is not memory access.
5066  if (isa<ArrayType>(ResultTy))
5067  return;
5068 
5069  if (ResultTy->hasAttr(attr::NoDeref)) {
5070  LastRecord.PossibleDerefs.insert(E);
5071  return;
5072  }
5073 
5074  // Check if the base type is a pointer to a member access of a struct
5075  // marked with noderef.
5076  const Expr *Base = E->getBase();
5077  QualType BaseTy = Base->getType();
5078  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5079  // Not a pointer access
5080  return;
5081 
5082  const MemberExpr *Member = nullptr;
5083  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5084  Member->isArrow())
5085  Base = Member->getBase();
5086 
5087  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5088  if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5089  LastRecord.PossibleDerefs.insert(E);
5090  }
5091 }
5092 
5094  Expr *LowerBound,
5095  SourceLocation ColonLocFirst,
5096  SourceLocation ColonLocSecond,
5097  Expr *Length, Expr *Stride,
5098  SourceLocation RBLoc) {
5099  if (Base->hasPlaceholderType() &&
5100  !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5102  if (Result.isInvalid())
5103  return ExprError();
5104  Base = Result.get();
5105  }
5106  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5107  ExprResult Result = CheckPlaceholderExpr(LowerBound);
5108  if (Result.isInvalid())
5109  return ExprError();
5110  Result = DefaultLvalueConversion(Result.get());
5111  if (Result.isInvalid())
5112  return ExprError();
5113  LowerBound = Result.get();
5114  }
5115  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5116  ExprResult Result = CheckPlaceholderExpr(Length);
5117  if (Result.isInvalid())
5118  return ExprError();
5119  Result = DefaultLvalueConversion(Result.get());
5120  if (Result.isInvalid())
5121  return ExprError();
5122  Length = Result.get();
5123  }
5124  if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5125  ExprResult Result = CheckPlaceholderExpr(Stride);
5126  if (Result.isInvalid())
5127  return ExprError();
5128  Result = DefaultLvalueConversion(Result.get());
5129  if (Result.isInvalid())
5130  return ExprError();
5131  Stride = Result.get();
5132  }
5133 
5134  // Build an unanalyzed expression if either operand is type-dependent.
5135  if (Base->isTypeDependent() ||
5136  (LowerBound &&
5137  (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5138  (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5139  (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5140  return new (Context) OMPArraySectionExpr(
5141  Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5142  OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5143  }
5144 
5145  // Perform default conversions.
5147  QualType ResultTy;
5148  if (OriginalTy->isAnyPointerType()) {
5149  ResultTy = OriginalTy->getPointeeType();
5150  } else if (OriginalTy->isArrayType()) {
5151  ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5152  } else {
5153  return ExprError(
5154  Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5155  << Base->getSourceRange());
5156  }
5157  // C99 6.5.2.1p1
5158  if (LowerBound) {
5159  auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5160  LowerBound);
5161  if (Res.isInvalid())
5162  return ExprError(Diag(LowerBound->getExprLoc(),
5163  diag::err_omp_typecheck_section_not_integer)
5164  << 0 << LowerBound->getSourceRange());
5165  LowerBound = Res.get();
5166 
5167  if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5168  LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5169  Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5170  << 0 << LowerBound->getSourceRange();
5171  }
5172  if (Length) {
5173  auto Res =
5175  if (Res.isInvalid())
5176  return ExprError(Diag(Length->getExprLoc(),
5177  diag::err_omp_typecheck_section_not_integer)
5178  << 1 << Length->getSourceRange());
5179  Length = Res.get();
5180 
5181  if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5182  Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5183  Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5184  << 1 << Length->getSourceRange();
5185  }
5186  if (Stride) {
5187  ExprResult Res =
5189  if (Res.isInvalid())
5190  return ExprError(Diag(Stride->getExprLoc(),
5191  diag::err_omp_typecheck_section_not_integer)
5192  << 1 << Stride->getSourceRange());
5193  Stride = Res.get();
5194 
5195  if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5196  Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5197  Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5198  << 1 << Stride->getSourceRange();
5199  }
5200 
5201  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5202  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5203  // type. Note that functions are not objects, and that (in C99 parlance)
5204  // incomplete types are not object types.
5205  if (ResultTy->isFunctionType()) {
5206  Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5207  << ResultTy << Base->getSourceRange();
5208  return ExprError();
5209  }
5210 
5211  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5212  diag::err_omp_section_incomplete_type, Base))
5213  return ExprError();
5214 
5215  if (LowerBound && !OriginalTy->isAnyPointerType()) {
5216  Expr::EvalResult Result;
5217  if (LowerBound->EvaluateAsInt(Result, Context)) {
5218  // OpenMP 5.0, [2.1.5 Array Sections]
5219  // The array section must be a subset of the original array.
5220  llvm::APSInt LowerBoundValue = Result.Val.getInt();
5221  if (LowerBoundValue.isNegative()) {
5222  Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5223  << LowerBound->getSourceRange();
5224  return ExprError();
5225  }
5226  }
5227  }
5228 
5229  if (Length) {
5230  Expr::EvalResult Result;
5231  if (Length->EvaluateAsInt(Result, Context)) {
5232  // OpenMP 5.0, [2.1.5 Array Sections]
5233  // The length must evaluate to non-negative integers.
5234  llvm::APSInt LengthValue = Result.Val.getInt();
5235  if (LengthValue.isNegative()) {
5236  Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5237  << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5238  << Length->getSourceRange();
5239  return ExprError();
5240  }
5241  }
5242  } else if (ColonLocFirst.isValid() &&
5243  (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5244  !OriginalTy->isVariableArrayType()))) {
5245  // OpenMP 5.0, [2.1.5 Array Sections]
5246  // When the size of the array dimension is not known, the length must be
5247  // specified explicitly.
5248  Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5249  << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5250  return ExprError();
5251  }
5252 
5253  if (Stride) {
5254  Expr::EvalResult Result;
5255  if (Stride->EvaluateAsInt(Result, Context)) {
5256  // OpenMP 5.0, [2.1.5 Array Sections]
5257  // The stride must evaluate to a positive integer.
5258  llvm::APSInt StrideValue = Result.Val.getInt();
5259  if (!StrideValue.isStrictlyPositive()) {
5260  Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5261  << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5262  << Stride->getSourceRange();
5263  return ExprError();
5264  }
5265  }
5266  }
5267 
5268  if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5270  if (Result.isInvalid())
5271  return ExprError();
5272  Base = Result.get();
5273  }
5274  return new (Context) OMPArraySectionExpr(
5275  Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5276  OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5277 }
5278 
5280  SourceLocation RParenLoc,
5281  ArrayRef<Expr *> Dims,
5282  ArrayRef<SourceRange> Brackets) {
5283  if (Base->hasPlaceholderType()) {
5285  if (Result.isInvalid())
5286  return ExprError();
5287  Result = DefaultLvalueConversion(Result.get());
5288  if (Result.isInvalid())
5289  return ExprError();
5290  Base = Result.get();
5291  }
5292  QualType BaseTy = Base->getType();
5293  // Delay analysis of the types/expressions if instantiation/specialization is
5294  // required.
5295  if (!BaseTy->isPointerType() && Base->isTypeDependent())
5297  LParenLoc, RParenLoc, Dims, Brackets);
5298  if (!BaseTy->isPointerType() ||
5299  (!Base->isTypeDependent() &&
5300  BaseTy->getPointeeType()->isIncompleteType()))
5301  return ExprError(Diag(Base->getExprLoc(),
5302  diag::err_omp_non_pointer_type_array_shaping_base)
5303  << Base->getSourceRange());
5304 
5305  SmallVector<Expr *, 4> NewDims;
5306  bool ErrorFound = false;
5307  for (Expr *Dim : Dims) {
5308  if (Dim->hasPlaceholderType()) {
5309  ExprResult Result = CheckPlaceholderExpr(Dim);
5310  if (Result.isInvalid()) {
5311  ErrorFound = true;
5312  continue;
5313  }
5314  Result = DefaultLvalueConversion(Result.get());
5315  if (Result.isInvalid()) {
5316  ErrorFound = true;
5317  continue;
5318  }
5319  Dim = Result.get();
5320  }
5321  if (!Dim->isTypeDependent()) {
5322  ExprResult Result =
5323  PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5324  if (Result.isInvalid()) {
5325  ErrorFound = true;
5326  Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5327  << Dim->getSourceRange();
5328  continue;
5329  }
5330  Dim = Result.get();
5331  Expr::EvalResult EvResult;
5332  if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5333  // OpenMP 5.0, [2.1.4 Array Shaping]
5334  // Each si is an integral type expression that must evaluate to a
5335  // positive integer.
5336  llvm::APSInt Value = EvResult.Val.getInt();
5337  if (!Value.isStrictlyPositive()) {
5338  Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5339  << toString(Value, /*Radix=*/10, /*Signed=*/true)
5340  << Dim->getSourceRange();
5341  ErrorFound = true;
5342  continue;
5343&#