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