clang  10.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 "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/FixedPoint.h"
32 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 using namespace clang;
50 using namespace sema;
51 
52 /// Determine whether the use of this declaration is valid, without
53 /// emitting diagnostics.
54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
55  // See if this is an auto-typed variable whose initializer we are parsing.
56  if (ParsingInitForAutoVars.count(D))
57  return false;
58 
59  // See if this is a deleted function.
60  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
61  if (FD->isDeleted())
62  return false;
63 
64  // If the function has a deduced return type, and we can't deduce it,
65  // then we can't use it either.
66  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
67  DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
68  return false;
69 
70  // See if this is an aligned allocation/deallocation function that is
71  // unavailable.
72  if (TreatUnavailableAsInvalid &&
73  isUnavailableAlignedAllocationFunction(*FD))
74  return false;
75  }
76 
77  // See if this function is unavailable.
78  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
79  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
80  return false;
81 
82  return true;
83 }
84 
86  // Warn if this is used but marked unused.
87  if (const auto *A = D->getAttr<UnusedAttr>()) {
88  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
89  // should diagnose them.
90  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
91  A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
92  const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
93  if (DC && !DC->hasAttr<UnusedAttr>())
94  S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
95  }
96  }
97 }
98 
99 /// Emit a note explaining that this function is deleted.
101  assert(Decl && Decl->isDeleted());
102 
103  if (Decl->isDefaulted()) {
104  // If the method was explicitly defaulted, point at that declaration.
105  if (!Decl->isImplicit())
106  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
107 
108  // Try to diagnose why this special member function was implicitly
109  // deleted. This might fail, if that reason no longer applies.
110  DiagnoseDeletedDefaultedFunction(Decl);
111  return;
112  }
113 
114  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
115  if (Ctor && Ctor->isInheritingConstructor())
116  return NoteDeletedInheritingConstructor(Ctor);
117 
118  Diag(Decl->getLocation(), diag::note_availability_specified_here)
119  << Decl << 1;
120 }
121 
122 /// Determine whether a FunctionDecl was ever declared with an
123 /// explicit storage class.
125  for (auto I : D->redecls()) {
126  if (I->getStorageClass() != SC_None)
127  return true;
128  }
129  return false;
130 }
131 
132 /// Check whether we're in an extern inline function and referring to a
133 /// variable or function with internal linkage (C11 6.7.4p3).
134 ///
135 /// This is only a warning because we used to silently accept this code, but
136 /// in many cases it will not behave correctly. This is not enabled in C++ mode
137 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
138 /// and so while there may still be user mistakes, most of the time we can't
139 /// prove that there are errors.
141  const NamedDecl *D,
142  SourceLocation Loc) {
143  // This is disabled under C++; there are too many ways for this to fire in
144  // contexts where the warning is a false positive, or where it is technically
145  // correct but benign.
146  if (S.getLangOpts().CPlusPlus)
147  return;
148 
149  // Check if this is an inlined function or method.
150  FunctionDecl *Current = S.getCurFunctionDecl();
151  if (!Current)
152  return;
153  if (!Current->isInlined())
154  return;
155  if (!Current->isExternallyVisible())
156  return;
157 
158  // Check if the decl has internal linkage.
159  if (D->getFormalLinkage() != InternalLinkage)
160  return;
161 
162  // Downgrade from ExtWarn to Extension if
163  // (1) the supposedly external inline function is in the main file,
164  // and probably won't be included anywhere else.
165  // (2) the thing we're referencing is a pure function.
166  // (3) the thing we're referencing is another inline function.
167  // This last can give us false negatives, but it's better than warning on
168  // wrappers for simple C library functions.
169  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
170  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
171  if (!DowngradeWarning && UsedFn)
172  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
173 
174  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
175  : diag::ext_internal_in_extern_inline)
176  << /*IsVar=*/!UsedFn << D;
177 
179 
180  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
181  << D;
182 }
183 
185  const FunctionDecl *First = Cur->getFirstDecl();
186 
187  // Suggest "static" on the function, if possible.
188  if (!hasAnyExplicitStorageClass(First)) {
189  SourceLocation DeclBegin = First->getSourceRange().getBegin();
190  Diag(DeclBegin, diag::note_convert_inline_to_static)
191  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
192  }
193 }
194 
195 /// Determine whether the use of this declaration is valid, and
196 /// emit any corresponding diagnostics.
197 ///
198 /// This routine diagnoses various problems with referencing
199 /// declarations that can occur when using a declaration. For example,
200 /// it might warn if a deprecated or unavailable declaration is being
201 /// used, or produce an error (and return true) if a C++0x deleted
202 /// function is being used.
203 ///
204 /// \returns true if there was an error (this declaration cannot be
205 /// referenced), false otherwise.
206 ///
208  const ObjCInterfaceDecl *UnknownObjCClass,
209  bool ObjCPropertyAccess,
210  bool AvoidPartialAvailabilityChecks,
211  ObjCInterfaceDecl *ClassReceiver) {
212  SourceLocation Loc = Locs.front();
213  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
214  // If there were any diagnostics suppressed by template argument deduction,
215  // emit them now.
216  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
217  if (Pos != SuppressedDiagnostics.end()) {
218  for (const PartialDiagnosticAt &Suppressed : Pos->second)
219  Diag(Suppressed.first, Suppressed.second);
220 
221  // Clear out the list of suppressed diagnostics, so that we don't emit
222  // them again for this specialization. However, we don't obsolete this
223  // entry from the table, because we want to avoid ever emitting these
224  // diagnostics again.
225  Pos->second.clear();
226  }
227 
228  // C++ [basic.start.main]p3:
229  // The function 'main' shall not be used within a program.
230  if (cast<FunctionDecl>(D)->isMain())
231  Diag(Loc, diag::ext_main_used);
232 
233  diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
234  }
235 
236  // See if this is an auto-typed variable whose initializer we are parsing.
237  if (ParsingInitForAutoVars.count(D)) {
238  if (isa<BindingDecl>(D)) {
239  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
240  << D->getDeclName();
241  } else {
242  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
243  << D->getDeclName() << cast<VarDecl>(D)->getType();
244  }
245  return true;
246  }
247 
248  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
249  // See if this is a deleted function.
250  if (FD->isDeleted()) {
251  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
252  if (Ctor && Ctor->isInheritingConstructor())
253  Diag(Loc, diag::err_deleted_inherited_ctor_use)
254  << Ctor->getParent()
255  << Ctor->getInheritedConstructor().getConstructor()->getParent();
256  else
257  Diag(Loc, diag::err_deleted_function_use);
258  NoteDeletedFunction(FD);
259  return true;
260  }
261 
262  // [expr.prim.id]p4
263  // A program that refers explicitly or implicitly to a function with a
264  // trailing requires-clause whose constraint-expression is not satisfied,
265  // other than to declare it, is ill-formed. [...]
266  //
267  // See if this is a function with constraints that need to be satisfied.
268  // Check this before deducing the return type, as it might instantiate the
269  // definition.
270  if (FD->getTrailingRequiresClause()) {
271  ConstraintSatisfaction Satisfaction;
272  if (CheckFunctionConstraints(FD, Satisfaction, Loc))
273  // A diagnostic will have already been generated (non-constant
274  // constraint expression, for example)
275  return true;
276  if (!Satisfaction.IsSatisfied) {
277  Diag(Loc,
278  diag::err_reference_to_function_with_unsatisfied_constraints)
279  << D;
280  DiagnoseUnsatisfiedConstraint(Satisfaction);
281  return true;
282  }
283  }
284 
285  // If the function has a deduced return type, and we can't deduce it,
286  // then we can't use it either.
287  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
288  DeduceReturnType(FD, Loc))
289  return true;
290 
291  if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
292  return true;
293  }
294 
295  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
296  // Lambdas are only default-constructible or assignable in C++2a onwards.
297  if (MD->getParent()->isLambda() &&
298  ((isa<CXXConstructorDecl>(MD) &&
299  cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
300  MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
301  Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
302  << !isa<CXXConstructorDecl>(MD);
303  }
304  }
305 
306  auto getReferencedObjCProp = [](const NamedDecl *D) ->
307  const ObjCPropertyDecl * {
308  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
309  return MD->findPropertyDecl();
310  return nullptr;
311  };
312  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
313  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
314  return true;
315  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
316  return true;
317  }
318 
319  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
320  // Only the variables omp_in and omp_out are allowed in the combiner.
321  // Only the variables omp_priv and omp_orig are allowed in the
322  // initializer-clause.
323  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
324  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
325  isa<VarDecl>(D)) {
326  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
327  << getCurFunction()->HasOMPDeclareReductionCombiner;
328  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
329  return true;
330  }
331 
332  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
333  // List-items in map clauses on this construct may only refer to the declared
334  // variable var and entities that could be referenced by a procedure defined
335  // at the same location
336  auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
337  if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
338  isa<VarDecl>(D)) {
339  Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
340  << DMD->getVarName().getAsString();
341  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
342  return true;
343  }
344 
345  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
346  AvoidPartialAvailabilityChecks, ClassReceiver);
347 
348  DiagnoseUnusedOfDecl(*this, D, Loc);
349 
351 
352  if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
353  !isUnevaluatedContext()) {
354  // C++ [expr.prim.req.nested] p3
355  // A local parameter shall only appear as an unevaluated operand
356  // (Clause 8) within the constraint-expression.
357  Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
358  << D;
359  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
360  return true;
361  }
362 
363  return false;
364 }
365 
366 /// DiagnoseSentinelCalls - This routine checks whether a call or
367 /// message-send is to a declaration with the sentinel attribute, and
368 /// if so, it checks that the requirements of the sentinel are
369 /// satisfied.
371  ArrayRef<Expr *> Args) {
372  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
373  if (!attr)
374  return;
375 
376  // The number of formal parameters of the declaration.
377  unsigned numFormalParams;
378 
379  // The kind of declaration. This is also an index into a %select in
380  // the diagnostic.
381  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
382 
383  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
384  numFormalParams = MD->param_size();
385  calleeType = CT_Method;
386  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
387  numFormalParams = FD->param_size();
388  calleeType = CT_Function;
389  } else if (isa<VarDecl>(D)) {
390  QualType type = cast<ValueDecl>(D)->getType();
391  const FunctionType *fn = nullptr;
392  if (const PointerType *ptr = type->getAs<PointerType>()) {
393  fn = ptr->getPointeeType()->getAs<FunctionType>();
394  if (!fn) return;
395  calleeType = CT_Function;
396  } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
397  fn = ptr->getPointeeType()->castAs<FunctionType>();
398  calleeType = CT_Block;
399  } else {
400  return;
401  }
402 
403  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
404  numFormalParams = proto->getNumParams();
405  } else {
406  numFormalParams = 0;
407  }
408  } else {
409  return;
410  }
411 
412  // "nullPos" is the number of formal parameters at the end which
413  // effectively count as part of the variadic arguments. This is
414  // useful if you would prefer to not have *any* formal parameters,
415  // but the language forces you to have at least one.
416  unsigned nullPos = attr->getNullPos();
417  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
418  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
419 
420  // The number of arguments which should follow the sentinel.
421  unsigned numArgsAfterSentinel = attr->getSentinel();
422 
423  // If there aren't enough arguments for all the formal parameters,
424  // the sentinel, and the args after the sentinel, complain.
425  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
426  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
427  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
428  return;
429  }
430 
431  // Otherwise, find the sentinel expression.
432  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
433  if (!sentinelExpr) return;
434  if (sentinelExpr->isValueDependent()) return;
435  if (Context.isSentinelNullExpr(sentinelExpr)) return;
436 
437  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
438  // or 'NULL' if those are actually defined in the context. Only use
439  // 'nil' for ObjC methods, where it's much more likely that the
440  // variadic arguments form a list of object pointers.
441  SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
442  std::string NullValue;
443  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
444  NullValue = "nil";
445  else if (getLangOpts().CPlusPlus11)
446  NullValue = "nullptr";
447  else if (PP.isMacroDefined("NULL"))
448  NullValue = "NULL";
449  else
450  NullValue = "(void*) 0";
451 
452  if (MissingNilLoc.isInvalid())
453  Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
454  else
455  Diag(MissingNilLoc, diag::warn_missing_sentinel)
456  << int(calleeType)
457  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
458  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
459 }
460 
462  return E ? E->getSourceRange() : SourceRange();
463 }
464 
465 //===----------------------------------------------------------------------===//
466 // Standard Promotions and Conversions
467 //===----------------------------------------------------------------------===//
468 
469 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
471  // Handle any placeholder expressions which made it here.
472  if (E->getType()->isPlaceholderType()) {
473  ExprResult result = CheckPlaceholderExpr(E);
474  if (result.isInvalid()) return ExprError();
475  E = result.get();
476  }
477 
478  QualType Ty = E->getType();
479  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
480 
481  if (Ty->isFunctionType()) {
482  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
483  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
484  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
485  return ExprError();
486 
487  E = ImpCastExprToType(E, Context.getPointerType(Ty),
488  CK_FunctionToPointerDecay).get();
489  } else if (Ty->isArrayType()) {
490  // In C90 mode, arrays only promote to pointers if the array expression is
491  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
492  // type 'array of type' is converted to an expression that has type 'pointer
493  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
494  // that has type 'array of type' ...". The relevant change is "an lvalue"
495  // (C90) to "an expression" (C99).
496  //
497  // C++ 4.2p1:
498  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
499  // T" can be converted to an rvalue of type "pointer to T".
500  //
501  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
502  E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
503  CK_ArrayToPointerDecay).get();
504  }
505  return E;
506 }
507 
509  // Check to see if we are dereferencing a null pointer. If so,
510  // and if not volatile-qualified, this is undefined behavior that the
511  // optimizer will delete, so warn about it. People sometimes try to use this
512  // to get a deterministic trap and are surprised by clang's behavior. This
513  // only handles the pattern "*null", which is a very syntactic check.
514  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
515  if (UO && UO->getOpcode() == UO_Deref &&
516  UO->getSubExpr()->getType()->isPointerType()) {
517  const LangAS AS =
519  if ((!isTargetAddressSpace(AS) ||
520  (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
521  UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
523  !UO->getType().isVolatileQualified()) {
524  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
525  S.PDiag(diag::warn_indirection_through_null)
526  << UO->getSubExpr()->getSourceRange());
527  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
528  S.PDiag(diag::note_indirection_through_null));
529  }
530  }
531 }
532 
533 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
534  SourceLocation AssignLoc,
535  const Expr* RHS) {
536  const ObjCIvarDecl *IV = OIRE->getDecl();
537  if (!IV)
538  return;
539 
540  DeclarationName MemberName = IV->getDeclName();
541  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
542  if (!Member || !Member->isStr("isa"))
543  return;
544 
545  const Expr *Base = OIRE->getBase();
546  QualType BaseType = Base->getType();
547  if (OIRE->isArrow())
548  BaseType = BaseType->getPointeeType();
549  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
550  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
551  ObjCInterfaceDecl *ClassDeclared = nullptr;
552  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
553  if (!ClassDeclared->getSuperClass()
554  && (*ClassDeclared->ivar_begin()) == IV) {
555  if (RHS) {
556  NamedDecl *ObjectSetClass =
558  &S.Context.Idents.get("object_setClass"),
560  if (ObjectSetClass) {
561  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
562  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
564  "object_setClass(")
566  SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
567  << FixItHint::CreateInsertion(RHSLocEnd, ")");
568  }
569  else
570  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
571  } else {
572  NamedDecl *ObjectGetClass =
574  &S.Context.Idents.get("object_getClass"),
576  if (ObjectGetClass)
577  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
579  "object_getClass(")
581  SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
582  else
583  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
584  }
585  S.Diag(IV->getLocation(), diag::note_ivar_decl);
586  }
587  }
588 }
589 
591  // Handle any placeholder expressions which made it here.
592  if (E->getType()->isPlaceholderType()) {
593  ExprResult result = CheckPlaceholderExpr(E);
594  if (result.isInvalid()) return ExprError();
595  E = result.get();
596  }
597 
598  // C++ [conv.lval]p1:
599  // A glvalue of a non-function, non-array type T can be
600  // converted to a prvalue.
601  if (!E->isGLValue()) return E;
602 
603  QualType T = E->getType();
604  assert(!T.isNull() && "r-value conversion on typeless expression?");
605 
606  // We don't want to throw lvalue-to-rvalue casts on top of
607  // expressions of certain types in C++.
608  if (getLangOpts().CPlusPlus &&
609  (E->getType() == Context.OverloadTy ||
610  T->isDependentType() ||
611  T->isRecordType()))
612  return E;
613 
614  // The C standard is actually really unclear on this point, and
615  // DR106 tells us what the result should be but not why. It's
616  // generally best to say that void types just doesn't undergo
617  // lvalue-to-rvalue at all. Note that expressions of unqualified
618  // 'void' type are never l-values, but qualified void can be.
619  if (T->isVoidType())
620  return E;
621 
622  // OpenCL usually rejects direct accesses to values of 'half' type.
623  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
624  T->isHalfType()) {
625  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
626  << 0 << T;
627  return ExprError();
628  }
629 
631  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
632  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
633  &Context.Idents.get("object_getClass"),
634  SourceLocation(), LookupOrdinaryName);
635  if (ObjectGetClass)
636  Diag(E->getExprLoc(), diag::warn_objc_isa_use)
637  << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
639  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
640  else
641  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
642  }
643  else if (const ObjCIvarRefExpr *OIRE =
644  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
645  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
646 
647  // C++ [conv.lval]p1:
648  // [...] If T is a non-class type, the type of the prvalue is the
649  // cv-unqualified version of T. Otherwise, the type of the
650  // rvalue is T.
651  //
652  // C99 6.3.2.1p2:
653  // If the lvalue has qualified type, the value has the unqualified
654  // version of the type of the lvalue; otherwise, the value has the
655  // type of the lvalue.
656  if (T.hasQualifiers())
657  T = T.getUnqualifiedType();
658 
659  // Under the MS ABI, lock down the inheritance model now.
660  if (T->isMemberPointerType() &&
661  Context.getTargetInfo().getCXXABI().isMicrosoft())
662  (void)isCompleteType(E->getExprLoc(), T);
663 
664  ExprResult Res = CheckLValueToRValueConversionOperand(E);
665  if (Res.isInvalid())
666  return Res;
667  E = Res.get();
668 
669  // Loading a __weak object implicitly retains the value, so we need a cleanup to
670  // balance that.
672  Cleanup.setExprNeedsCleanups(true);
673 
674  // C++ [conv.lval]p3:
675  // If T is cv std::nullptr_t, the result is a null pointer constant.
676  CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
677  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
678 
679  // C11 6.3.2.1p2:
680  // ... if the lvalue has atomic type, the value has the non-atomic version
681  // of the type of the lvalue ...
682  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
683  T = Atomic->getValueType().getUnqualifiedType();
684  Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
685  nullptr, VK_RValue);
686  }
687 
688  return Res;
689 }
690 
692  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
693  if (Res.isInvalid())
694  return ExprError();
695  Res = DefaultLvalueConversion(Res.get());
696  if (Res.isInvalid())
697  return ExprError();
698  return Res;
699 }
700 
701 /// CallExprUnaryConversions - a special case of an unary conversion
702 /// performed on a function designator of a call expression.
704  QualType Ty = E->getType();
705  ExprResult Res = E;
706  // Only do implicit cast for a function type, but not for a pointer
707  // to function type.
708  if (Ty->isFunctionType()) {
709  Res = ImpCastExprToType(E, Context.getPointerType(Ty),
710  CK_FunctionToPointerDecay).get();
711  if (Res.isInvalid())
712  return ExprError();
713  }
714  Res = DefaultLvalueConversion(Res.get());
715  if (Res.isInvalid())
716  return ExprError();
717  return Res.get();
718 }
719 
720 /// UsualUnaryConversions - Performs various conversions that are common to most
721 /// operators (C99 6.3). The conversions of array and function types are
722 /// sometimes suppressed. For example, the array->pointer conversion doesn't
723 /// apply if the array is an argument to the sizeof or address (&) operators.
724 /// In these instances, this routine should *not* be called.
726  // First, convert to an r-value.
727  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
728  if (Res.isInvalid())
729  return ExprError();
730  E = Res.get();
731 
732  QualType Ty = E->getType();
733  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
734 
735  // Half FP have to be promoted to float unless it is natively supported
736  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
737  return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
738 
739  // Try to perform integral promotions if the object has a theoretically
740  // promotable type.
742  // C99 6.3.1.1p2:
743  //
744  // The following may be used in an expression wherever an int or
745  // unsigned int may be used:
746  // - an object or expression with an integer type whose integer
747  // conversion rank is less than or equal to the rank of int
748  // and unsigned int.
749  // - A bit-field of type _Bool, int, signed int, or unsigned int.
750  //
751  // If an int can represent all values of the original type, the
752  // value is converted to an int; otherwise, it is converted to an
753  // unsigned int. These are called the integer promotions. All
754  // other types are unchanged by the integer promotions.
755 
756  QualType PTy = Context.isPromotableBitField(E);
757  if (!PTy.isNull()) {
758  E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
759  return E;
760  }
761  if (Ty->isPromotableIntegerType()) {
762  QualType PT = Context.getPromotedIntegerType(Ty);
763  E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
764  return E;
765  }
766  }
767  return E;
768 }
769 
770 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
771 /// do not have a prototype. Arguments that have type float or __fp16
772 /// are promoted to double. All other argument types are converted by
773 /// UsualUnaryConversions().
775  QualType Ty = E->getType();
776  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
777 
778  ExprResult Res = UsualUnaryConversions(E);
779  if (Res.isInvalid())
780  return ExprError();
781  E = Res.get();
782 
783  // If this is a 'float' or '__fp16' (CVR qualified or typedef)
784  // promote to double.
785  // Note that default argument promotion applies only to float (and
786  // half/fp16); it does not apply to _Float16.
787  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
788  if (BTy && (BTy->getKind() == BuiltinType::Half ||
789  BTy->getKind() == BuiltinType::Float)) {
790  if (getLangOpts().OpenCL &&
791  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
792  if (BTy->getKind() == BuiltinType::Half) {
793  E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
794  }
795  } else {
796  E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
797  }
798  }
799 
800  // C++ performs lvalue-to-rvalue conversion as a default argument
801  // promotion, even on class types, but note:
802  // C++11 [conv.lval]p2:
803  // When an lvalue-to-rvalue conversion occurs in an unevaluated
804  // operand or a subexpression thereof the value contained in the
805  // referenced object is not accessed. Otherwise, if the glvalue
806  // has a class type, the conversion copy-initializes a temporary
807  // of type T from the glvalue and the result of the conversion
808  // is a prvalue for the temporary.
809  // FIXME: add some way to gate this entire thing for correctness in
810  // potentially potentially evaluated contexts.
811  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
812  ExprResult Temp = PerformCopyInitialization(
814  E->getExprLoc(), E);
815  if (Temp.isInvalid())
816  return ExprError();
817  E = Temp.get();
818  }
819 
820  return E;
821 }
822 
823 /// Determine the degree of POD-ness for an expression.
824 /// Incomplete types are considered POD, since this check can be performed
825 /// when we're in an unevaluated context.
827  if (Ty->isIncompleteType()) {
828  // C++11 [expr.call]p7:
829  // After these conversions, if the argument does not have arithmetic,
830  // enumeration, pointer, pointer to member, or class type, the program
831  // is ill-formed.
832  //
833  // Since we've already performed array-to-pointer and function-to-pointer
834  // decay, the only such type in C++ is cv void. This also handles
835  // initializer lists as variadic arguments.
836  if (Ty->isVoidType())
837  return VAK_Invalid;
838 
839  if (Ty->isObjCObjectType())
840  return VAK_Invalid;
841  return VAK_Valid;
842  }
843 
845  return VAK_Invalid;
846 
847  if (Ty.isCXX98PODType(Context))
848  return VAK_Valid;
849 
850  // C++11 [expr.call]p7:
851  // Passing a potentially-evaluated argument of class type (Clause 9)
852  // having a non-trivial copy constructor, a non-trivial move constructor,
853  // or a non-trivial destructor, with no corresponding parameter,
854  // is conditionally-supported with implementation-defined semantics.
855  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
856  if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
857  if (!Record->hasNonTrivialCopyConstructor() &&
858  !Record->hasNonTrivialMoveConstructor() &&
859  !Record->hasNonTrivialDestructor())
860  return VAK_ValidInCXX11;
861 
862  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
863  return VAK_Valid;
864 
865  if (Ty->isObjCObjectType())
866  return VAK_Invalid;
867 
868  if (getLangOpts().MSVCCompat)
869  return VAK_MSVCUndefined;
870 
871  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
872  // permitted to reject them. We should consider doing so.
873  return VAK_Undefined;
874 }
875 
877  // Don't allow one to pass an Objective-C interface to a vararg.
878  const QualType &Ty = E->getType();
879  VarArgKind VAK = isValidVarArgType(Ty);
880 
881  // Complain about passing non-POD types through varargs.
882  switch (VAK) {
883  case VAK_ValidInCXX11:
884  DiagRuntimeBehavior(
885  E->getBeginLoc(), nullptr,
886  PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
887  LLVM_FALLTHROUGH;
888  case VAK_Valid:
889  if (Ty->isRecordType()) {
890  // This is unlikely to be what the user intended. If the class has a
891  // 'c_str' member function, the user probably meant to call that.
892  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
893  PDiag(diag::warn_pass_class_arg_to_vararg)
894  << Ty << CT << hasCStrMethod(E) << ".c_str()");
895  }
896  break;
897 
898  case VAK_Undefined:
899  case VAK_MSVCUndefined:
900  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
901  PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
902  << getLangOpts().CPlusPlus11 << Ty << CT);
903  break;
904 
905  case VAK_Invalid:
907  Diag(E->getBeginLoc(),
908  diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
909  << Ty << CT;
910  else if (Ty->isObjCObjectType())
911  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
912  PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
913  << Ty << CT);
914  else
915  Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
916  << isa<InitListExpr>(E) << Ty << CT;
917  break;
918  }
919 }
920 
921 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
922 /// will create a trap if the resulting type is not a POD type.
924  FunctionDecl *FDecl) {
925  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
926  // Strip the unbridged-cast placeholder expression off, if applicable.
927  if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
928  (CT == VariadicMethod ||
929  (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
930  E = stripARCUnbridgedCast(E);
931 
932  // Otherwise, do normal placeholder checking.
933  } else {
934  ExprResult ExprRes = CheckPlaceholderExpr(E);
935  if (ExprRes.isInvalid())
936  return ExprError();
937  E = ExprRes.get();
938  }
939  }
940 
941  ExprResult ExprRes = DefaultArgumentPromotion(E);
942  if (ExprRes.isInvalid())
943  return ExprError();
944  E = ExprRes.get();
945 
946  // Diagnostics regarding non-POD argument types are
947  // emitted along with format string checking in Sema::CheckFunctionCall().
948  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
949  // Turn this into a trap.
950  CXXScopeSpec SS;
951  SourceLocation TemplateKWLoc;
952  UnqualifiedId Name;
953  Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
954  E->getBeginLoc());
955  ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
956  /*HasTrailingLParen=*/true,
957  /*IsAddressOfOperand=*/false);
958  if (TrapFn.isInvalid())
959  return ExprError();
960 
961  ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
962  None, E->getEndLoc());
963  if (Call.isInvalid())
964  return ExprError();
965 
966  ExprResult Comma =
967  ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
968  if (Comma.isInvalid())
969  return ExprError();
970  return Comma.get();
971  }
972 
973  if (!getLangOpts().CPlusPlus &&
974  RequireCompleteType(E->getExprLoc(), E->getType(),
975  diag::err_call_incomplete_argument))
976  return ExprError();
977 
978  return E;
979 }
980 
981 /// Converts an integer to complex float type. Helper function of
982 /// UsualArithmeticConversions()
983 ///
984 /// \return false if the integer expression is an integer type and is
985 /// successfully converted to the complex type.
987  ExprResult &ComplexExpr,
988  QualType IntTy,
989  QualType ComplexTy,
990  bool SkipCast) {
991  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
992  if (SkipCast) return false;
993  if (IntTy->isIntegerType()) {
994  QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
995  IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
996  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
997  CK_FloatingRealToComplex);
998  } else {
999  assert(IntTy->isComplexIntegerType());
1000  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1001  CK_IntegralComplexToFloatingComplex);
1002  }
1003  return false;
1004 }
1005 
1006 /// Handle arithmetic conversion with complex types. Helper function of
1007 /// UsualArithmeticConversions()
1009  ExprResult &RHS, QualType LHSType,
1010  QualType RHSType,
1011  bool IsCompAssign) {
1012  // if we have an integer operand, the result is the complex type.
1013  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1014  /*skipCast*/false))
1015  return LHSType;
1016  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1017  /*skipCast*/IsCompAssign))
1018  return RHSType;
1019 
1020  // This handles complex/complex, complex/float, or float/complex.
1021  // When both operands are complex, the shorter operand is converted to the
1022  // type of the longer, and that is the type of the result. This corresponds
1023  // to what is done when combining two real floating-point operands.
1024  // The fun begins when size promotion occur across type domains.
1025  // From H&S 6.3.4: When one operand is complex and the other is a real
1026  // floating-point type, the less precise type is converted, within it's
1027  // real or complex domain, to the precision of the other type. For example,
1028  // when combining a "long double" with a "double _Complex", the
1029  // "double _Complex" is promoted to "long double _Complex".
1030 
1031  // Compute the rank of the two types, regardless of whether they are complex.
1032  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1033 
1034  auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1035  auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1036  QualType LHSElementType =
1037  LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1038  QualType RHSElementType =
1039  RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1040 
1041  QualType ResultType = S.Context.getComplexType(LHSElementType);
1042  if (Order < 0) {
1043  // Promote the precision of the LHS if not an assignment.
1044  ResultType = S.Context.getComplexType(RHSElementType);
1045  if (!IsCompAssign) {
1046  if (LHSComplexType)
1047  LHS =
1048  S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1049  else
1050  LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1051  }
1052  } else if (Order > 0) {
1053  // Promote the precision of the RHS.
1054  if (RHSComplexType)
1055  RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1056  else
1057  RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1058  }
1059  return ResultType;
1060 }
1061 
1062 /// Handle arithmetic conversion from integer to float. Helper function
1063 /// of UsualArithmeticConversions()
1065  ExprResult &IntExpr,
1066  QualType FloatTy, QualType IntTy,
1067  bool ConvertFloat, bool ConvertInt) {
1068  if (IntTy->isIntegerType()) {
1069  if (ConvertInt)
1070  // Convert intExpr to the lhs floating point type.
1071  IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1072  CK_IntegralToFloating);
1073  return FloatTy;
1074  }
1075 
1076  // Convert both sides to the appropriate complex float.
1077  assert(IntTy->isComplexIntegerType());
1078  QualType result = S.Context.getComplexType(FloatTy);
1079 
1080  // _Complex int -> _Complex float
1081  if (ConvertInt)
1082  IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1083  CK_IntegralComplexToFloatingComplex);
1084 
1085  // float -> _Complex float
1086  if (ConvertFloat)
1087  FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1088  CK_FloatingRealToComplex);
1089 
1090  return result;
1091 }
1092 
1093 /// Handle arithmethic conversion with floating point types. Helper
1094 /// function of UsualArithmeticConversions()
1096  ExprResult &RHS, QualType LHSType,
1097  QualType RHSType, bool IsCompAssign) {
1098  bool LHSFloat = LHSType->isRealFloatingType();
1099  bool RHSFloat = RHSType->isRealFloatingType();
1100 
1101  // If we have two real floating types, convert the smaller operand
1102  // to the bigger result.
1103  if (LHSFloat && RHSFloat) {
1104  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1105  if (order > 0) {
1106  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1107  return LHSType;
1108  }
1109 
1110  assert(order < 0 && "illegal float comparison");
1111  if (!IsCompAssign)
1112  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1113  return RHSType;
1114  }
1115 
1116  if (LHSFloat) {
1117  // Half FP has to be promoted to float unless it is natively supported
1118  if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1119  LHSType = S.Context.FloatTy;
1120 
1121  return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1122  /*ConvertFloat=*/!IsCompAssign,
1123  /*ConvertInt=*/ true);
1124  }
1125  assert(RHSFloat);
1126  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1127  /*convertInt=*/ true,
1128  /*convertFloat=*/!IsCompAssign);
1129 }
1130 
1131 /// Diagnose attempts to convert between __float128 and long double if
1132 /// there is no support for such conversion. Helper function of
1133 /// UsualArithmeticConversions().
1134 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1135  QualType RHSType) {
1136  /* No issue converting if at least one of the types is not a floating point
1137  type or the two types have the same rank.
1138  */
1139  if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1140  S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1141  return false;
1142 
1143  assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1144  "The remaining types must be floating point types.");
1145 
1146  auto *LHSComplex = LHSType->getAs<ComplexType>();
1147  auto *RHSComplex = RHSType->getAs<ComplexType>();
1148 
1149  QualType LHSElemType = LHSComplex ?
1150  LHSComplex->getElementType() : LHSType;
1151  QualType RHSElemType = RHSComplex ?
1152  RHSComplex->getElementType() : RHSType;
1153 
1154  // No issue if the two types have the same representation
1155  if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1156  &S.Context.getFloatTypeSemantics(RHSElemType))
1157  return false;
1158 
1159  bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1160  RHSElemType == S.Context.LongDoubleTy);
1161  Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1162  RHSElemType == S.Context.Float128Ty);
1163 
1164  // We've handled the situation where __float128 and long double have the same
1165  // representation. We allow all conversions for all possible long double types
1166  // except PPC's double double.
1167  return Float128AndLongDouble &&
1169  &llvm::APFloat::PPCDoubleDouble());
1170 }
1171 
1172 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1173 
1174 namespace {
1175 /// These helper callbacks are placed in an anonymous namespace to
1176 /// permit their use as function template parameters.
1177 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1178  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1179 }
1180 
1181 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1182  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1183  CK_IntegralComplexCast);
1184 }
1185 }
1186 
1187 /// Handle integer arithmetic conversions. Helper function of
1188 /// UsualArithmeticConversions()
1189 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1191  ExprResult &RHS, QualType LHSType,
1192  QualType RHSType, bool IsCompAssign) {
1193  // The rules for this case are in C99 6.3.1.8
1194  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1195  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1196  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1197  if (LHSSigned == RHSSigned) {
1198  // Same signedness; use the higher-ranked type
1199  if (order >= 0) {
1200  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1201  return LHSType;
1202  } else if (!IsCompAssign)
1203  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1204  return RHSType;
1205  } else if (order != (LHSSigned ? 1 : -1)) {
1206  // The unsigned type has greater than or equal rank to the
1207  // signed type, so use the unsigned type
1208  if (RHSSigned) {
1209  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1210  return LHSType;
1211  } else if (!IsCompAssign)
1212  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1213  return RHSType;
1214  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1215  // The two types are different widths; if we are here, that
1216  // means the signed type is larger than the unsigned type, so
1217  // use the signed type.
1218  if (LHSSigned) {
1219  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1220  return LHSType;
1221  } else if (!IsCompAssign)
1222  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1223  return RHSType;
1224  } else {
1225  // The signed type is higher-ranked than the unsigned type,
1226  // but isn't actually any bigger (like unsigned int and long
1227  // on most 32-bit systems). Use the unsigned type corresponding
1228  // to the signed type.
1229  QualType result =
1230  S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1231  RHS = (*doRHSCast)(S, RHS.get(), result);
1232  if (!IsCompAssign)
1233  LHS = (*doLHSCast)(S, LHS.get(), result);
1234  return result;
1235  }
1236 }
1237 
1238 /// Handle conversions with GCC complex int extension. Helper function
1239 /// of UsualArithmeticConversions()
1241  ExprResult &RHS, QualType LHSType,
1242  QualType RHSType,
1243  bool IsCompAssign) {
1244  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1245  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1246 
1247  if (LHSComplexInt && RHSComplexInt) {
1248  QualType LHSEltType = LHSComplexInt->getElementType();
1249  QualType RHSEltType = RHSComplexInt->getElementType();
1250  QualType ScalarType =
1251  handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1252  (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1253 
1254  return S.Context.getComplexType(ScalarType);
1255  }
1256 
1257  if (LHSComplexInt) {
1258  QualType LHSEltType = LHSComplexInt->getElementType();
1259  QualType ScalarType =
1260  handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1261  (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1262  QualType ComplexType = S.Context.getComplexType(ScalarType);
1263  RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1264  CK_IntegralRealToComplex);
1265 
1266  return ComplexType;
1267  }
1268 
1269  assert(RHSComplexInt);
1270 
1271  QualType RHSEltType = RHSComplexInt->getElementType();
1272  QualType ScalarType =
1273  handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1274  (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1275  QualType ComplexType = S.Context.getComplexType(ScalarType);
1276 
1277  if (!IsCompAssign)
1278  LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1279  CK_IntegralRealToComplex);
1280  return ComplexType;
1281 }
1282 
1283 /// Return the rank of a given fixed point or integer type. The value itself
1284 /// doesn't matter, but the values must be increasing with proper increasing
1285 /// rank as described in N1169 4.1.1.
1286 static unsigned GetFixedPointRank(QualType Ty) {
1287  const auto *BTy = Ty->getAs<BuiltinType>();
1288  assert(BTy && "Expected a builtin type.");
1289 
1290  switch (BTy->getKind()) {
1291  case BuiltinType::ShortFract:
1292  case BuiltinType::UShortFract:
1293  case BuiltinType::SatShortFract:
1294  case BuiltinType::SatUShortFract:
1295  return 1;
1296  case BuiltinType::Fract:
1297  case BuiltinType::UFract:
1298  case BuiltinType::SatFract:
1299  case BuiltinType::SatUFract:
1300  return 2;
1301  case BuiltinType::LongFract:
1302  case BuiltinType::ULongFract:
1303  case BuiltinType::SatLongFract:
1304  case BuiltinType::SatULongFract:
1305  return 3;
1306  case BuiltinType::ShortAccum:
1307  case BuiltinType::UShortAccum:
1308  case BuiltinType::SatShortAccum:
1309  case BuiltinType::SatUShortAccum:
1310  return 4;
1311  case BuiltinType::Accum:
1312  case BuiltinType::UAccum:
1313  case BuiltinType::SatAccum:
1314  case BuiltinType::SatUAccum:
1315  return 5;
1316  case BuiltinType::LongAccum:
1317  case BuiltinType::ULongAccum:
1318  case BuiltinType::SatLongAccum:
1319  case BuiltinType::SatULongAccum:
1320  return 6;
1321  default:
1322  if (BTy->isInteger())
1323  return 0;
1324  llvm_unreachable("Unexpected fixed point or integer type");
1325  }
1326 }
1327 
1328 /// handleFixedPointConversion - Fixed point operations between fixed
1329 /// point types and integers or other fixed point types do not fall under
1330 /// usual arithmetic conversion since these conversions could result in loss
1331 /// of precsision (N1169 4.1.4). These operations should be calculated with
1332 /// the full precision of their result type (N1169 4.1.6.2.1).
1334  QualType RHSTy) {
1335  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1336  "Expected at least one of the operands to be a fixed point type");
1337  assert((LHSTy->isFixedPointOrIntegerType() ||
1338  RHSTy->isFixedPointOrIntegerType()) &&
1339  "Special fixed point arithmetic operation conversions are only "
1340  "applied to ints or other fixed point types");
1341 
1342  // If one operand has signed fixed-point type and the other operand has
1343  // unsigned fixed-point type, then the unsigned fixed-point operand is
1344  // converted to its corresponding signed fixed-point type and the resulting
1345  // type is the type of the converted operand.
1346  if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1348  else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1350 
1351  // The result type is the type with the highest rank, whereby a fixed-point
1352  // conversion rank is always greater than an integer conversion rank; if the
1353  // type of either of the operands is a saturating fixedpoint type, the result
1354  // type shall be the saturating fixed-point type corresponding to the type
1355  // with the highest rank; the resulting value is converted (taking into
1356  // account rounding and overflow) to the precision of the resulting type.
1357  // Same ranks between signed and unsigned types are resolved earlier, so both
1358  // types are either signed or both unsigned at this point.
1359  unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1360  unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1361 
1362  QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1363 
1364  if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1365  ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1366 
1367  return ResultTy;
1368 }
1369 
1370 /// Check that the usual arithmetic conversions can be performed on this pair of
1371 /// expressions that might be of enumeration type.
1372 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1373  SourceLocation Loc,
1374  Sema::ArithConvKind ACK) {
1375  // C++2a [expr.arith.conv]p1:
1376  // If one operand is of enumeration type and the other operand is of a
1377  // different enumeration type or a floating-point type, this behavior is
1378  // deprecated ([depr.arith.conv.enum]).
1379  //
1380  // Warn on this in all language modes. Produce a deprecation warning in C++20.
1381  // Eventually we will presumably reject these cases (in C++23 onwards?).
1382  QualType L = LHS->getType(), R = RHS->getType();
1383  bool LEnum = L->isUnscopedEnumerationType(),
1384  REnum = R->isUnscopedEnumerationType();
1385  bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1386  if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1387  (REnum && L->isFloatingType())) {
1388  S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1389  ? diag::warn_arith_conv_enum_float_cxx2a
1390  : diag::warn_arith_conv_enum_float)
1391  << LHS->getSourceRange() << RHS->getSourceRange()
1392  << (int)ACK << LEnum << L << R;
1393  } else if (!IsCompAssign && LEnum && REnum &&
1394  !S.Context.hasSameUnqualifiedType(L, R)) {
1395  unsigned DiagID;
1396  if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1397  !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1398  // If either enumeration type is unnamed, it's less likely that the
1399  // user cares about this, but this situation is still deprecated in
1400  // C++2a. Use a different warning group.
1401  DiagID = S.getLangOpts().CPlusPlus2a
1402  ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1403  : diag::warn_arith_conv_mixed_anon_enum_types;
1404  } else if (ACK == Sema::ACK_Conditional) {
1405  // Conditional expressions are separated out because they have
1406  // historically had a different warning flag.
1407  DiagID = S.getLangOpts().CPlusPlus2a
1408  ? diag::warn_conditional_mixed_enum_types_cxx2a
1409  : diag::warn_conditional_mixed_enum_types;
1410  } else if (ACK == Sema::ACK_Comparison) {
1411  // Comparison expressions are separated out because they have
1412  // historically had a different warning flag.
1413  DiagID = S.getLangOpts().CPlusPlus2a
1414  ? diag::warn_comparison_mixed_enum_types_cxx2a
1415  : diag::warn_comparison_mixed_enum_types;
1416  } else {
1417  DiagID = S.getLangOpts().CPlusPlus2a
1418  ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1419  : diag::warn_arith_conv_mixed_enum_types;
1420  }
1421  S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1422  << (int)ACK << L << R;
1423  }
1424 }
1425 
1426 /// UsualArithmeticConversions - Performs various conversions that are common to
1427 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1428 /// routine returns the first non-arithmetic type found. The client is
1429 /// responsible for emitting appropriate error diagnostics.
1431  SourceLocation Loc,
1432  ArithConvKind ACK) {
1433  checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1434 
1435  if (ACK != ACK_CompAssign) {
1436  LHS = UsualUnaryConversions(LHS.get());
1437  if (LHS.isInvalid())
1438  return QualType();
1439  }
1440 
1441  RHS = UsualUnaryConversions(RHS.get());
1442  if (RHS.isInvalid())
1443  return QualType();
1444 
1445  // For conversion purposes, we ignore any qualifiers.
1446  // For example, "const float" and "float" are equivalent.
1447  QualType LHSType =
1448  Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1449  QualType RHSType =
1450  Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1451 
1452  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1453  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1454  LHSType = AtomicLHS->getValueType();
1455 
1456  // If both types are identical, no conversion is needed.
1457  if (LHSType == RHSType)
1458  return LHSType;
1459 
1460  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1461  // The caller can deal with this (e.g. pointer + int).
1462  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1463  return QualType();
1464 
1465  // Apply unary and bitfield promotions to the LHS's type.
1466  QualType LHSUnpromotedType = LHSType;
1467  if (LHSType->isPromotableIntegerType())
1468  LHSType = Context.getPromotedIntegerType(LHSType);
1469  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1470  if (!LHSBitfieldPromoteTy.isNull())
1471  LHSType = LHSBitfieldPromoteTy;
1472  if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1473  LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1474 
1475  // If both types are identical, no conversion is needed.
1476  if (LHSType == RHSType)
1477  return LHSType;
1478 
1479  // At this point, we have two different arithmetic types.
1480 
1481  // Diagnose attempts to convert between __float128 and long double where
1482  // such conversions currently can't be handled.
1483  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1484  return QualType();
1485 
1486  // Handle complex types first (C99 6.3.1.8p1).
1487  if (LHSType->isComplexType() || RHSType->isComplexType())
1488  return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1489  ACK == ACK_CompAssign);
1490 
1491  // Now handle "real" floating types (i.e. float, double, long double).
1492  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1493  return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1494  ACK == ACK_CompAssign);
1495 
1496  // Handle GCC complex int extension.
1497  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1498  return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1499  ACK == ACK_CompAssign);
1500 
1501  if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1502  return handleFixedPointConversion(*this, LHSType, RHSType);
1503 
1504  // Finally, we have two differing integer types.
1505  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1506  (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1507 }
1508 
1509 //===----------------------------------------------------------------------===//
1510 // Semantic Analysis for various Expression Types
1511 //===----------------------------------------------------------------------===//
1512 
1513 
1514 ExprResult
1516  SourceLocation DefaultLoc,
1517  SourceLocation RParenLoc,
1518  Expr *ControllingExpr,
1519  ArrayRef<ParsedType> ArgTypes,
1520  ArrayRef<Expr *> ArgExprs) {
1521  unsigned NumAssocs = ArgTypes.size();
1522  assert(NumAssocs == ArgExprs.size());
1523 
1524  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1525  for (unsigned i = 0; i < NumAssocs; ++i) {
1526  if (ArgTypes[i])
1527  (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1528  else
1529  Types[i] = nullptr;
1530  }
1531 
1532  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1533  ControllingExpr,
1534  llvm::makeArrayRef(Types, NumAssocs),
1535  ArgExprs);
1536  delete [] Types;
1537  return ER;
1538 }
1539 
1540 ExprResult
1542  SourceLocation DefaultLoc,
1543  SourceLocation RParenLoc,
1544  Expr *ControllingExpr,
1546  ArrayRef<Expr *> Exprs) {
1547  unsigned NumAssocs = Types.size();
1548  assert(NumAssocs == Exprs.size());
1549 
1550  // Decay and strip qualifiers for the controlling expression type, and handle
1551  // placeholder type replacement. See committee discussion from WG14 DR423.
1552  {
1555  ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1556  if (R.isInvalid())
1557  return ExprError();
1558  ControllingExpr = R.get();
1559  }
1560 
1561  // The controlling expression is an unevaluated operand, so side effects are
1562  // likely unintended.
1563  if (!inTemplateInstantiation() &&
1564  ControllingExpr->HasSideEffects(Context, false))
1565  Diag(ControllingExpr->getExprLoc(),
1566  diag::warn_side_effects_unevaluated_context);
1567 
1568  bool TypeErrorFound = false,
1569  IsResultDependent = ControllingExpr->isTypeDependent(),
1570  ContainsUnexpandedParameterPack
1571  = ControllingExpr->containsUnexpandedParameterPack();
1572 
1573  for (unsigned i = 0; i < NumAssocs; ++i) {
1574  if (Exprs[i]->containsUnexpandedParameterPack())
1575  ContainsUnexpandedParameterPack = true;
1576 
1577  if (Types[i]) {
1578  if (Types[i]->getType()->containsUnexpandedParameterPack())
1579  ContainsUnexpandedParameterPack = true;
1580 
1581  if (Types[i]->getType()->isDependentType()) {
1582  IsResultDependent = true;
1583  } else {
1584  // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1585  // complete object type other than a variably modified type."
1586  unsigned D = 0;
1587  if (Types[i]->getType()->isIncompleteType())
1588  D = diag::err_assoc_type_incomplete;
1589  else if (!Types[i]->getType()->isObjectType())
1590  D = diag::err_assoc_type_nonobject;
1591  else if (Types[i]->getType()->isVariablyModifiedType())
1592  D = diag::err_assoc_type_variably_modified;
1593 
1594  if (D != 0) {
1595  Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1596  << Types[i]->getTypeLoc().getSourceRange()
1597  << Types[i]->getType();
1598  TypeErrorFound = true;
1599  }
1600 
1601  // C11 6.5.1.1p2 "No two generic associations in the same generic
1602  // selection shall specify compatible types."
1603  for (unsigned j = i+1; j < NumAssocs; ++j)
1604  if (Types[j] && !Types[j]->getType()->isDependentType() &&
1605  Context.typesAreCompatible(Types[i]->getType(),
1606  Types[j]->getType())) {
1607  Diag(Types[j]->getTypeLoc().getBeginLoc(),
1608  diag::err_assoc_compatible_types)
1609  << Types[j]->getTypeLoc().getSourceRange()
1610  << Types[j]->getType()
1611  << Types[i]->getType();
1612  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1613  diag::note_compat_assoc)
1614  << Types[i]->getTypeLoc().getSourceRange()
1615  << Types[i]->getType();
1616  TypeErrorFound = true;
1617  }
1618  }
1619  }
1620  }
1621  if (TypeErrorFound)
1622  return ExprError();
1623 
1624  // If we determined that the generic selection is result-dependent, don't
1625  // try to compute the result expression.
1626  if (IsResultDependent)
1627  return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1628  Exprs, DefaultLoc, RParenLoc,
1629  ContainsUnexpandedParameterPack);
1630 
1631  SmallVector<unsigned, 1> CompatIndices;
1632  unsigned DefaultIndex = -1U;
1633  for (unsigned i = 0; i < NumAssocs; ++i) {
1634  if (!Types[i])
1635  DefaultIndex = i;
1636  else if (Context.typesAreCompatible(ControllingExpr->getType(),
1637  Types[i]->getType()))
1638  CompatIndices.push_back(i);
1639  }
1640 
1641  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1642  // type compatible with at most one of the types named in its generic
1643  // association list."
1644  if (CompatIndices.size() > 1) {
1645  // We strip parens here because the controlling expression is typically
1646  // parenthesized in macro definitions.
1647  ControllingExpr = ControllingExpr->IgnoreParens();
1648  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1649  << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1650  << (unsigned)CompatIndices.size();
1651  for (unsigned I : CompatIndices) {
1652  Diag(Types[I]->getTypeLoc().getBeginLoc(),
1653  diag::note_compat_assoc)
1654  << Types[I]->getTypeLoc().getSourceRange()
1655  << Types[I]->getType();
1656  }
1657  return ExprError();
1658  }
1659 
1660  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1661  // its controlling expression shall have type compatible with exactly one of
1662  // the types named in its generic association list."
1663  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1664  // We strip parens here because the controlling expression is typically
1665  // parenthesized in macro definitions.
1666  ControllingExpr = ControllingExpr->IgnoreParens();
1667  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1668  << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1669  return ExprError();
1670  }
1671 
1672  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1673  // type name that is compatible with the type of the controlling expression,
1674  // then the result expression of the generic selection is the expression
1675  // in that generic association. Otherwise, the result expression of the
1676  // generic selection is the expression in the default generic association."
1677  unsigned ResultIndex =
1678  CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1679 
1681  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1682  ContainsUnexpandedParameterPack, ResultIndex);
1683 }
1684 
1685 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1686 /// location of the token and the offset of the ud-suffix within it.
1688  unsigned Offset) {
1689  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1690  S.getLangOpts());
1691 }
1692 
1693 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1694 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1696  IdentifierInfo *UDSuffix,
1697  SourceLocation UDSuffixLoc,
1698  ArrayRef<Expr*> Args,
1699  SourceLocation LitEndLoc) {
1700  assert(Args.size() <= 2 && "too many arguments for literal operator");
1701 
1702  QualType ArgTy[2];
1703  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1704  ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1705  if (ArgTy[ArgIdx]->isArrayType())
1706  ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1707  }
1708 
1709  DeclarationName OpName =
1711  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1712  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1713 
1714  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1715  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1716  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1717  /*AllowStringTemplate*/ false,
1718  /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1719  return ExprError();
1720 
1721  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1722 }
1723 
1724 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1725 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1726 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1727 /// multiple tokens. However, the common case is that StringToks points to one
1728 /// string.
1729 ///
1730 ExprResult
1732  assert(!StringToks.empty() && "Must have at least one string!");
1733 
1734  StringLiteralParser Literal(StringToks, PP);
1735  if (Literal.hadError)
1736  return ExprError();
1737 
1738  SmallVector<SourceLocation, 4> StringTokLocs;
1739  for (const Token &Tok : StringToks)
1740  StringTokLocs.push_back(Tok.getLocation());
1741 
1742  QualType CharTy = Context.CharTy;
1744  if (Literal.isWide()) {
1745  CharTy = Context.getWideCharType();
1746  Kind = StringLiteral::Wide;
1747  } else if (Literal.isUTF8()) {
1748  if (getLangOpts().Char8)
1749  CharTy = Context.Char8Ty;
1750  Kind = StringLiteral::UTF8;
1751  } else if (Literal.isUTF16()) {
1752  CharTy = Context.Char16Ty;
1753  Kind = StringLiteral::UTF16;
1754  } else if (Literal.isUTF32()) {
1755  CharTy = Context.Char32Ty;
1756  Kind = StringLiteral::UTF32;
1757  } else if (Literal.isPascal()) {
1758  CharTy = Context.UnsignedCharTy;
1759  }
1760 
1761  // Warn on initializing an array of char from a u8 string literal; this
1762  // becomes ill-formed in C++2a.
1763  if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1764  !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1765  Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1766 
1767  // Create removals for all 'u8' prefixes in the string literal(s). This
1768  // ensures C++2a compatibility (but may change the program behavior when
1769  // built by non-Clang compilers for which the execution character set is
1770  // not always UTF-8).
1771  auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1772  SourceLocation RemovalDiagLoc;
1773  for (const Token &Tok : StringToks) {
1774  if (Tok.getKind() == tok::utf8_string_literal) {
1775  if (RemovalDiagLoc.isInvalid())
1776  RemovalDiagLoc = Tok.getLocation();
1778  Tok.getLocation(),
1779  Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1780  getSourceManager(), getLangOpts())));
1781  }
1782  }
1783  Diag(RemovalDiagLoc, RemovalDiag);
1784  }
1785 
1786  QualType StrTy =
1787  Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1788 
1789  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1790  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1791  Kind, Literal.Pascal, StrTy,
1792  &StringTokLocs[0],
1793  StringTokLocs.size());
1794  if (Literal.getUDSuffix().empty())
1795  return Lit;
1796 
1797  // We're building a user-defined literal.
1798  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1799  SourceLocation UDSuffixLoc =
1800  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1801  Literal.getUDSuffixOffset());
1802 
1803  // Make sure we're allowed user-defined literals here.
1804  if (!UDLScope)
1805  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1806 
1807  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1808  // operator "" X (str, len)
1809  QualType SizeType = Context.getSizeType();
1810 
1811  DeclarationName OpName =
1812  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1813  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1814  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1815 
1816  QualType ArgTy[] = {
1817  Context.getArrayDecayedType(StrTy), SizeType
1818  };
1819 
1820  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1821  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1822  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1823  /*AllowStringTemplate*/ true,
1824  /*DiagnoseMissing*/ true)) {
1825 
1826  case LOLR_Cooked: {
1827  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1828  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1829  StringTokLocs[0]);
1830  Expr *Args[] = { Lit, LenArg };
1831 
1832  return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1833  }
1834 
1835  case LOLR_StringTemplate: {
1836  TemplateArgumentListInfo ExplicitArgs;
1837 
1838  unsigned CharBits = Context.getIntWidth(CharTy);
1839  bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1840  llvm::APSInt Value(CharBits, CharIsUnsigned);
1841 
1842  TemplateArgument TypeArg(CharTy);
1843  TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1844  ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1845 
1846  for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1847  Value = Lit->getCodeUnit(I);
1848  TemplateArgument Arg(Context, Value, CharTy);
1849  TemplateArgumentLocInfo ArgInfo;
1850  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1851  }
1852  return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1853  &ExplicitArgs);
1854  }
1855  case LOLR_Raw:
1856  case LOLR_Template:
1857  case LOLR_ErrorNoDiagnostic:
1858  llvm_unreachable("unexpected literal operator lookup result");
1859  case LOLR_Error:
1860  return ExprError();
1861  }
1862  llvm_unreachable("unexpected literal operator lookup result");
1863 }
1864 
1865 DeclRefExpr *
1867  SourceLocation Loc,
1868  const CXXScopeSpec *SS) {
1869  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1870  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1871 }
1872 
1873 DeclRefExpr *
1875  const DeclarationNameInfo &NameInfo,
1876  const CXXScopeSpec *SS, NamedDecl *FoundD,
1877  SourceLocation TemplateKWLoc,
1878  const TemplateArgumentListInfo *TemplateArgs) {
1880  SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1881  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1882  TemplateArgs);
1883 }
1884 
1886  // A declaration named in an unevaluated operand never constitutes an odr-use.
1887  if (isUnevaluatedContext())
1888  return NOUR_Unevaluated;
1889 
1890  // C++2a [basic.def.odr]p4:
1891  // A variable x whose name appears as a potentially-evaluated expression e
1892  // is odr-used by e unless [...] x is a reference that is usable in
1893  // constant expressions.
1894  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1895  if (VD->getType()->isReferenceType() &&
1896  !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1897  VD->isUsableInConstantExpressions(Context))
1898  return NOUR_Constant;
1899  }
1900 
1901  // All remaining non-variable cases constitute an odr-use. For variables, we
1902  // need to wait and see how the expression is used.
1903  return NOUR_None;
1904 }
1905 
1906 /// BuildDeclRefExpr - Build an expression that references a
1907 /// declaration that does not require a closure capture.
1908 DeclRefExpr *
1910  const DeclarationNameInfo &NameInfo,
1911  NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1912  SourceLocation TemplateKWLoc,
1913  const TemplateArgumentListInfo *TemplateArgs) {
1914  bool RefersToCapturedVariable =
1915  isa<VarDecl>(D) &&
1916  NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1917 
1919  Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1920  VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1921  MarkDeclRefReferenced(E);
1922 
1923  // C++ [except.spec]p17:
1924  // An exception-specification is considered to be needed when:
1925  // - in an expression, the function is the unique lookup result or
1926  // the selected member of a set of overloaded functions.
1927  //
1928  // We delay doing this until after we've built the function reference and
1929  // marked it as used so that:
1930  // a) if the function is defaulted, we get errors from defining it before /
1931  // instead of errors from computing its exception specification, and
1932  // b) if the function is a defaulted comparison, we can use the body we
1933  // build when defining it as input to the exception specification
1934  // computation rather than computing a new body.
1935  if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1936  if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1937  if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1938  E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1939  }
1940  }
1941 
1942  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1943  Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1944  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1945  getCurFunction()->recordUseOfWeak(E);
1946 
1947  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1948  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1949  FD = IFD->getAnonField();
1950  if (FD) {
1951  UnusedPrivateFields.remove(FD);
1952  // Just in case we're building an illegal pointer-to-member.
1953  if (FD->isBitField())
1954  E->setObjectKind(OK_BitField);
1955  }
1956 
1957  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1958  // designates a bit-field.
1959  if (auto *BD = dyn_cast<BindingDecl>(D))
1960  if (auto *BE = BD->getBinding())
1961  E->setObjectKind(BE->getObjectKind());
1962 
1963  return E;
1964 }
1965 
1966 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1967 /// possibly a list of template arguments.
1968 ///
1969 /// If this produces template arguments, it is permitted to call
1970 /// DecomposeTemplateName.
1971 ///
1972 /// This actually loses a lot of source location information for
1973 /// non-standard name kinds; we should consider preserving that in
1974 /// some way.
1975 void
1977  TemplateArgumentListInfo &Buffer,
1978  DeclarationNameInfo &NameInfo,
1979  const TemplateArgumentListInfo *&TemplateArgs) {
1981  Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1982  Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1983 
1984  ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1985  Id.TemplateId->NumArgs);
1986  translateTemplateArguments(TemplateArgsPtr, Buffer);
1987 
1988  TemplateName TName = Id.TemplateId->Template.get();
1989  SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1990  NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1991  TemplateArgs = &Buffer;
1992  } else {
1993  NameInfo = GetNameFromUnqualifiedId(Id);
1994  TemplateArgs = nullptr;
1995  }
1996 }
1997 
1999  const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2000  DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2001  unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2002  DeclContext *Ctx =
2003  SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2004  if (!TC) {
2005  // Emit a special diagnostic for failed member lookups.
2006  // FIXME: computing the declaration context might fail here (?)
2007  if (Ctx)
2008  SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2009  << SS.getRange();
2010  else
2011  SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2012  return;
2013  }
2014 
2015  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2016  bool DroppedSpecifier =
2017  TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2018  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2019  ? diag::note_implicit_param_decl
2020  : diag::note_previous_decl;
2021  if (!Ctx)
2022  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2023  SemaRef.PDiag(NoteID));
2024  else
2025  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2026  << Typo << Ctx << DroppedSpecifier
2027  << SS.getRange(),
2028  SemaRef.PDiag(NoteID));
2029 }
2030 
2031 /// Diagnose an empty lookup.
2032 ///
2033 /// \return false if new lookup candidates were found
2036  TemplateArgumentListInfo *ExplicitTemplateArgs,
2037  ArrayRef<Expr *> Args, TypoExpr **Out) {
2038  DeclarationName Name = R.getLookupName();
2039 
2040  unsigned diagnostic = diag::err_undeclared_var_use;
2041  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2045  diagnostic = diag::err_undeclared_use;
2046  diagnostic_suggest = diag::err_undeclared_use_suggest;
2047  }
2048 
2049  // If the original lookup was an unqualified lookup, fake an
2050  // unqualified lookup. This is useful when (for example) the
2051  // original lookup would not have found something because it was a
2052  // dependent name.
2053  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2054  while (DC) {
2055  if (isa<CXXRecordDecl>(DC)) {
2056  LookupQualifiedName(R, DC);
2057 
2058  if (!R.empty()) {
2059  // Don't give errors about ambiguities in this lookup.
2060  R.suppressDiagnostics();
2061 
2062  // During a default argument instantiation the CurContext points
2063  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2064  // function parameter list, hence add an explicit check.
2065  bool isDefaultArgument =
2066  !CodeSynthesisContexts.empty() &&
2067  CodeSynthesisContexts.back().Kind ==
2068  CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2069  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2070  bool isInstance = CurMethod &&
2071  CurMethod->isInstance() &&
2072  DC == CurMethod->getParent() && !isDefaultArgument;
2073 
2074  // Give a code modification hint to insert 'this->'.
2075  // TODO: fixit for inserting 'Base<T>::' in the other cases.
2076  // Actually quite difficult!
2077  if (getLangOpts().MSVCCompat)
2078  diagnostic = diag::ext_found_via_dependent_bases_lookup;
2079  if (isInstance) {
2080  Diag(R.getNameLoc(), diagnostic) << Name
2081  << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2082  CheckCXXThisCapture(R.getNameLoc());
2083  } else {
2084  Diag(R.getNameLoc(), diagnostic) << Name;
2085  }
2086 
2087  // Do we really want to note all of these?
2088  for (NamedDecl *D : R)
2089  Diag(D->getLocation(), diag::note_dependent_var_use);
2090 
2091  // Return true if we are inside a default argument instantiation
2092  // and the found name refers to an instance member function, otherwise
2093  // the function calling DiagnoseEmptyLookup will try to create an
2094  // implicit member call and this is wrong for default argument.
2095  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2096  Diag(R.getNameLoc(), diag::err_member_call_without_object);
2097  return true;
2098  }
2099 
2100  // Tell the callee to try to recover.
2101  return false;
2102  }
2103 
2104  R.clear();
2105  }
2106 
2107  DC = DC->getLookupParent();
2108  }
2109 
2110  // We didn't find anything, so try to correct for a typo.
2111  TypoCorrection Corrected;
2112  if (S && Out) {
2113  SourceLocation TypoLoc = R.getNameLoc();
2114  assert(!ExplicitTemplateArgs &&
2115  "Diagnosing an empty lookup with explicit template args!");
2116  *Out = CorrectTypoDelayed(
2117  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2118  [=](const TypoCorrection &TC) {
2119  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2120  diagnostic, diagnostic_suggest);
2121  },
2122  nullptr, CTK_ErrorRecovery);
2123  if (*Out)
2124  return true;
2125  } else if (S &&
2126  (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2127  S, &SS, CCC, CTK_ErrorRecovery))) {
2128  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2129  bool DroppedSpecifier =
2130  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2131  R.setLookupName(Corrected.getCorrection());
2132 
2133  bool AcceptableWithRecovery = false;
2134  bool AcceptableWithoutRecovery = false;
2135  NamedDecl *ND = Corrected.getFoundDecl();
2136  if (ND) {
2137  if (Corrected.isOverloaded()) {
2141  for (NamedDecl *CD : Corrected) {
2142  if (FunctionTemplateDecl *FTD =
2143  dyn_cast<FunctionTemplateDecl>(CD))
2144  AddTemplateOverloadCandidate(
2145  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2146  Args, OCS);
2147  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2148  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2149  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2150  Args, OCS);
2151  }
2152  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2153  case OR_Success:
2154  ND = Best->FoundDecl;
2155  Corrected.setCorrectionDecl(ND);
2156  break;
2157  default:
2158  // FIXME: Arbitrarily pick the first declaration for the note.
2159  Corrected.setCorrectionDecl(ND);
2160  break;
2161  }
2162  }
2163  R.addDecl(ND);
2164  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2165  CXXRecordDecl *Record = nullptr;
2166  if (Corrected.getCorrectionSpecifier()) {
2167  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2168  Record = Ty->getAsCXXRecordDecl();
2169  }
2170  if (!Record)
2171  Record = cast<CXXRecordDecl>(
2172  ND->getDeclContext()->getRedeclContext());
2173  R.setNamingClass(Record);
2174  }
2175 
2176  auto *UnderlyingND = ND->getUnderlyingDecl();
2177  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2178  isa<FunctionTemplateDecl>(UnderlyingND);
2179  // FIXME: If we ended up with a typo for a type name or
2180  // Objective-C class name, we're in trouble because the parser
2181  // is in the wrong place to recover. Suggest the typo
2182  // correction, but don't make it a fix-it since we're not going
2183  // to recover well anyway.
2184  AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2185  getAsTypeTemplateDecl(UnderlyingND) ||
2186  isa<ObjCInterfaceDecl>(UnderlyingND);
2187  } else {
2188  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2189  // because we aren't able to recover.
2190  AcceptableWithoutRecovery = true;
2191  }
2192 
2193  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2194  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2195  ? diag::note_implicit_param_decl
2196  : diag::note_previous_decl;
2197  if (SS.isEmpty())
2198  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2199  PDiag(NoteID), AcceptableWithRecovery);
2200  else
2201  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2202  << Name << computeDeclContext(SS, false)
2203  << DroppedSpecifier << SS.getRange(),
2204  PDiag(NoteID), AcceptableWithRecovery);
2205 
2206  // Tell the callee whether to try to recover.
2207  return !AcceptableWithRecovery;
2208  }
2209  }
2210  R.clear();
2211 
2212  // Emit a special diagnostic for failed member lookups.
2213  // FIXME: computing the declaration context might fail here (?)
2214  if (!SS.isEmpty()) {
2215  Diag(R.getNameLoc(), diag::err_no_member)
2216  << Name << computeDeclContext(SS, false)
2217  << SS.getRange();
2218  return true;
2219  }
2220 
2221  // Give up, we can't recover.
2222  Diag(R.getNameLoc(), diagnostic) << Name;
2223  return true;
2224 }
2225 
2226 /// In Microsoft mode, if we are inside a template class whose parent class has
2227 /// dependent base classes, and we can't resolve an unqualified identifier, then
2228 /// assume the identifier is a member of a dependent base class. We can only
2229 /// recover successfully in static methods, instance methods, and other contexts
2230 /// where 'this' is available. This doesn't precisely match MSVC's
2231 /// instantiation model, but it's close enough.
2232 static Expr *
2234  DeclarationNameInfo &NameInfo,
2235  SourceLocation TemplateKWLoc,
2236  const TemplateArgumentListInfo *TemplateArgs) {
2237  // Only try to recover from lookup into dependent bases in static methods or
2238  // contexts where 'this' is available.
2239  QualType ThisType = S.getCurrentThisType();
2240  const CXXRecordDecl *RD = nullptr;
2241  if (!ThisType.isNull())
2242  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2243  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2244  RD = MD->getParent();
2245  if (!RD || !RD->hasAnyDependentBases())
2246  return nullptr;
2247 
2248  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2249  // is available, suggest inserting 'this->' as a fixit.
2250  SourceLocation Loc = NameInfo.getLoc();
2251  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2252  DB << NameInfo.getName() << RD;
2253 
2254  if (!ThisType.isNull()) {
2255  DB << FixItHint::CreateInsertion(Loc, "this->");
2257  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2258  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2259  /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2260  }
2261 
2262  // Synthesize a fake NNS that points to the derived class. This will
2263  // perform name lookup during template instantiation.
2264  CXXScopeSpec SS;
2265  auto *NNS =
2266  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2267  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2269  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2270  TemplateArgs);
2271 }
2272 
2273 ExprResult
2275  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2276  bool HasTrailingLParen, bool IsAddressOfOperand,
2278  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2279  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2280  "cannot be direct & operand and have a trailing lparen");
2281  if (SS.isInvalid())
2282  return ExprError();
2283 
2284  TemplateArgumentListInfo TemplateArgsBuffer;
2285 
2286  // Decompose the UnqualifiedId into the following data.
2287  DeclarationNameInfo NameInfo;
2288  const TemplateArgumentListInfo *TemplateArgs;
2289  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2290 
2291  DeclarationName Name = NameInfo.getName();
2292  IdentifierInfo *II = Name.getAsIdentifierInfo();
2293  SourceLocation NameLoc = NameInfo.getLoc();
2294 
2295  if (II && II->isEditorPlaceholder()) {
2296  // FIXME: When typed placeholders are supported we can create a typed
2297  // placeholder expression node.
2298  return ExprError();
2299  }
2300 
2301  // C++ [temp.dep.expr]p3:
2302  // An id-expression is type-dependent if it contains:
2303  // -- an identifier that was declared with a dependent type,
2304  // (note: handled after lookup)
2305  // -- a template-id that is dependent,
2306  // (note: handled in BuildTemplateIdExpr)
2307  // -- a conversion-function-id that specifies a dependent type,
2308  // -- a nested-name-specifier that contains a class-name that
2309  // names a dependent type.
2310  // Determine whether this is a member of an unknown specialization;
2311  // we need to handle these differently.
2312  bool DependentID = false;
2314  Name.getCXXNameType()->isDependentType()) {
2315  DependentID = true;
2316  } else if (SS.isSet()) {
2317  if (DeclContext *DC = computeDeclContext(SS, false)) {
2318  if (RequireCompleteDeclContext(SS, DC))
2319  return ExprError();
2320  } else {
2321  DependentID = true;
2322  }
2323  }
2324 
2325  if (DependentID)
2326  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2327  IsAddressOfOperand, TemplateArgs);
2328 
2329  // Perform the required lookup.
2330  LookupResult R(*this, NameInfo,
2332  ? LookupObjCImplicitSelfParam
2333  : LookupOrdinaryName);
2334  if (TemplateKWLoc.isValid() || TemplateArgs) {
2335  // Lookup the template name again to correctly establish the context in
2336  // which it was found. This is really unfortunate as we already did the
2337  // lookup to determine that it was a template name in the first place. If
2338  // this becomes a performance hit, we can work harder to preserve those
2339  // results until we get here but it's likely not worth it.
2340  bool MemberOfUnknownSpecialization;
2341  AssumedTemplateKind AssumedTemplate;
2342  if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2343  MemberOfUnknownSpecialization, TemplateKWLoc,
2344  &AssumedTemplate))
2345  return ExprError();
2346 
2347  if (MemberOfUnknownSpecialization ||
2349  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2350  IsAddressOfOperand, TemplateArgs);
2351  } else {
2352  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2353  LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2354 
2355  // If the result might be in a dependent base class, this is a dependent
2356  // id-expression.
2358  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2359  IsAddressOfOperand, TemplateArgs);
2360 
2361  // If this reference is in an Objective-C method, then we need to do
2362  // some special Objective-C lookup, too.
2363  if (IvarLookupFollowUp) {
2364  ExprResult E(LookupInObjCMethod(R, S, II, true));
2365  if (E.isInvalid())
2366  return ExprError();
2367 
2368  if (Expr *Ex = E.getAs<Expr>())
2369  return Ex;
2370  }
2371  }
2372 
2373  if (R.isAmbiguous())
2374  return ExprError();
2375 
2376  // This could be an implicitly declared function reference (legal in C90,
2377  // extension in C99, forbidden in C++).
2378  if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2379  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2380  if (D) R.addDecl(D);
2381  }
2382 
2383  // Determine whether this name might be a candidate for
2384  // argument-dependent lookup.
2385  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2386 
2387  if (R.empty() && !ADL) {
2388  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2389  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2390  TemplateKWLoc, TemplateArgs))
2391  return E;
2392  }
2393 
2394  // Don't diagnose an empty lookup for inline assembly.
2395  if (IsInlineAsmIdentifier)
2396  return ExprError();
2397 
2398  // If this name wasn't predeclared and if this is not a function
2399  // call, diagnose the problem.
2400  TypoExpr *TE = nullptr;
2401  DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2402  : nullptr);
2403  DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2404  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2405  "Typo correction callback misconfigured");
2406  if (CCC) {
2407  // Make sure the callback knows what the typo being diagnosed is.
2408  CCC->setTypoName(II);
2409  if (SS.isValid())
2410  CCC->setTypoNNS(SS.getScopeRep());
2411  }
2412  // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2413  // a template name, but we happen to have always already looked up the name
2414  // before we get here if it must be a template name.
2415  if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2416  None, &TE)) {
2417  if (TE && KeywordReplacement) {
2418  auto &State = getTypoExprState(TE);
2419  auto BestTC = State.Consumer->getNextCorrection();
2420  if (BestTC.isKeyword()) {
2421  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2422  if (State.DiagHandler)
2423  State.DiagHandler(BestTC);
2424  KeywordReplacement->startToken();
2425  KeywordReplacement->setKind(II->getTokenID());
2426  KeywordReplacement->setIdentifierInfo(II);
2427  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2428  // Clean up the state associated with the TypoExpr, since it has
2429  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2430  clearDelayedTypo(TE);
2431  // Signal that a correction to a keyword was performed by returning a
2432  // valid-but-null ExprResult.
2433  return (Expr*)nullptr;
2434  }
2435  State.Consumer->resetCorrectionStream();
2436  }
2437  return TE ? TE : ExprError();
2438  }
2439 
2440  assert(!R.empty() &&
2441  "DiagnoseEmptyLookup returned false but added no results");
2442 
2443  // If we found an Objective-C instance variable, let
2444  // LookupInObjCMethod build the appropriate expression to
2445  // reference the ivar.
2446  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2447  R.clear();
2448  ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2449  // In a hopelessly buggy code, Objective-C instance variable
2450  // lookup fails and no expression will be built to reference it.
2451  if (!E.isInvalid() && !E.get())
2452  return ExprError();
2453  return E;
2454  }
2455  }
2456 
2457  // This is guaranteed from this point on.
2458  assert(!R.empty() || ADL);
2459 
2460  // Check whether this might be a C++ implicit instance member access.
2461  // C++ [class.mfct.non-static]p3:
2462  // When an id-expression that is not part of a class member access
2463  // syntax and not used to form a pointer to member is used in the
2464  // body of a non-static member function of class X, if name lookup
2465  // resolves the name in the id-expression to a non-static non-type
2466  // member of some class C, the id-expression is transformed into a
2467  // class member access expression using (*this) as the
2468  // postfix-expression to the left of the . operator.
2469  //
2470  // But we don't actually need to do this for '&' operands if R
2471  // resolved to a function or overloaded function set, because the
2472  // expression is ill-formed if it actually works out to be a
2473  // non-static member function:
2474  //
2475  // C++ [expr.ref]p4:
2476  // Otherwise, if E1.E2 refers to a non-static member function. . .
2477  // [t]he expression can be used only as the left-hand operand of a
2478  // member function call.
2479  //
2480  // There are other safeguards against such uses, but it's important
2481  // to get this right here so that we don't end up making a
2482  // spuriously dependent expression if we're inside a dependent
2483  // instance method.
2484  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2485  bool MightBeImplicitMember;
2486  if (!IsAddressOfOperand)
2487  MightBeImplicitMember = true;
2488  else if (!SS.isEmpty())
2489  MightBeImplicitMember = false;
2490  else if (R.isOverloadedResult())
2491  MightBeImplicitMember = false;
2492  else if (R.isUnresolvableResult())
2493  MightBeImplicitMember = true;
2494  else
2495  MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2496  isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2497  isa<MSPropertyDecl>(R.getFoundDecl());
2498 
2499  if (MightBeImplicitMember)
2500  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2501  R, TemplateArgs, S);
2502  }
2503 
2504  if (TemplateArgs || TemplateKWLoc.isValid()) {
2505 
2506  // In C++1y, if this is a variable template id, then check it
2507  // in BuildTemplateIdExpr().
2508  // The single lookup result must be a variable template declaration.
2510  Id.TemplateId->Kind == TNK_Var_template) {
2511  assert(R.getAsSingle<VarTemplateDecl>() &&
2512  "There should only be one declaration found.");
2513  }
2514 
2515  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2516  }
2517 
2518  return BuildDeclarationNameExpr(SS, R, ADL);
2519 }
2520 
2521 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2522 /// declaration name, generally during template instantiation.
2523 /// There's a large number of things which don't need to be done along
2524 /// this path.
2526  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2527  bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2528  DeclContext *DC = computeDeclContext(SS, false);
2529  if (!DC)
2530  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2531  NameInfo, /*TemplateArgs=*/nullptr);
2532 
2533  if (RequireCompleteDeclContext(SS, DC))
2534  return ExprError();
2535 
2536  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2537  LookupQualifiedName(R, DC);
2538 
2539  if (R.isAmbiguous())
2540  return ExprError();
2541 
2543  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2544  NameInfo, /*TemplateArgs=*/nullptr);
2545 
2546  if (R.empty()) {
2547  Diag(NameInfo.getLoc(), diag::err_no_member)
2548  << NameInfo.getName() << DC << SS.getRange();
2549  return ExprError();
2550  }
2551 
2552  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2553  // Diagnose a missing typename if this resolved unambiguously to a type in
2554  // a dependent context. If we can recover with a type, downgrade this to
2555  // a warning in Microsoft compatibility mode.
2556  unsigned DiagID = diag::err_typename_missing;
2557  if (RecoveryTSI && getLangOpts().MSVCCompat)
2558  DiagID = diag::ext_typename_missing;
2559  SourceLocation Loc = SS.getBeginLoc();
2560  auto D = Diag(Loc, DiagID);
2561  D << SS.getScopeRep() << NameInfo.getName().getAsString()
2562  << SourceRange(Loc, NameInfo.getEndLoc());
2563 
2564  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2565  // context.
2566  if (!RecoveryTSI)
2567  return ExprError();
2568 
2569  // Only issue the fixit if we're prepared to recover.
2570  D << FixItHint::CreateInsertion(Loc, "typename ");
2571 
2572  // Recover by pretending this was an elaborated type.
2573  QualType Ty = Context.getTypeDeclType(TD);
2574  TypeLocBuilder TLB;
2575  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2576 
2577  QualType ET = getElaboratedType(ETK_None, SS, Ty);
2578  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2580  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2581 
2582  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2583 
2584  return ExprEmpty();
2585  }
2586 
2587  // Defend against this resolving to an implicit member access. We usually
2588  // won't get here if this might be a legitimate a class member (we end up in
2589  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2590  // a pointer-to-member or in an unevaluated context in C++11.
2591  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2592  return BuildPossibleImplicitMemberExpr(SS,
2593  /*TemplateKWLoc=*/SourceLocation(),
2594  R, /*TemplateArgs=*/nullptr, S);
2595 
2596  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2597 }
2598 
2599 /// The parser has read a name in, and Sema has detected that we're currently
2600 /// inside an ObjC method. Perform some additional checks and determine if we
2601 /// should form a reference to an ivar.
2602 ///
2603 /// Ideally, most of this would be done by lookup, but there's
2604 /// actually quite a lot of extra work involved.
2606  IdentifierInfo *II) {
2607  SourceLocation Loc = Lookup.getNameLoc();
2608  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2609 
2610  // Check for error condition which is already reported.
2611  if (!CurMethod)
2612  return DeclResult(true);
2613 
2614  // There are two cases to handle here. 1) scoped lookup could have failed,
2615  // in which case we should look for an ivar. 2) scoped lookup could have
2616  // found a decl, but that decl is outside the current instance method (i.e.
2617  // a global variable). In these two cases, we do a lookup for an ivar with
2618  // this name, if the lookup sucedes, we replace it our current decl.
2619 
2620  // If we're in a class method, we don't normally want to look for
2621  // ivars. But if we don't find anything else, and there's an
2622  // ivar, that's an error.
2623  bool IsClassMethod = CurMethod->isClassMethod();
2624 
2625  bool LookForIvars;
2626  if (Lookup.empty())
2627  LookForIvars = true;
2628  else if (IsClassMethod)
2629  LookForIvars = false;
2630  else
2631  LookForIvars = (Lookup.isSingleResult() &&
2633  ObjCInterfaceDecl *IFace = nullptr;
2634  if (LookForIvars) {
2635  IFace = CurMethod->getClassInterface();
2636  ObjCInterfaceDecl *ClassDeclared;
2637  ObjCIvarDecl *IV = nullptr;
2638  if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2639  // Diagnose using an ivar in a class method.
2640  if (IsClassMethod) {
2641  Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2642  return DeclResult(true);
2643  }
2644 
2645  // Diagnose the use of an ivar outside of the declaring class.
2646  if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2647  !declaresSameEntity(ClassDeclared, IFace) &&
2648  !getLangOpts().DebuggerSupport)
2649  Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2650 
2651  // Success.
2652  return IV;
2653  }
2654  } else if (CurMethod->isInstanceMethod()) {
2655  // We should warn if a local variable hides an ivar.
2656  if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2657  ObjCInterfaceDecl *ClassDeclared;
2658  if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2659  if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2660  declaresSameEntity(IFace, ClassDeclared))
2661  Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2662  }
2663  }
2664  } else if (Lookup.isSingleResult() &&
2666  // If accessing a stand-alone ivar in a class method, this is an error.
2667  if (const ObjCIvarDecl *IV =
2668  dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2669  Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2670  return DeclResult(true);
2671  }
2672  }
2673 
2674  // Didn't encounter an error, didn't find an ivar.
2675  return DeclResult(false);
2676 }
2677 
2679  ObjCIvarDecl *IV) {
2680  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2681  assert(CurMethod && CurMethod->isInstanceMethod() &&
2682  "should not reference ivar from this context");
2683 
2684  ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2685  assert(IFace && "should not reference ivar from this context");
2686 
2687  // If we're referencing an invalid decl, just return this as a silent
2688  // error node. The error diagnostic was already emitted on the decl.
2689  if (IV->isInvalidDecl())
2690  return ExprError();
2691 
2692  // Check if referencing a field with __attribute__((deprecated)).
2693  if (DiagnoseUseOfDecl(IV, Loc))
2694  return ExprError();
2695 
2696  // FIXME: This should use a new expr for a direct reference, don't
2697  // turn this into Self->ivar, just return a BareIVarExpr or something.
2698  IdentifierInfo &II = Context.Idents.get("self");
2699  UnqualifiedId SelfName;
2700  SelfName.setIdentifier(&II, SourceLocation());
2702  CXXScopeSpec SelfScopeSpec;
2703  SourceLocation TemplateKWLoc;
2704  ExprResult SelfExpr =
2705  ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2706  /*HasTrailingLParen=*/false,
2707  /*IsAddressOfOperand=*/false);
2708  if (SelfExpr.isInvalid())
2709  return ExprError();
2710 
2711  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2712  if (SelfExpr.isInvalid())
2713  return ExprError();
2714 
2715  MarkAnyDeclReferenced(Loc, IV, true);
2716 
2717  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2718  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2719  !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2720  Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2721 
2722  ObjCIvarRefExpr *Result = new (Context)
2723  ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2724  IV->getLocation(), SelfExpr.get(), true, true);
2725 
2726  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2727  if (!isUnevaluatedContext() &&
2728  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2729  getCurFunction()->recordUseOfWeak(Result);
2730  }
2731  if (getLangOpts().ObjCAutoRefCount)
2732  if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2733  ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2734 
2735  return Result;
2736 }
2737 
2738 /// The parser has read a name in, and Sema has detected that we're currently
2739 /// inside an ObjC method. Perform some additional checks and determine if we
2740 /// should form a reference to an ivar. If so, build an expression referencing
2741 /// that ivar.
2742 ExprResult
2744  IdentifierInfo *II, bool AllowBuiltinCreation) {
2745  // FIXME: Integrate this lookup step into LookupParsedName.
2746  DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2747  if (Ivar.isInvalid())
2748  return ExprError();
2749  if (Ivar.isUsable())
2750  return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2751  cast<ObjCIvarDecl>(Ivar.get()));
2752 
2753  if (Lookup.empty() && II && AllowBuiltinCreation)
2754  LookupBuiltin(Lookup);
2755 
2756  // Sentinel value saying that we didn't do anything special.
2757  return ExprResult(false);
2758 }
2759 
2760 /// Cast a base object to a member's actual type.
2761 ///
2762 /// Logically this happens in three phases:
2763 ///
2764 /// * First we cast from the base type to the naming class.
2765 /// The naming class is the class into which we were looking
2766 /// when we found the member; it's the qualifier type if a
2767 /// qualifier was provided, and otherwise it's the base type.
2768 ///
2769 /// * Next we cast from the naming class to the declaring class.
2770 /// If the member we found was brought into a class's scope by
2771 /// a using declaration, this is that class; otherwise it's
2772 /// the class declaring the member.
2773 ///
2774 /// * Finally we cast from the declaring class to the "true"
2775 /// declaring class of the member. This conversion does not
2776 /// obey access control.
2777 ExprResult
2779  NestedNameSpecifier *Qualifier,
2780  NamedDecl *FoundDecl,
2781  NamedDecl *Member) {
2782  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2783  if (!RD)
2784  return From;
2785 
2786  QualType DestRecordType;
2787  QualType DestType;
2788  QualType FromRecordType;
2789  QualType FromType = From->getType();
2790  bool PointerConversions = false;
2791  if (isa<FieldDecl>(Member)) {
2792  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2793  auto FromPtrType = FromType->getAs<PointerType>();
2794  DestRecordType = Context.getAddrSpaceQualType(
2795  DestRecordType, FromPtrType
2796  ? FromType->getPointeeType().getAddressSpace()
2797  : FromType.getAddressSpace());
2798 
2799  if (FromPtrType) {
2800  DestType = Context.getPointerType(DestRecordType);
2801  FromRecordType = FromPtrType->getPointeeType();
2802  PointerConversions = true;
2803  } else {
2804  DestType = DestRecordType;
2805  FromRecordType = FromType;
2806  }
2807  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2808  if (Method->isStatic())
2809  return From;
2810 
2811  DestType = Method->getThisType();
2812  DestRecordType = DestType->getPointeeType();
2813 
2814  if (FromType->getAs<PointerType>()) {
2815  FromRecordType = FromType->getPointeeType();
2816  PointerConversions = true;
2817  } else {
2818  FromRecordType = FromType;
2819  DestType = DestRecordType;
2820  }
2821 
2822  LangAS FromAS = FromRecordType.getAddressSpace();
2823  LangAS DestAS = DestRecordType.getAddressSpace();
2824  if (FromAS != DestAS) {
2825  QualType FromRecordTypeWithoutAS =
2826  Context.removeAddrSpaceQualType(FromRecordType);
2827  QualType FromTypeWithDestAS =
2828  Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2829  if (PointerConversions)
2830  FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2831  From = ImpCastExprToType(From, FromTypeWithDestAS,
2832  CK_AddressSpaceConversion, From->getValueKind())
2833  .get();
2834  }
2835  } else {
2836  // No conversion necessary.
2837  return From;
2838  }
2839 
2840  if (DestType->isDependentType() || FromType->isDependentType())
2841  return From;
2842 
2843  // If the unqualified types are the same, no conversion is necessary.
2844  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2845  return From;
2846 
2847  SourceRange FromRange = From->getSourceRange();
2848  SourceLocation FromLoc = FromRange.getBegin();
2849 
2850  ExprValueKind VK = From->getValueKind();
2851 
2852  // C++ [class.member.lookup]p8:
2853  // [...] Ambiguities can often be resolved by qualifying a name with its
2854  // class name.
2855  //
2856  // If the member was a qualified name and the qualified referred to a
2857  // specific base subobject type, we'll cast to that intermediate type
2858  // first and then to the object in which the member is declared. That allows
2859  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2860  //
2861  // class Base { public: int x; };
2862  // class Derived1 : public Base { };
2863  // class Derived2 : public Base { };
2864  // class VeryDerived : public Derived1, public Derived2 { void f(); };
2865  //
2866  // void VeryDerived::f() {
2867  // x = 17; // error: ambiguous base subobjects
2868  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2869  // }
2870  if (Qualifier && Qualifier->getAsType()) {
2871  QualType QType = QualType(Qualifier->getAsType(), 0);
2872  assert(QType->isRecordType() && "lookup done with non-record type");
2873 
2874  QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2875 
2876  // In C++98, the qualifier type doesn't actually have to be a base
2877  // type of the object type, in which case we just ignore it.
2878  // Otherwise build the appropriate casts.
2879  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2880  CXXCastPath BasePath;
2881  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2882  FromLoc, FromRange, &BasePath))
2883  return ExprError();
2884 
2885  if (PointerConversions)
2886  QType = Context.getPointerType(QType);
2887  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2888  VK, &BasePath).get();
2889 
2890  FromType = QType;
2891  FromRecordType = QRecordType;
2892 
2893  // If the qualifier type was the same as the destination type,
2894  // we're done.
2895  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2896  return From;
2897  }
2898  }
2899 
2900  bool IgnoreAccess = false;
2901 
2902  // If we actually found the member through a using declaration, cast
2903  // down to the using declaration's type.
2904  //
2905  // Pointer equality is fine here because only one declaration of a
2906  // class ever has member declarations.
2907  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2908  assert(isa<UsingShadowDecl>(FoundDecl));
2909  QualType URecordType = Context.getTypeDeclType(
2910  cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2911 
2912  // We only need to do this if the naming-class to declaring-class
2913  // conversion is non-trivial.
2914  if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2915  assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2916  CXXCastPath BasePath;
2917  if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2918  FromLoc, FromRange, &BasePath))
2919  return ExprError();
2920 
2921  QualType UType = URecordType;
2922  if (PointerConversions)
2923  UType = Context.getPointerType(UType);
2924  From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2925  VK, &BasePath).get();
2926  FromType = UType;
2927  FromRecordType = URecordType;
2928  }
2929 
2930  // We don't do access control for the conversion from the
2931  // declaring class to the true declaring class.
2932  IgnoreAccess = true;
2933  }
2934 
2935  CXXCastPath BasePath;
2936  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2937  FromLoc, FromRange, &BasePath,
2938  IgnoreAccess))
2939  return ExprError();
2940 
2941  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2942  VK, &BasePath);
2943 }
2944 
2946  const LookupResult &R,
2947  bool HasTrailingLParen) {
2948  // Only when used directly as the postfix-expression of a call.
2949  if (!HasTrailingLParen)
2950  return false;
2951 
2952  // Never if a scope specifier was provided.
2953  if (SS.isSet())
2954  return false;
2955 
2956  // Only in C++ or ObjC++.
2957  if (!getLangOpts().CPlusPlus)
2958  return false;
2959 
2960  // Turn off ADL when we find certain kinds of declarations during
2961  // normal lookup:
2962  for (NamedDecl *D : R) {
2963  // C++0x [basic.lookup.argdep]p3:
2964  // -- a declaration of a class member
2965  // Since using decls preserve this property, we check this on the
2966  // original decl.
2967  if (D->isCXXClassMember())
2968  return false;
2969 
2970  // C++0x [basic.lookup.argdep]p3:
2971  // -- a block-scope function declaration that is not a
2972  // using-declaration
2973  // NOTE: we also trigger this for function templates (in fact, we
2974  // don't check the decl type at all, since all other decl types
2975  // turn off ADL anyway).
2976  if (isa<UsingShadowDecl>(D))
2977  D = cast<UsingShadowDecl>(D)->getTargetDecl();
2978  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2979  return false;
2980 
2981  // C++0x [basic.lookup.argdep]p3:
2982  // -- a declaration that is neither a function or a function
2983  // template
2984  // And also for builtin functions.
2985  if (isa<FunctionDecl>(D)) {
2986  FunctionDecl *FDecl = cast<FunctionDecl>(D);
2987 
2988  // But also builtin functions.
2989  if (FDecl->getBuiltinID() && FDecl->isImplicit())
2990  return false;
2991  } else if (!isa<FunctionTemplateDecl>(D))
2992  return false;
2993  }
2994 
2995  return true;
2996 }
2997 
2998 
2999 /// Diagnoses obvious problems with the use of the given declaration
3000 /// as an expression. This is only actually called for lookups that
3001 /// were not overloaded, and it doesn't promise that the declaration
3002 /// will in fact be used.
3003 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3004  if (D->isInvalidDecl())
3005  return true;
3006 
3007  if (isa<TypedefNameDecl>(D)) {
3008  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3009  return true;
3010  }
3011 
3012  if (isa<ObjCInterfaceDecl>(D)) {
3013  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3014  return true;
3015  }
3016 
3017  if (isa<NamespaceDecl>(D)) {
3018  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3019  return true;
3020  }
3021 
3022  return false;
3023 }
3024 
3025 // Certain multiversion types should be treated as overloaded even when there is
3026 // only one result.
3028  assert(R.isSingleResult() && "Expected only a single result");
3029  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3030  return FD &&
3031  (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3032 }
3033 
3035  LookupResult &R, bool NeedsADL,
3036  bool AcceptInvalidDecl) {
3037  // If this is a single, fully-resolved result and we don't need ADL,
3038  // just build an ordinary singleton decl ref.
3039  if (!NeedsADL && R.isSingleResult() &&
3042  return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3043  R.getRepresentativeDecl(), nullptr,
3044  AcceptInvalidDecl);
3045 
3046  // We only need to check the declaration if there's exactly one
3047  // result, because in the overloaded case the results can only be
3048  // functions and function templates.
3050  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3051  return ExprError();
3052 
3053  // Otherwise, just build an unresolved lookup expression. Suppress
3054  // any lookup-related diagnostics; we'll hash these out later, when
3055  // we've picked a target.
3056  R.suppressDiagnostics();
3057 
3060  SS.getWithLocInContext(Context),
3061  R.getLookupNameInfo(),
3062  NeedsADL, R.isOverloadedResult(),
3063  R.begin(), R.end());
3064 
3065  return ULE;
3066 }
3067 
3068 static void
3070  ValueDecl *var, DeclContext *DC);
3071 
3072 /// Complete semantic analysis for a reference to the given declaration.
3074  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3075  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3076  bool AcceptInvalidDecl) {
3077  assert(D && "Cannot refer to a NULL declaration");
3078  assert(!isa<FunctionTemplateDecl>(D) &&
3079  "Cannot refer unambiguously to a function template");
3080 
3081  SourceLocation Loc = NameInfo.getLoc();
3082  if (CheckDeclInExpr(*this, Loc, D))
3083  return ExprError();
3084 
3085  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3086  // Specifically diagnose references to class templates that are missing
3087  // a template argument list.
3088  diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3089  return ExprError();
3090  }
3091 
3092  // Make sure that we're referring to a value.
3093  ValueDecl *VD = dyn_cast<ValueDecl>(D);
3094  if (!VD) {
3095  Diag(Loc, diag::err_ref_non_value)
3096  << D << SS.getRange();
3097  Diag(D->getLocation(), diag::note_declared_at);
3098  return ExprError();
3099  }
3100 
3101  // Check whether this declaration can be used. Note that we suppress
3102  // this check when we're going to perform argument-dependent lookup
3103  // on this function name, because this might not be the function
3104  // that overload resolution actually selects.
3105  if (DiagnoseUseOfDecl(VD, Loc))
3106  return ExprError();
3107 
3108  // Only create DeclRefExpr's for valid Decl's.
3109  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3110  return ExprError();
3111 
3112  // Handle members of anonymous structs and unions. If we got here,
3113  // and the reference is to a class member indirect field, then this
3114  // must be the subject of a pointer-to-member expression.
3115  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3116  if (!indirectField->isCXXClassMember())
3117  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3118  indirectField);
3119 
3120  {
3121  QualType type = VD->getType();
3122  if (type.isNull())
3123  return ExprError();
3124  ExprValueKind valueKind = VK_RValue;
3125 
3126  switch (D->getKind()) {
3127  // Ignore all the non-ValueDecl kinds.
3128 #define ABSTRACT_DECL(kind)
3129 #define VALUE(type, base)
3130 #define DECL(type, base) \
3131  case Decl::type:
3132 #include "clang/AST/DeclNodes.inc"
3133  llvm_unreachable("invalid value decl kind");
3134 
3135  // These shouldn't make it here.
3136  case Decl::ObjCAtDefsField:
3137  llvm_unreachable("forming non-member reference to ivar?");
3138 
3139  // Enum constants are always r-values and never references.
3140  // Unresolved using declarations are dependent.
3141  case Decl::EnumConstant:
3142  case Decl::UnresolvedUsingValue:
3143  case Decl::OMPDeclareReduction:
3144  case Decl::OMPDeclareMapper:
3145  valueKind = VK_RValue;
3146  break;
3147 
3148  // Fields and indirect fields that got here must be for
3149  // pointer-to-member expressions; we just call them l-values for
3150  // internal consistency, because this subexpression doesn't really
3151  // exist in the high-level semantics.
3152  case Decl::Field:
3153  case Decl::IndirectField:
3154  case Decl::ObjCIvar:
3155  assert(getLangOpts().CPlusPlus &&
3156  "building reference to field in C?");
3157 
3158  // These can't have reference type in well-formed programs, but
3159  // for internal consistency we do this anyway.
3160  type = type.getNonReferenceType();
3161  valueKind = VK_LValue;
3162  break;
3163 
3164  // Non-type template parameters are either l-values or r-values
3165  // depending on the type.
3166  case Decl::NonTypeTemplateParm: {
3167  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3168  type = reftype->getPointeeType();
3169  valueKind = VK_LValue; // even if the parameter is an r-value reference
3170  break;
3171  }
3172 
3173  // For non-references, we need to strip qualifiers just in case
3174  // the template parameter was declared as 'const int' or whatever.
3175  valueKind = VK_RValue;
3176  type = type.getUnqualifiedType();
3177  break;
3178  }
3179 
3180  case Decl::Var:
3181  case Decl::VarTemplateSpecialization:
3182  case Decl::VarTemplatePartialSpecialization:
3183  case Decl::Decomposition:
3184  case Decl::OMPCapturedExpr:
3185  // In C, "extern void blah;" is valid and is an r-value.
3186  if (!getLangOpts().CPlusPlus &&
3187  !type.hasQualifiers() &&
3188  type->isVoidType()) {
3189  valueKind = VK_RValue;
3190  break;
3191  }
3192  LLVM_FALLTHROUGH;
3193 
3194  case Decl::ImplicitParam:
3195  case Decl::ParmVar: {
3196  // These are always l-values.
3197  valueKind = VK_LValue;
3198  type = type.getNonReferenceType();
3199 
3200  // FIXME: Does the addition of const really only apply in
3201  // potentially-evaluated contexts? Since the variable isn't actually
3202  // captured in an unevaluated context, it seems that the answer is no.
3203  if (!isUnevaluatedContext()) {
3204  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3205  if (!CapturedType.isNull())
3206  type = CapturedType;
3207  }
3208 
3209  break;
3210  }
3211 
3212  case Decl::Binding: {
3213  // These are always lvalues.
3214  valueKind = VK_LValue;
3215  type = type.getNonReferenceType();
3216  // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3217  // decides how that's supposed to work.
3218  auto *BD = cast<BindingDecl>(VD);
3219  if (BD->getDeclContext() != CurContext) {
3220  auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3221  if (DD && DD->hasLocalStorage())
3222  diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3223  }
3224  break;
3225  }
3226 
3227  case Decl::Function: {
3228  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3229  if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3230  type = Context.BuiltinFnTy;
3231  valueKind = VK_RValue;
3232  break;
3233  }
3234  }
3235 
3236  const FunctionType *fty = type->castAs<FunctionType>();
3237 
3238  // If we're referring to a function with an __unknown_anytype
3239  // result type, make the entire expression __unknown_anytype.
3240  if (fty->getReturnType() == Context.UnknownAnyTy) {
3241  type = Context.UnknownAnyTy;
3242  valueKind = VK_RValue;
3243  break;
3244  }
3245 
3246  // Functions are l-values in C++.
3247  if (getLangOpts().CPlusPlus) {
3248  valueKind = VK_LValue;
3249  break;
3250  }
3251 
3252  // C99 DR 316 says that, if a function type comes from a
3253  // function definition (without a prototype), that type is only
3254  // used for checking compatibility. Therefore, when referencing
3255  // the function, we pretend that we don't have the full function
3256  // type.
3257  if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3258  isa<FunctionProtoType>(fty))
3259  type = Context.getFunctionNoProtoType(fty->getReturnType(),
3260  fty->getExtInfo());
3261 
3262  // Functions are r-values in C.
3263  valueKind = VK_RValue;
3264  break;
3265  }
3266 
3267  case Decl::CXXDeductionGuide:
3268  llvm_unreachable("building reference to deduction guide");
3269 
3270  case Decl::MSProperty:
3271  valueKind = VK_LValue;
3272  break;
3273 
3274  case Decl::CXXMethod:
3275  // If we're referring to a method with an __unknown_anytype
3276  // result type, make the entire expression __unknown_anytype.
3277  // This should only be possible with a type written directly.
3278  if (const FunctionProtoType *proto
3279  = dyn_cast<FunctionProtoType>(VD->getType()))
3280  if (proto->getReturnType() == Context.UnknownAnyTy) {
3281  type = Context.UnknownAnyTy;
3282  valueKind = VK_RValue;
3283  break;
3284  }
3285 
3286  // C++ methods are l-values if static, r-values if non-static.
3287  if (cast<CXXMethodDecl>(VD)->isStatic()) {
3288  valueKind = VK_LValue;
3289  break;
3290  }
3291  LLVM_FALLTHROUGH;
3292 
3293  case Decl::CXXConversion:
3294  case Decl::CXXDestructor:
3295  case Decl::CXXConstructor:
3296  valueKind = VK_RValue;
3297  break;
3298  }
3299 
3300  return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3301  /*FIXME: TemplateKWLoc*/ SourceLocation(),
3302  TemplateArgs);
3303  }
3304 }
3305 
3306 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3307  SmallString<32> &Target) {
3308  Target.resize(CharByteWidth * (Source.size() + 1));
3309  char *ResultPtr = &Target[0];
3310  const llvm::UTF8 *ErrorPtr;
3311  bool success =
3312  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3313  (void)success;
3314  assert(success);
3315  Target.resize(ResultPtr - &Target[0]);
3316 }
3317 
3320  // Pick the current block, lambda, captured statement or function.
3321  Decl *currentDecl = nullptr;
3322  if (const BlockScopeInfo *BSI = getCurBlock())
3323  currentDecl = BSI->TheDecl;
3324  else if (const LambdaScopeInfo *LSI = getCurLambda())
3325  currentDecl = LSI->CallOperator;
3326  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3327  currentDecl = CSI->TheCapturedDecl;
3328  else
3329  currentDecl = getCurFunctionOrMethodDecl();
3330 
3331  if (!currentDecl) {
3332  Diag(Loc, diag::ext_predef_outside_function);
3333  currentDecl = Context.getTranslationUnitDecl();
3334  }
3335 
3336  QualType ResTy;
3337  StringLiteral *SL = nullptr;
3338  if (cast<DeclContext>(currentDecl)->isDependentContext())
3339  ResTy = Context.DependentTy;
3340  else {
3341  // Pre-defined identifiers are of type char[x], where x is the length of
3342  // the string.
3343  auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3344  unsigned Length = Str.length();
3345 
3346  llvm::APInt LengthI(32, Length + 1);
3348  ResTy =
3350  SmallString<32> RawChars;
3352  Str, RawChars);
3353  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3355  /*IndexTypeQuals*/ 0);
3356  SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3357  /*Pascal*/ false, ResTy, Loc);
3358  } else {
3359  ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3360  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3362  /*IndexTypeQuals*/ 0);
3363  SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3364  /*Pascal*/ false, ResTy, Loc);
3365  }
3366  }
3367 
3368  return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3369 }
3370 
3373 
3374  switch (Kind) {
3375  default: llvm_unreachable("Unknown simple primary expr!");
3376  case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3377  case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3378  case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3379  case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3380  case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3381  case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3382  case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3383  }
3384 
3385  return BuildPredefinedExpr(Loc, IK);
3386 }
3387 
3389  SmallString<16> CharBuffer;
3390  bool Invalid = false;
3391  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3392  if (Invalid)
3393  return ExprError();
3394 
3395  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3396  PP, Tok.getKind());
3397  if (Literal.hadError())
3398  return ExprError();
3399 
3400  QualType Ty;
3401  if (Literal.isWide())
3402  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3403  else if (Literal.isUTF8() && getLangOpts().Char8)
3404  Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3405  else if (Literal.isUTF16())
3406  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3407  else if (Literal.isUTF32())
3408  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3409  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3410  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3411  else
3412  Ty = Context.CharTy; // 'x' -> char in C++
3413 
3415  if (Literal.isWide())
3417  else if (Literal.isUTF16())
3419  else if (Literal.isUTF32())
3421  else if (Literal.isUTF8())
3423 
3424  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3425  Tok.getLocation());
3426 
3427  if (Literal.getUDSuffix().empty())
3428  return Lit;
3429 
3430  // We're building a user-defined literal.
3431  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3432  SourceLocation UDSuffixLoc =
3433  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3434 
3435  // Make sure we're allowed user-defined literals here.
3436  if (!UDLScope)
3437  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3438 
3439  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3440  // operator "" X (ch)
3441  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3442  Lit, Tok.getLocation());
3443 }
3444 
3446  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3447  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3448  Context.IntTy, Loc);
3449 }
3450 
3452  QualType Ty, SourceLocation Loc) {
3453  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3454 
3455  using llvm::APFloat;
3456  APFloat Val(Format);
3457 
3458  APFloat::opStatus result = Literal.GetFloatValue(Val);
3459 
3460  // Overflow is always an error, but underflow is only an error if
3461  // we underflowed to zero (APFloat reports denormals as underflow).
3462  if ((result & APFloat::opOverflow) ||
3463  ((result & APFloat::opUnderflow) && Val.isZero())) {
3464  unsigned diagnostic;
3465  SmallString<20> buffer;
3466  if (result & APFloat::opOverflow) {
3467  diagnostic = diag::warn_float_overflow;
3468  APFloat::getLargest(Format).toString(buffer);
3469  } else {
3470  diagnostic = diag::warn_float_underflow;
3471  APFloat::getSmallest(Format).toString(buffer);
3472  }
3473 
3474  S.Diag(Loc, diagnostic)
3475  << Ty
3476  << StringRef(buffer.data(), buffer.size());
3477  }
3478 
3479  bool isExact = (result == APFloat::opOK);
3480  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3481 }
3482 
3484  assert(E && "Invalid expression");
3485 
3486  if (E->isValueDependent())
3487  return false;
3488 
3489  QualType QT = E->getType();
3490  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3491  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3492  return true;
3493  }
3494 
3495  llvm::APSInt ValueAPS;
3496  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3497 
3498  if (R.isInvalid())
3499  return true;
3500 
3501  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3502  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3503  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3504  << ValueAPS.toString(10) << ValueIsPositive;
3505  return true;
3506  }
3507 
3508  return false;
3509 }
3510 
3512  // Fast path for a single digit (which is quite common). A single digit
3513  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3514  if (Tok.getLength() == 1) {
3515  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3516  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3517  }
3518 
3519  SmallString<128> SpellingBuffer;
3520  // NumericLiteralParser wants to overread by one character. Add padding to
3521  // the buffer in case the token is copied to the buffer. If getSpelling()
3522  // returns a StringRef to the memory buffer, it should have a null char at
3523  // the EOF, so it is also safe.
3524  SpellingBuffer.resize(Tok.getLength() + 1);
3525 
3526  // Get the spelling of the token, which eliminates trigraphs, etc.
3527  bool Invalid = false;
3528  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3529  if (Invalid)
3530  return ExprError();
3531 
3532  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3533  if (Literal.hadError)
3534  return ExprError();
3535 
3536  if (Literal.hasUDSuffix()) {
3537  // We're building a user-defined literal.
3538  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3539  SourceLocation UDSuffixLoc =
3540  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3541 
3542  // Make sure we're allowed user-defined literals here.
3543  if (!UDLScope)
3544  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3545 
3546  QualType CookedTy;
3547  if (Literal.isFloatingLiteral()) {
3548  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3549  // long double, the literal is treated as a call of the form
3550  // operator "" X (f L)
3551  CookedTy = Context.LongDoubleTy;
3552  } else {
3553  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3554  // unsigned long long, the literal is treated as a call of the form
3555  // operator "" X (n ULL)
3556  CookedTy = Context.UnsignedLongLongTy;
3557  }
3558 
3559  DeclarationName OpName =
3560  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3561  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3562  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3563 
3564  SourceLocation TokLoc = Tok.getLocation();
3565 
3566  // Perform literal operator lookup to determine if we're building a raw
3567  // literal or a cooked one.
3568  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3569  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3570  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3571  /*AllowStringTemplate*/ false,
3572  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3573  case LOLR_ErrorNoDiagnostic:
3574  // Lookup failure for imaginary constants isn't fatal, there's still the
3575  // GNU extension producing _Complex types.
3576  break;
3577  case LOLR_Error:
3578  return ExprError();
3579  case LOLR_Cooked: {
3580  Expr *Lit;
3581  if (Literal.isFloatingLiteral()) {
3582  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3583  } else {
3584  llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3585  if (Literal.GetIntegerValue(ResultVal))
3586  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3587  << /* Unsigned */ 1;
3588  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3589  Tok.getLocation());
3590  }
3591  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3592  }
3593 
3594  case LOLR_Raw: {
3595  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3596  // literal is treated as a call of the form
3597  // operator "" X ("n")
3598  unsigned Length = Literal.getUDSuffixOffset();
3599  QualType StrTy = Context.getConstantArrayType(
3600  Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3601  llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3602  Expr *Lit = StringLiteral::Create(
3603  Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3604  /*Pascal*/false, StrTy, &TokLoc, 1);
3605  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3606  }
3607 
3608  case LOLR_Template: {
3609  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3610  // template), L is treated as a call fo the form
3611  // operator "" X <'c1', 'c2', ... 'ck'>()
3612  // where n is the source character sequence c1 c2 ... ck.
3613  TemplateArgumentListInfo ExplicitArgs;
3614  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3615  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3616  llvm::APSInt Value(CharBits, CharIsUnsigned);
3617  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3618  Value = TokSpelling[I];
3619  TemplateArgument Arg(Context, Value, Context.CharTy);
3620  TemplateArgumentLocInfo ArgInfo;
3621  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3622  }
3623  return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3624  &ExplicitArgs);
3625  }
3626  case LOLR_StringTemplate:
3627  llvm_unreachable("unexpected literal operator lookup result");
3628  }
3629  }
3630 
3631  Expr *Res;
3632 
3633  if (Literal.isFixedPointLiteral()) {
3634  QualType Ty;
3635 
3636  if (Literal.isAccum) {
3637  if (Literal.isHalf) {
3638  Ty = Context.ShortAccumTy;
3639  } else if (Literal.isLong) {
3640  Ty = Context.LongAccumTy;
3641  } else {
3642  Ty = Context.AccumTy;
3643  }
3644  } else if (Literal.isFract) {
3645  if (Literal.isHalf) {
3646  Ty = Context.ShortFractTy;
3647  } else if (Literal.isLong) {
3648  Ty = Context.LongFractTy;
3649  } else {
3650  Ty = Context.FractTy;
3651  }
3652  }
3653 
3654  if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3655 
3656  bool isSigned = !Literal.isUnsigned;
3657  unsigned scale = Context.getFixedPointScale(Ty);
3658  unsigned bit_width = Context.getTypeInfo(Ty).Width;
3659 
3660  llvm::APInt Val(bit_width, 0, isSigned);
3661  bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3662  bool ValIsZero = Val.isNullValue() && !Overflowed;
3663 
3664  auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3665  if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3666  // Clause 6.4.4 - The value of a constant shall be in the range of
3667  // representable values for its type, with exception for constants of a
3668  // fract type with a value of exactly 1; such a constant shall denote
3669  // the maximal value for the type.
3670  --Val;
3671  else if (Val.ugt(MaxVal) || Overflowed)
3672  Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3673 
3674  Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3675  Tok.getLocation(), scale);
3676  } else if (Literal.isFloatingLiteral()) {
3677  QualType Ty;
3678  if (Literal.isHalf){
3679  if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3680  Ty = Context.HalfTy;
3681  else {
3682  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3683  return ExprError();
3684  }
3685  } else if (Literal.isFloat)
3686  Ty = Context.FloatTy;
3687  else if (Literal.isLong)
3688  Ty = Context.LongDoubleTy;
3689  else if (Literal.isFloat16)
3690  Ty = Context.Float16Ty;
3691  else if (Literal.isFloat128)
3692  Ty = Context.Float128Ty;
3693  else
3694  Ty = Context.DoubleTy;
3695 
3696  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3697 
3698  if (Ty == Context.DoubleTy) {
3699  if (getLangOpts().SinglePrecisionConstants) {
3700  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3701  if (BTy->getKind() != BuiltinType::Float) {
3702  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3703  }
3704  } else if (getLangOpts().OpenCL &&
3705  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3706  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3707  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3708  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3709  }
3710  }
3711  } else if (!Literal.isIntegerLiteral()) {
3712  return ExprError();
3713  } else {
3714  QualType Ty;
3715 
3716  // 'long long' is a C99 or C++11 feature.
3717  if (!getLangOpts().C99 && Literal.isLongLong) {
3718  if (getLangOpts().CPlusPlus)
3719  Diag(Tok.getLocation(),
3720  getLangOpts().CPlusPlus11 ?
3721  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3722  else
3723  Diag(Tok.getLocation(), diag::ext_c99_longlong);
3724  }
3725 
3726  // Get the value in the widest-possible width.
3727  unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3728  llvm::APInt ResultVal(MaxWidth, 0);
3729 
3730  if (Literal.GetIntegerValue(ResultVal)) {
3731  // If this value didn't fit into uintmax_t, error and force to ull.
3732  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3733  << /* Unsigned */ 1;
3734  Ty = Context.UnsignedLongLongTy;
3735  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3736  "long long is not intmax_t?");
3737  } else {
3738  // If this value fits into a ULL, try to figure out what else it fits into
3739  // according to the rules of C99 6.4.4.1p5.
3740 
3741  // Octal, Hexadecimal, and integers with a U suffix are allowed to
3742  // be an unsigned int.
3743  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3744 
3745  // Check from smallest to largest, picking the smallest type we can.
3746  unsigned Width = 0;
3747 
3748  // Microsoft specific integer suffixes are explicitly sized.
3749  if (Literal.MicrosoftInteger) {
3750  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3751  Width = 8;
3752  Ty = Context.CharTy;
3753  } else {
3754  Width = Literal.MicrosoftInteger;
3755  Ty = Context.getIntTypeForBitwidth(Width,
3756  /*Signed=*/!Literal.isUnsigned);
3757  }
3758  }
3759 
3760  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3761  // Are int/unsigned possibilities?
3762  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3763 
3764  // Does it fit in a unsigned int?
3765  if (ResultVal.isIntN(IntSize)) {
3766  // Does it fit in a signed int?
3767  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3768  Ty = Context.IntTy;
3769  else if (AllowUnsigned)
3770  Ty = Context.UnsignedIntTy;
3771  Width = IntSize;
3772  }
3773  }
3774 
3775  // Are long/unsigned long possibilities?
3776  if (Ty.isNull() && !Literal.isLongLong) {
3777  unsigned LongSize = Context.getTargetInfo().getLongWidth();
3778 
3779  // Does it fit in a unsigned long?
3780  if (ResultVal.isIntN(LongSize)) {
3781  // Does it fit in a signed long?
3782  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3783  Ty = Context.LongTy;
3784  else if (AllowUnsigned)
3785  Ty = Context.UnsignedLongTy;
3786  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3787  // is compatible.
3788  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3789  const unsigned LongLongSize =
3790  Context.getTargetInfo().getLongLongWidth();
3791  Diag(Tok.getLocation(),
3792  getLangOpts().CPlusPlus
3793  ? Literal.isLong
3794  ? diag::warn_old_implicitly_unsigned_long_cxx
3795  : /*C++98 UB*/ diag::
3796  ext_old_implicitly_unsigned_long_cxx
3797  : diag::warn_old_implicitly_unsigned_long)
3798  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3799  : /*will be ill-formed*/ 1);
3800  Ty = Context.UnsignedLongTy;
3801  }
3802  Width = LongSize;
3803  }
3804  }
3805 
3806  // Check long long if needed.
3807  if (Ty.isNull()) {
3808  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3809 
3810  // Does it fit in a unsigned long long?
3811  if (ResultVal.isIntN(LongLongSize)) {
3812  // Does it fit in a signed long long?
3813  // To be compatible with MSVC, hex integer literals ending with the
3814  // LL or i64 suffix are always signed in Microsoft mode.
3815  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3816  (getLangOpts().MSVCCompat && Literal.isLongLong)))
3817  Ty = Context.LongLongTy;
3818  else if (AllowUnsigned)
3819  Ty = Context.UnsignedLongLongTy;
3820  Width = LongLongSize;
3821  }
3822  }
3823 
3824  // If we still couldn't decide a type, we probably have something that
3825  // does not fit in a signed long long, but has no U suffix.
3826  if (Ty.isNull()) {
3827  Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3828  Ty = Context.UnsignedLongLongTy;
3829  Width = Context.getTargetInfo().getLongLongWidth();
3830  }
3831 
3832  if (ResultVal.getBitWidth() != Width)
3833  ResultVal = ResultVal.trunc(Width);
3834  }
3835  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3836  }
3837 
3838  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3839  if (Literal.isImaginary) {
3840  Res = new (Context) ImaginaryLiteral(Res,
3841  Context.getComplexType(Res->getType()));
3842 
3843  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3844  }
3845  return Res;
3846 }
3847 
3849  assert(E && "ActOnParenExpr() missing expr");
3850  return new (Context) ParenExpr(L, R, E);
3851 }
3852 
3854  SourceLocation Loc,
3855  SourceRange ArgRange) {
3856  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3857  // scalar or vector data type argument..."
3858  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3859  // type (C99 6.2.5p18) or void.
3860  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3861  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3862  << T << ArgRange;
3863  return true;
3864  }
3865 
3866  assert((T->isVoidType() || !T->isIncompleteType()) &&
3867  "Scalar types should always be complete");
3868  return false;
3869 }
3870 
3872  SourceLocation Loc,
3873  SourceRange ArgRange,
3874  UnaryExprOrTypeTrait TraitKind) {
3875  // Invalid types must be hard errors for SFINAE in C++.
3876  if (S.LangOpts.CPlusPlus)
3877  return true;
3878 
3879  // C99 6.5.3.4p1:
3880  if (T->isFunctionType() &&
3881  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3882  TraitKind == UETT_PreferredAlignOf)) {
3883  // sizeof(function)/alignof(function) is allowed as an extension.
3884  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3885  << TraitKind << ArgRange;
3886  return false;
3887  }
3888 
3889  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3890  // this is an error (OpenCL v1.1 s6.3.k)
3891  if (T->isVoidType()) {
3892  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3893  : diag::ext_sizeof_alignof_void_type;
3894  S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3895  return false;
3896  }
3897 
3898  return true;
3899 }
3900 
3902  SourceLocation Loc,
3903  SourceRange ArgRange,
3904  UnaryExprOrTypeTrait TraitKind) {
3905  // Reject sizeof(interface) and sizeof(interface<proto>) if the
3906  // runtime doesn't allow it.
3908  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3909  << T << (TraitKind == UETT_SizeOf)
3910  << ArgRange;
3911  return true;
3912  }
3913 
3914  return false;
3915 }
3916 
3917 /// Check whether E is a pointer from a decayed array type (the decayed
3918 /// pointer type is equal to T) and emit a warning if it is.
3920  Expr *E) {
3921  // Don't warn if the operation changed the type.
3922  if (T != E->getType())
3923  return;
3924 
3925  // Now look for array decays.
3926  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3927  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3928  return;
3929 
3930  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3931  << ICE->getType()
3932  << ICE->getSubExpr()->getType();
3933 }
3934 
3935 /// Check the constraints on expression operands to unary type expression
3936 /// and type traits.
3937 ///
3938 /// Completes any types necessary and validates the constraints on the operand
3939 /// expression. The logic mostly mirrors the type-based overload, but may modify
3940 /// the expression as it completes the type for that expression through template
3941 /// instantiation, etc.
3943  UnaryExprOrTypeTrait ExprKind) {
3944  QualType ExprTy = E->getType();
3945  assert(!ExprTy->isReferenceType());
3946 
3947  bool IsUnevaluatedOperand =
3948  (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3949  ExprKind == UETT_PreferredAlignOf);
3950  if (IsUnevaluatedOperand) {
3951  ExprResult Result = CheckUnevaluatedOperand(E);
3952  if (Result.isInvalid())
3953  return true;
3954  E = Result.get();
3955  }
3956 
3957  if (ExprKind == UETT_VecStep)
3958  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3959  E->getSourceRange());
3960 
3961  // Whitelist some types as extensions
3962  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3963  E->getSourceRange(), ExprKind))
3964  return false;
3965 
3966  // 'alignof' applied to an expression only requires the base element type of
3967  // the expression to be complete. 'sizeof' requires the expression's type to
3968  // be complete (and will attempt to complete it if it's an array of unknown
3969  // bound).
3970  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3971  if (RequireCompleteType(E->getExprLoc(),
3972  Context.getBaseElementType(E->getType()),
3973  diag::err_sizeof_alignof_incomplete_type, ExprKind,
3974  E->getSourceRange()))
3975  return true;
3976  } else {
3977  if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3978  ExprKind, E->getSourceRange()))
3979  return true;
3980  }
3981 
3982  // Completing the expression's type may have changed it.
3983  ExprTy = E->getType();
3984  assert(!ExprTy->isReferenceType());
3985 
3986  if (ExprTy->isFunctionType()) {
3987  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3988  << ExprKind << E->getSourceRange();
3989  return true;
3990  }
3991 
3992  // The operand for sizeof and alignof is in an unevaluated expression context,
3993  // so side effects could result in unintended consequences.
3994  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3995  E->HasSideEffects(Context, false))
3996  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3997 
3998  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3999  E->getSourceRange(), ExprKind))
4000  return true;
4001 
4002  if (ExprKind == UETT_SizeOf) {
4003  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4004  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4005  QualType OType = PVD->getOriginalType();
4006  QualType Type = PVD->getType();
4007  if (Type->isPointerType() && OType->isArrayType()) {
4008  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4009  << Type << OType;
4010  Diag(PVD->getLocation(), diag::note_declared_at);
4011  }
4012  }
4013  }
4014 
4015  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4016  // decays into a pointer and returns an unintended result. This is most
4017  // likely a typo for "sizeof(array) op x".
4018  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4019  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4020  BO->getLHS());
4021  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4022  BO->getRHS());
4023  }
4024  }
4025 
4026  return false;
4027 }
4028 
4029 /// Check the constraints on operands to unary expression and type
4030 /// traits.
4031 ///
4032 /// This will complete any types necessary, and validate the various constraints
4033 /// on those operands.
4034 ///
4035 /// The UsualUnaryConversions() function is *not* called by this routine.
4036 /// C99 6.3.2.1p[2-4] all state:
4037 /// Except when it is the operand of the sizeof operator ...
4038 ///
4039 /// C++ [expr.sizeof]p4
4040 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4041 /// standard conversions are not applied to the operand of sizeof.
4042 ///
4043 /// This policy is followed for all of the unary trait expressions.
4045  SourceLocation OpLoc,
4046  SourceRange ExprRange,
4047  UnaryExprOrTypeTrait ExprKind) {
4048  if (ExprType->isDependentType())
4049  return false;
4050 
4051  // C++ [expr.sizeof]p2:
4052  // When applied to a reference or a reference type, the result
4053  // is the size of the referenced type.
4054  // C++11 [expr.alignof]p3:
4055  // When alignof is applied to a reference type, the result
4056  // shall be the alignment of the referenced type.
4057  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4058  ExprType = Ref->getPointeeType();
4059 
4060  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4061  // When alignof or _Alignof is applied to an array type, the result
4062  // is the alignment of the element type.
4063  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4064  ExprKind == UETT_OpenMPRequiredSimdAlign)
4065  ExprType = Context.getBaseElementType(ExprType);
4066 
4067  if (ExprKind == UETT_VecStep)
4068  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4069 
4070  // Whitelist some types as extensions
4071  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4072  ExprKind))
4073  return false;
4074 
4075  if (RequireCompleteType(OpLoc, ExprType,
4076  diag::err_sizeof_alignof_incomplete_type,
4077  ExprKind, ExprRange))
4078  return true;
4079 
4080  if (ExprType->isFunctionType()) {
4081  Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4082  << ExprKind << ExprRange;
4083  return true;
4084  }
4085 
4086  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4087  ExprKind))
4088  return true;
4089 
4090  return false;
4091 }
4092 
4093 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4094  // Cannot know anything else if the expression is dependent.
4095  if (E->isTypeDependent())
4096  return false;
4097 
4098  if (E->getObjectKind() == OK_BitField) {
4099  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4100  << 1 << E->getSourceRange();
4101  return true;
4102  }
4103 
4104  ValueDecl *D = nullptr;
4105  Expr *Inner = E->IgnoreParens();
4106  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4107  D = DRE->getDecl();
4108  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4109  D = ME->getMemberDecl();
4110  }
4111 
4112  // If it's a field, require the containing struct to have a
4113  // complete definition so that we can compute the layout.
4114  //
4115  // This can happen in C++11 onwards, either by naming the member
4116  // in a way that is not transformed into a member access expression
4117  // (in an unevaluated operand, for instance), or by naming the member
4118  // in a trailing-return-type.
4119  //
4120  // For the record, since __alignof__ on expressions is a GCC
4121  // extension, GCC seems to permit this but always gives the
4122  // nonsensical answer 0.
4123  //
4124  // We don't really need the layout here --- we could instead just
4125  // directly check for all the appropriate alignment-lowing
4126  // attributes --- but that would require duplicating a lot of
4127  // logic that just isn't worth duplicating for such a marginal
4128  // use-case.
4129  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4130  // Fast path this check, since we at least know the record has a
4131  // definition if we can find a member of it.
4132  if (!FD->getParent()->isCompleteDefinition()) {
4133  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4134  << E->getSourceRange();
4135  return true;
4136  }
4137 
4138  // Otherwise, if it's a field, and the field doesn't have
4139  // reference type, then it must have a complete type (or be a
4140  // flexible array member, which we explicitly want to
4141  // white-list anyway), which makes the following checks trivial.
4142  if (!FD->getType()->isReferenceType())
4143  return false;
4144  }
4145 
4146  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4147 }
4148 
4150  E = E->IgnoreParens();
4151 
4152  // Cannot know anything else if the expression is dependent.
4153  if (E->isTypeDependent())
4154  return false;
4155 
4156  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4157 }
4158 
4160  CapturingScopeInfo *CSI) {
4161  assert(T->isVariablyModifiedType());
4162  assert(CSI != nullptr);
4163 
4164  // We're going to walk down into the type and look for VLA expressions.
4165  do {
4166  const Type *Ty = T.getTypePtr();
4167  switch (Ty->getTypeClass()) {
4168 #define TYPE(Class, Base)
4169 #define ABSTRACT_TYPE(Class, Base)
4170 #define NON_CANONICAL_TYPE(Class, Base)
4171 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4172 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4173 #include "clang/AST/TypeNodes.inc"
4174  T = QualType();
4175  break;
4176  // These types are never variably-modified.
4177  case Type::Builtin:
4178  case Type::Complex:
4179  case Type::Vector:
4180  case Type::ExtVector:
4181  case Type::Record:
4182  case Type::Enum:
4183  case Type::Elaborated:
4184  case Type::TemplateSpecialization:
4185  case Type::ObjCObject:
4186  case Type::ObjCInterface:
4187  case Type::ObjCObjectPointer:
4188  case Type::ObjCTypeParam:
4189  case Type::Pipe:
4190  llvm_unreachable("type class is never variably-modified!");
4191  case Type::Adjusted:
4192  T = cast<AdjustedType>(Ty)->getOriginalType();
4193  break;
4194  case Type::Decayed:
4195  T = cast<DecayedType>(Ty)->getPointeeType();
4196  break;
4197  case Type::Pointer:
4198  T = cast<PointerType>(Ty)->getPointeeType();
4199  break;
4200  case Type::BlockPointer:
4201  T = cast<BlockPointerType>(Ty)->getPointeeType();
4202  break;
4203  case Type::LValueReference:
4204  case Type::RValueReference:
4205  T = cast<ReferenceType>(Ty)->getPointeeType();
4206  break;
4207  case Type::MemberPointer:
4208  T = cast<MemberPointerType>(Ty)->getPointeeType();
4209  break;
4210  case Type::ConstantArray:
4211  case Type::IncompleteArray:
4212  // Losing element qualification here is fine.
4213  T = cast<ArrayType>(Ty)->getElementType();
4214  break;
4215  case Type::VariableArray: {
4216  // Losing element qualification here is fine.
4217  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4218 
4219  // Unknown size indication requires no size computation.
4220  // Otherwise, evaluate and record it.
4221  auto Size = VAT->getSizeExpr();
4222  if (Size && !CSI->isVLATypeCaptured(VAT) &&
4223  (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4224  CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4225 
4226  T = VAT->getElementType();
4227  break;
4228  }
4229  case Type::FunctionProto:
4230  case Type::FunctionNoProto:
4231  T = cast<FunctionType>(Ty)->getReturnType();
4232  break;
4233  case Type::Paren:
4234  case Type::TypeOf:
4235  case Type::UnaryTransform:
4236  case Type::Attributed:
4237  case Type::SubstTemplateTypeParm:
4238  case Type::PackExpansion:
4239  case Type::MacroQualified:
4240  // Keep walking after single level desugaring.
4241  T = T.getSingleStepDesugaredType(Context);
4242  break;
4243  case Type::Typedef:
4244  T = cast<TypedefType>(Ty)->desugar();
4245  break;
4246  case Type::Decltype:
4247  T = cast<DecltypeType>(Ty)->desugar();
4248  break;
4249  case Type::Auto:
4250  case Type::DeducedTemplateSpecialization:
4251  T = cast<DeducedType>(Ty)->getDeducedType();
4252  break;
4253  case Type::TypeOfExpr:
4254  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4255  break;
4256  case Type::Atomic:
4257  T = cast<AtomicType>(Ty)->getValueType();
4258  break;
4259  }
4260  } while (!T.isNull() && T->isVariablyModifiedType());
4261 }
4262 
4263 /// Build a sizeof or alignof expression given a type operand.
4264 ExprResult
4266  SourceLocation OpLoc,
4267  UnaryExprOrTypeTrait ExprKind,
4268  SourceRange R) {
4269  if (!TInfo)
4270  return ExprError();
4271 
4272  QualType T = TInfo->getType();
4273 
4274  if (!T->isDependentType() &&
4275  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4276  return ExprError();
4277 
4278  if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4279  if (auto *TT = T->getAs<TypedefType>()) {
4280  for (auto I = FunctionScopes.rbegin(),
4281  E = std::prev(FunctionScopes.rend());
4282  I != E; ++I) {
4283  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4284  if (CSI == nullptr)
4285  break;
4286  DeclContext *DC = nullptr;
4287  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4288  DC = LSI->CallOperator;
4289  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4290  DC = CRSI->TheCapturedDecl;
4291  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4292  DC = BSI->TheDecl;
4293  if (DC) {
4294  if (DC->containsDecl(TT->getDecl()))
4295  break;
4296  captureVariablyModifiedType(Context, T, CSI);
4297  }
4298  }
4299  }
4300  }
4301 
4302  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4303  return new (Context) UnaryExprOrTypeTraitExpr(
4304  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4305 }
4306 
4307 /// Build a sizeof or alignof expression given an expression
4308 /// operand.
4309 ExprResult
4311  UnaryExprOrTypeTrait ExprKind) {
4312  ExprResult PE = CheckPlaceholderExpr(E);
4313  if (PE.isInvalid())
4314  return ExprError();
4315 
4316  E = PE.get();
4317 
4318  // Verify that the operand is valid.
4319  bool isInvalid = false;
4320  if (E->isTypeDependent()) {
4321  // Delay type-checking for type-dependent expressions.
4322  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4323  isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4324  } else if (ExprKind == UETT_VecStep) {
4325  isInvalid = CheckVecStepExpr(E);
4326  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4327  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4328  isInvalid = true;
4329  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4330  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4331  isInvalid = true;
4332  } else {
4333  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4334  }
4335 
4336  if (isInvalid)
4337  return ExprError();
4338 
4339  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4340  PE = TransformToPotentiallyEvaluated(E);
4341  if (PE.isInvalid()) return ExprError();
4342  E = PE.get();
4343  }
4344 
4345  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4346  return new (Context) UnaryExprOrTypeTraitExpr(
4347  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4348 }
4349 
4350 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4351 /// expr and the same for @c alignof and @c __alignof
4352 /// Note that the ArgRange is invalid if isType is false.
4353 ExprResult
4355  UnaryExprOrTypeTrait ExprKind, bool IsType,
4356  void *TyOrEx, SourceRange ArgRange) {
4357  // If error parsing type, ignore.
4358  if (!TyOrEx) return ExprError();
4359 
4360  if (IsType) {
4361  TypeSourceInfo *TInfo;
4362  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4363  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4364  }
4365 
4366  Expr *ArgEx = (Expr *)TyOrEx;
4367  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4368  return Result;
4369 }
4370 
4372  bool IsReal) {
4373  if (V.get()->isTypeDependent())
4374  return S.Context.DependentTy;
4375 
4376  // _Real and _Imag are only l-values for normal l-values.
4377  if (V.get()->getObjectKind() != OK_Ordinary) {
4378  V = S.DefaultLvalueConversion(V.get());
4379  if (V.isInvalid())
4380  return QualType();
4381  }
4382 
4383  // These operators return the element type of a complex type.
4384  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4385  return CT->getElementType();
4386 
4387  // Otherwise they pass through real integer and floating point types here.
4388  if (V.get()->getType()->isArithmeticType())
4389  return V.get()->getType();
4390 
4391  // Test for placeholders.
4392  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4393  if (PR.isInvalid()) return QualType();
4394  if (PR.get() != V.get()) {
4395  V = PR;
4396  return CheckRealImagOperand(S, V, Loc, IsReal);
4397  }
4398 
4399  // Reject anything else.
4400  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4401  << (IsReal ? "__real" : "__imag");
4402  return QualType();
4403 }
4404 
4405 
4406 
4407 ExprResult
4409  tok::TokenKind Kind, Expr *Input) {
4410  UnaryOperatorKind Opc;
4411  switch (Kind) {
4412  default: llvm_unreachable("Unknown unary op!");
4413  case tok::plusplus: Opc = UO_PostInc; break;
4414  case tok::minusminus: Opc = UO_PostDec; break;
4415  }
4416 
4417  // Since this might is a postfix expression, get rid of ParenListExprs.
4418  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4419  if (Result.isInvalid()) return ExprError();
4420  Input = Result.get();
4421 
4422  return BuildUnaryOp(S, OpLoc, Opc, Input);
4423 }
4424 
4425 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4426 ///
4427 /// \return true on error
4429  SourceLocation opLoc,
4430  Expr *op) {
4431  assert(op->getType()->isObjCObjectPointerType());
4433  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4434  return false;
4435 
4436  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4437  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4438  << op->getSourceRange();
4439  return true;
4440 }
4441 
4443  auto *BaseNoParens = Base->IgnoreParens();
4444  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4445  return MSProp->getPropertyDecl()->getType()->isArrayType();
4446  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4447 }
4448 
4449 ExprResult
4451  Expr *idx, SourceLocation rbLoc) {
4452  if (base && !base->getType().isNull() &&
4453  base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4454  return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4455  /*Length=*/nullptr, rbLoc);
4456 
4457  // Since this might be a postfix expression, get rid of ParenListExprs.
4458  if (isa<ParenListExpr>(base)) {
4459  ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4460  if (result.isInvalid()) return ExprError();
4461  base = result.get();
4462  }
4463 
4464  // A comma-expression as the index is deprecated in C++2a onwards.
4465  if (getLangOpts().CPlusPlus2a &&
4466  ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4467  (isa<CXXOperatorCallExpr>(idx) &&
4468  cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4469  Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4470  << SourceRange(base->getBeginLoc(), rbLoc);
4471  }
4472 
4473  // Handle any non-overload placeholder types in the base and index
4474  // expressions. We can't handle overloads here because the other
4475  // operand might be an overloadable type, in which case the overload
4476  // resolution for the operator overload should get the first crack
4477  // at the overload.
4478  bool IsMSPropertySubscript = false;
4479  if (base->getType()->isNonOverloadPlaceholderType()) {
4480  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4481  if (!IsMSPropertySubscript) {
4482  ExprResult result = CheckPlaceholderExpr(base);
4483  if (result.isInvalid())
4484  return ExprError();
4485  base = result.get();
4486  }
4487  }
4488  if (idx->getType()->isNonOverloadPlaceholderType()) {
4489  ExprResult result = CheckPlaceholderExpr(idx);
4490  if (result.isInvalid()) return ExprError();
4491  idx = result.get();
4492  }
4493 
4494  // Build an unanalyzed expression if either operand is type-dependent.
4495  if (getLangOpts().CPlusPlus &&
4496  (base->isTypeDependent() || idx->isTypeDependent())) {
4497  return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4498  VK_LValue, OK_Ordinary, rbLoc);
4499  }
4500 
4501  // MSDN, property (C++)
4502  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4503  // This attribute can also be used in the declaration of an empty array in a
4504  // class or structure definition. For example:
4505  // __declspec(property(get=GetX, put=PutX)) int x[];
4506  // The above statement indicates that x[] can be used with one or more array
4507  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4508  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4509  if (IsMSPropertySubscript) {
4510  // Build MS property subscript expression if base is MS property reference
4511  // or MS property subscript.
4512  return new (Context) MSPropertySubscriptExpr(
4513  base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4514  }
4515 
4516  // Use C++ overloaded-operator rules if either operand has record
4517  // type. The spec says to do this if either type is *overloadable*,
4518  // but enum types can't declare subscript operators or conversion
4519  // operators, so there's nothing interesting for overload resolution
4520  // to do if there aren't any record types involved.
4521  //
4522  // ObjC pointers have their own subscripting logic that is not tied
4523  // to overload resolution and so should not take this path.
4524  if (getLangOpts().CPlusPlus &&
4525  (base->getType()->isRecordType() ||
4526  (!base->getType()->isObjCObjectPointerType() &&
4527  idx->getType()->isRecordType()))) {
4528  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4529  }
4530 
4531  ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4532 
4533  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4534  CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4535 
4536  return Res;
4537 }
4538 
4539 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4540  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4541  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4542 
4543  // For expressions like `&(*s).b`, the base is recorded and what should be
4544  // checked.
4545  const MemberExpr *Member = nullptr;
4546  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4547  StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4548 
4549  LastRecord.PossibleDerefs.erase(StrippedExpr);
4550 }
4551 
4552 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4553  QualType ResultTy = E->getType();
4554  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4555 
4556  // Bail if the element is an array since it is not memory access.
4557  if (isa<ArrayType>(ResultTy))
4558  return;
4559 
4560  if (ResultTy->hasAttr(attr::NoDeref)) {
4561  LastRecord.PossibleDerefs.insert(E);
4562  return;
4563  }
4564 
4565  // Check if the base type is a pointer to a member access of a struct
4566  // marked with noderef.
4567  const Expr *Base = E->getBase();
4568  QualType BaseTy = Base->getType();
4569  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4570  // Not a pointer access
4571  return;
4572 
4573  const MemberExpr *Member = nullptr;
4574  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4575  Member->isArrow())
4576  Base = Member->getBase();
4577 
4578  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4579  if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4580  LastRecord.PossibleDerefs.insert(E);
4581  }
4582 }
4583 
4585  Expr *LowerBound,
4586  SourceLocation ColonLoc, Expr *Length,
4587  SourceLocation RBLoc) {
4588  if (Base->getType()->isPlaceholderType() &&
4590  BuiltinType::OMPArraySection)) {
4591  ExprResult Result = CheckPlaceholderExpr(Base);
4592  if (Result.isInvalid())
4593  return ExprError();
4594  Base = Result.get();
4595  }
4596  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4597  ExprResult Result = CheckPlaceholderExpr(LowerBound);
4598  if (Result.isInvalid())
4599  return ExprError();
4600  Result = DefaultLvalueConversion(Result.get());
4601  if (Result.isInvalid())
4602  return ExprError();
4603  LowerBound = Result.get();
4604  }
4605  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4606  ExprResult Result = CheckPlaceholderExpr(Length);
4607  if (Result.isInvalid())
4608  return ExprError();
4609  Result = DefaultLvalueConversion(Result.get());
4610  if (Result.isInvalid())
4611  return ExprError();
4612  Length = Result.get();
4613  }
4614 
4615  // Build an unanalyzed expression if either operand is type-dependent.
4616  if (Base->isTypeDependent() ||
4617  (LowerBound &&
4618  (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4619  (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4620  return new (Context)
4621  OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4622  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4623  }
4624 
4625  // Perform default conversions.
4627  QualType ResultTy;
4628  if (OriginalTy->isAnyPointerType()) {
4629  ResultTy = OriginalTy->getPointeeType();
4630  } else if (OriginalTy->isArrayType()) {
4631  ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4632  } else {
4633  return ExprError(
4634  Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4635  << Base->getSourceRange());
4636  }
4637  // C99 6.5.2.1p1
4638  if (LowerBound) {
4639  auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4640  LowerBound);
4641  if (Res.isInvalid())
4642  return ExprError(Diag(LowerBound->getExprLoc(),
4643  diag::err_omp_typecheck_section_not_integer)
4644  << 0 << LowerBound->getSourceRange());
4645  LowerBound = Res.get();
4646 
4647  if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4648  LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4649  Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4650  << 0 << LowerBound->getSourceRange();
4651  }
4652  if (Length) {
4653  auto Res =
4654  PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4655  if (Res.isInvalid())
4656  return ExprError(Diag(Length->getExprLoc(),
4657  diag::err_omp_typecheck_section_not_integer)
4658  << 1 << Length->getSourceRange());
4659  Length = Res.get();
4660 
4661  if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4662  Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4663  Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4664  << 1 << Length->getSourceRange();
4665  }
4666 
4667  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4668  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4669  // type. Note that functions are not objects, and that (in C99 parlance)
4670  // incomplete types are not object types.
4671  if (ResultTy->isFunctionType()) {
4672  Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4673  << ResultTy << Base->getSourceRange();
4674  return ExprError();
4675  }
4676 
4677  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4678  diag::err_omp_section_incomplete_type, Base))
4679  return ExprError();
4680 
4681  if (LowerBound && !OriginalTy->isAnyPointerType()) {
4682  Expr::EvalResult Result;
4683  if (LowerBound->EvaluateAsInt(Result, Context)) {
4684  // OpenMP 4.5, [2.4 Array Sections]
4685  // The array section must be a subset of the original array.
4686  llvm::APSInt LowerBoundValue = Result.Val.getInt();
4687  if (LowerBoundValue.isNegative()) {
4688  Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4689  << LowerBound->getSourceRange();
4690  return ExprError();
4691  }
4692  }
4693  }
4694 
4695  if (Length) {
4696  Expr::EvalResult Result;
4697  if (Length->EvaluateAsInt(Result, Context)) {
4698  // OpenMP 4.5, [2.4 Array Sections]
4699  // The length must evaluate to non-negative integers.
4700  llvm::APSInt LengthValue = Result.Val.getInt();
4701  if (LengthValue.isNegative()) {
4702  Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4703  << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4704  << Length->getSourceRange();
4705  return ExprError();
4706  }
4707  }
4708  } else if (ColonLoc.isValid() &&
4709  (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4710  !OriginalTy->isVariableArrayType()))) {
4711  // OpenMP 4.5, [2.4 Array Sections]
4712  // When the size of the array dimension is not known, the length must be
4713  // specified explicitly.
4714  Diag(ColonLoc, diag::err_omp_section_length_undefined)
4715  << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4716  return ExprError();
4717  }
4718 
4719  if (!Base->getType()->isSpecificPlaceholderType(
4720  BuiltinType::OMPArraySection)) {
4721  ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4722  if (Result.isInvalid())
4723  return ExprError();
4724  Base = Result.get();
4725  }
4726  return new (Context)
4727  OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4728  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4729 }
4730 
4731 ExprResult
4733  Expr *Idx, SourceLocation RLoc) {
4734  Expr *LHSExp = Base;
4735  Expr *RHSExp = Idx;
4736 
4737  ExprValueKind VK = VK_LValue;
4739 
4740  // Per C++ core issue 1213, the result is an xvalue if either operand is
4741  // a non-lvalue array, and an lvalue otherwise.
4742  if (getLangOpts().CPlusPlus11) {
4743  for (auto *Op : {LHSExp, RHSExp}) {
4744  Op = Op->IgnoreImplicit();
4745  if (Op->getType()->isArrayType() && !Op->isLValue())
4746  VK = VK_XValue;
4747  }
4748  }
4749 
4750  // Perform default conversions.
4751  if (!LHSExp->getType()->getAs<VectorType>()) {
4752  ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4753  if (Result.isInvalid())
4754  return ExprError();
4755  LHSExp = Result.get();
4756  }
4757  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4758  if (Result.isInvalid())
4759  return ExprError();
4760  RHSExp = Result.get();
4761 
4762  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4763 
4764  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4765  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4766  // in the subscript position. As a result, we need to derive the array base
4767  // and index from the expression types.
4768  Expr *BaseExpr, *IndexExpr;
4769  QualType ResultType;
4770  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4771  BaseExpr = LHSExp;
4772  IndexExpr = RHSExp;
4773  ResultType = Context.DependentTy;
4774  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4775  BaseExpr = LHSExp;
4776  IndexExpr = RHSExp;
4777  ResultType = PTy->getPointeeType();
4778  } else if (const ObjCObjectPointerType *PTy =
4779  LHSTy->getAs<ObjCObjectPointerType>()) {
4780  BaseExpr = LHSExp;
4781  IndexExpr = RHSExp;
4782 
4783  // Use custom logic if this should be the pseudo-object subscript
4784  // expression.
4785  if (!LangOpts.isSubscriptPointerArithmetic())
4786  return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4787  nullptr);
4788 
4789  ResultType = PTy->getPointeeType();
4790  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4791  // Handle the uncommon case of "123[Ptr]".
4792  BaseExpr = RHSExp;
4793  IndexExpr = LHSExp;
4794  ResultType = PTy->getPointeeType();
4795  } else if (const ObjCObjectPointerType *PTy =
4796  RHSTy->getAs<ObjCObjectPointerType>()) {
4797  // Handle the uncommon case of "123[Ptr]".
4798  BaseExpr = RHSExp;
4799  IndexExpr = LHSExp;
4800  ResultType = PTy->getPointeeType();
4801  if (!LangOpts.isSubscriptPointerArithmetic()) {
4802  Diag(LLoc, diag::err_subscript_nonfragile_interface)
4803  << ResultType << BaseExpr->getSourceRange();
4804  return ExprError();
4805  }
4806  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4807  BaseExpr = LHSExp; // vectors: V[123]
4808  IndexExpr = RHSExp;
4809  // We apply C++ DR1213 to vector subscripting too.
4810  if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4811  ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4812  if (Materialized.isInvalid())
4813  return ExprError();
4814  LHSExp = Materialized.get();
4815  }
4816  VK = LHSExp->getValueKind();
4817  if (VK != VK_RValue)
4818  OK = OK_VectorComponent;
4819 
4820  ResultType = VTy->getElementType();
4821  QualType BaseType = BaseExpr->getType();
4822  Qualifiers BaseQuals = BaseType.getQualifiers();
4823  Qualifiers MemberQuals = ResultType.getQualifiers();
4824  Qualifiers Combined = BaseQuals + MemberQuals;
4825  if (Combined != MemberQuals)
4826  ResultType = Context.getQualifiedType(ResultType, Combined);
4827  } else if (LHSTy->isArrayType()) {
4828  // If we see an array that wasn't promoted by
4829  // DefaultFunctionArrayLvalueConversion, it must be an array that
4830  // wasn't promoted because of the C90 rule that doesn't
4831  // allow promoting non-lvalue arrays. Warn, then
4832  // force the promotion here.
4833  Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4834  << LHSExp->getSourceRange();
4835  LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4836  CK_ArrayToPointerDecay).get();
4837  LHSTy = LHSExp->getType();
4838 
4839  BaseExpr = LHSExp;
4840  IndexExpr = RHSExp;
4841  ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4842  } else if (RHSTy->isArrayType()) {
4843  // Same as previous, except for 123[f().a] case
4844  Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4845  << RHSExp->getSourceRange();
4846  RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4847  CK_ArrayToPointerDecay).get();
4848  RHSTy = RHSExp->getType();
4849 
4850  BaseExpr = RHSExp;
4851  IndexExpr = LHSExp;
4852  ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4853  } else {
4854  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4855  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4856  }
4857  // C99 6.5.2.1p1
4858  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4859  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4860  << IndexExpr->getSourceRange());
4861 
4862  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4863  IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4864  && !IndexExpr->isTypeDependent())
4865  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4866 
4867  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4868  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4869  // type. Note that Functions are not objects, and that (in C99 parlance)
4870  // incomplete types are not object types.
4871  if (ResultType->isFunctionType()) {
4872  Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4873  << ResultType << BaseExpr->getSourceRange();
4874  return ExprError();
4875  }
4876 
4877  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4878  // GNU extension: subscripting on pointer to void
4879  Diag(LLoc, diag::ext_gnu_subscript_void_type)
4880  << BaseExpr->getSourceRange();
4881 
4882  // C forbids expressions of unqualified void type from being l-values.
4883  // See IsCForbiddenLValueType.
4884  if (!ResultType.hasQualifiers()) VK = VK_RValue;
4885  } else if (!ResultType->isDependentType() &&
4886  RequireCompleteType(LLoc, ResultType,
4887  diag::err_subscript_incomplete_type, BaseExpr))
4888  return ExprError();
4889 
4890  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4891  !ResultType.isCForbiddenLValueType());
4892 
4893  if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4894  FunctionScopes.size() > 1) {
4895  if (auto *TT =
4896  LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4897  for (auto I = FunctionScopes.rbegin(),
4898  E = std::prev(FunctionScopes.rend());
4899  I != E; ++I) {
4900  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4901  if (CSI == nullptr)
4902  break;
4903  DeclContext *DC = nullptr;
4904  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4905  DC = LSI->CallOperator;
4906  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4907  DC = CRSI->TheCapturedDecl;
4908  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4909  DC = BSI->TheDecl;
4910  if (DC) {
4911  if (DC->containsDecl(TT->getDecl()))
4912  break;
4914  Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4915  }
4916  }
4917  }
4918  }
4919 
4920  return new (Context)
4921  ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4922 }
4923 
4925  ParmVarDecl *Param) {
4926  if (Param->hasUnparsedDefaultArg()) {
4927  Diag(CallLoc,
4928  diag::err_use_of_default_argument_to_function_declared_later) <<
4929  FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4930  Diag(UnparsedDefaultArgLocs[Param],
4931  diag::note_default_argument_declared_here);
4932  return true;
4933  }
4934 
4935  if (Param->hasUninstantiatedDefaultArg()) {
4936  Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4937 
4939  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4940 
4941  // Instantiate the expression.
4942  //
4943  // FIXME: Pass in a correct Pattern argument, otherwise
4944  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4945  //
4946  // template<typename T>
4947  // struct A {
4948  // static int FooImpl();
4949  //
4950  // template<typename Tp>
4951  // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4952  // // template argument list [[T], [Tp]], should be [[Tp]].
4953  // friend A<Tp> Foo(int a);
4954  // };
4955  //
4956  // template<typename T>
4957  // A<T> Foo(int a = A<T>::FooImpl());
4958  MultiLevelTemplateArgumentList MutiLevelArgList
4959  = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4960 
4961  InstantiatingTemplate Inst(*this, CallLoc, Param,
4962  MutiLevelArgList.getInnermost());
4963  if (Inst.isInvalid())
4964  return true;
4965  if (Inst.isAlreadyInstantiating()) {
4966  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4967  Param->setInvalidDecl();
4968  return true;
4969  }
4970 
4971  ExprResult Result;
4972  {
4973  // C++ [dcl.fct.default]p5:
4974  // The names in the [default argument] expression are bound, and
4975  // the semantic constraints are checked, at the point where the
4976  // default argument expression appears.
4977  ContextRAII SavedContext(*this, FD);
4978  LocalInstantiationScope Local(*this);
4979  runWithSufficientStackSpace(CallLoc, [&] {
4980  Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4981  /*DirectInit*/false);
4982  });
4983  }
4984  if (Result.isInvalid())
4985  return true;
4986 
4987  // Check the expression as an initializer for the parameter.
4988  InitializedEntity Entity
4989  = InitializedEntity::InitializeParameter(Context, Param);
4991  Param->getLocation(),
4992  /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4993  Expr *ResultE = Result.getAs<Expr>();
4994 
4995  InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4996  Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4997  if (Result.isInvalid())
4998  return true;
4999 
5000  Result =
5001  ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5002  /*DiscardedValue*/ false);
5003  if (Result.isInvalid())
5004  return true;
5005 
5006  // Remember the instantiated default argument.
5007  Param->setDefaultArg(Result.getAs<Expr>());
5008  if (ASTMutationListener *L = getASTMutationListener()) {
5009  L->DefaultArgumentInstantiated(Param);
5010  }
5011  }
5012 
5013  // If the default argument expression is not set yet, we are building it now.
5014  if (!Param->hasInit()) {
5015  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5016  Param->setInvalidDecl();
5017  return true;
5018  }
5019 
5020  // If the default expression creates temporaries, we need to
5021  // push them to the current stack of expression temporaries so they'll
5022  // be properly destroyed.
5023  // FIXME: We should really be rebuilding the default argument with new
5024  // bound temporaries; see the comment in PR5810.
5025  // We don't need to do that with block decls, though, because
5026  // blocks in default argument expression can never capture anything.
5027  if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5028  // Set the "needs cleanups" bit regardless of whether there are
5029  // any explicit objects.
5030  Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5031 
5032  // Append all the objects to the cleanup list. Right now, this
5033  // should always be a no-op, because blocks in default argument
5034  // expressions should never be able to capture anything.
5035  assert(!Init->getNumObjects() &&
5036  "default argument expression has capturing blocks?");
5037  }
5038 
5039  // We already type-checked the argument, so we know it works.
5040  // Just mark all of the declarations in this potentially-evaluated expression
5041  // as being "referenced".
5043  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5044  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5045  /*SkipLocalVariables=*/true);
5046  return false;
5047 }
5048 
5050  FunctionDecl *FD, ParmVarDecl *Param) {
5051  if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5052  return ExprError();
5053  return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5054 }
5055 
5058  Expr *Fn) {
5059  if (Proto && Proto->isVariadic()) {
5060  if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5061  return VariadicConstructor;
5062  else if (Fn && Fn->getType()->isBlockPointerType())
5063  return VariadicBlock;
5064  else if (FDecl) {
5065  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5066  if (Method->isInstance())
5067  return VariadicMethod;
5068  } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5069  return VariadicMethod;
5070  return VariadicFunction;
5071  }
5072  return VariadicDoesNotApply;
5073 }
5074 
5075 namespace {
5076 class FunctionCallCCC final : public FunctionCallFilterCCC {
5077 public:
5078  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5079  unsigned NumArgs, MemberExpr *ME)
5080  : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5081  FunctionName(FuncName) {}
5082 
5083  bool ValidateCandidate(const TypoCorrection &candidate) override {
5084  if (!candidate.getCorrectionSpecifier() ||
5085  candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5086  return false;
5087  }
5088 
5089  return FunctionCallFilterCCC::ValidateCandidate(candidate);
5090  }
5091 
5092  std::unique_ptr<CorrectionCandidateCallback> clone() override {
5093  return std::make_unique<FunctionCallCCC>(*this);
5094  }
5095 
5096 private:
5097  const IdentifierInfo *const FunctionName;
5098 };
5099 }
5100 
5102  FunctionDecl *FDecl,
5103  ArrayRef<Expr *> Args) {
5104  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5105  DeclarationName FuncName = FDecl->getDeclName();
5106  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5107 
5108  FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5109  if (TypoCorrection Corrected = S.CorrectTypo(
5110  DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5111  S.getScopeForContext(S.CurContext), nullptr, CCC,
5113  if (NamedDecl *ND = Corrected.getFoundDecl()) {
5114  if (Corrected.isOverloaded()) {
5117  for (NamedDecl *CD : Corrected) {
5118  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5120  OCS);
5121  }
5122  switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5123  case OR_Success:
5124  ND = Best->FoundDecl;
5125  Corrected.setCorrectionDecl(ND);
5126  break;
5127  default:
5128  break;
5129  }
5130  }
5131  ND = ND->getUnderlyingDecl();
5132  if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5133  return Corrected;
5134  }
5135  }
5136  return TypoCorrection();
5137 }
5138 
5139 /// ConvertArgumentsForCall - Converts the arguments specified in
5140 /// Args/NumArgs to the parameter types of the function FDecl with
5141 /// function prototype Proto. Call is the call expression itself, and
5142 /// Fn is the function expression. For a C++ member function, this
5143 /// routine does not attempt to convert the object argument. Returns
5144 /// true if the call is ill-formed.
5145 bool
5147  FunctionDecl *FDecl,
5148  const FunctionProtoType *Proto,
5149  ArrayRef<Expr *> Args,
5150  SourceLocation RParenLoc,
5151  bool IsExecConfig) {
5152  // Bail out early if calling a builtin with custom typechecking.
5153  if (FDecl)
5154  if (unsigned ID = FDecl->getBuiltinID())
5155  if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5156  return false;
5157 
5158  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5159  // assignment, to the types of the corresponding parameter, ...
5160  unsigned NumParams = Proto->getNumParams();
5161  bool Invalid = false;
5162  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5163  unsigned FnKind = Fn->getType()->isBlockPointerType()
5164  ? 1 /* block */
5165  : (IsExecConfig ? 3 /* kernel function (exec config) */
5166  : 0 /* function */);
5167 
5168  // If too few arguments are available (and we don't have default
5169  // arguments for the remaining parameters), don't make the call.
5170  if (Args.size() < NumParams) {
5171  if (Args.size() < MinArgs) {
5172  TypoCorrection TC;
5173  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5174  unsigned diag_id =
5175  MinArgs == NumParams && !Proto->isVariadic()
5176  ? diag::err_typecheck_call_too_few_args_suggest
5177  : diag::err_typecheck_call_too_few_args_at_least_suggest;
5178  diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5179  << static_cast<unsigned>(Args.size())
5180  << TC.getCorrectionRange());
5181  } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5182  Diag(RParenLoc,
5183  MinArgs == NumParams && !Proto->isVariadic()
5184  ? diag::err_typecheck_call_too_few_args_one
5185  : diag::err_typecheck_call_too_few_args_at_least_one)
5186  << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5187  else
5188  Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5189  ? diag::err_typecheck_call_too_few_args
5190  : diag::err_typecheck_call_too_few_args_at_least)
5191  << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5192  << Fn->getSourceRange();
5193 
5194  // Emit the location of the prototype.
5195  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5196  Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5197 
5198  return true;
5199  }
5200  // We reserve space for the default arguments when we create
5201  // the call expression, before calling ConvertArgumentsForCall.
5202  assert((Call->getNumArgs() == NumParams) &&
5203  "We should have reserved space for the default arguments before!");
5204  }
5205 
5206  // If too many are passed and not variadic, error on the extras and drop
5207  // them.
5208  if (Args.size() > NumParams) {
5209  if (!Proto->isVariadic()) {
5210  TypoCorrection TC;
5211  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5212  unsigned diag_id =
5213  MinArgs == NumParams && !Proto->isVariadic()
5214  ? diag::err_typecheck_call_too_many_args_suggest
5215  : diag::err_typecheck_call_too_many_args_at_most_suggest;
5216  diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5217  << static_cast<unsigned>(Args.size())
5218  << TC.getCorrectionRange());
5219  } else if (NumParams == 1 && FDecl &&
5220  FDecl->getParamDecl(0)->getDeclName())
5221  Diag(Args[NumParams]->getBeginLoc(),
5222  MinArgs == NumParams
5223  ? diag::err_typecheck_call_too_many_args_one
5224  : diag::err_typecheck_call_too_many_args_at_most_one)
5225  << FnKind << FDecl->getParamDecl(0)
5226  << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5227  << SourceRange(Args[NumParams]->getBeginLoc(),
5228  Args.back()->getEndLoc());
5229  else
5230  Diag(Args[NumParams]->getBeginLoc(),
5231  MinArgs == NumParams
5232  ? diag::err_typecheck_call_too_many_args
5233  : diag::err_typecheck_call_too_many_args_at_most)
5234  << FnKind << NumParams << static_cast<unsigned>(Args.size())
5235  << Fn->getSourceRange()
5236  << SourceRange(Args[NumParams]->getBeginLoc(),
5237  Args.back()->getEndLoc());
5238 
5239  // Emit the location of the prototype.
5240  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5241  Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5242 
5243  // This deletes the extra arguments.
5244  Call->shrinkNumArgs(NumParams);
5245  return true;
5246  }
5247  }
5248  SmallVector<Expr *, 8> AllArgs;
5249  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5250 
5251  Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5252  AllArgs, CallType);
5253  if (Invalid)
5254  return true;
5255  unsigned TotalNumArgs = AllArgs.size();
5256  for (unsigned i = 0; i < TotalNumArgs; ++i)
5257  Call->setArg(i, AllArgs[i]);
5258 
5259  return false;
5260 }
5261 
5263  const FunctionProtoType *Proto,
5264  unsigned FirstParam, ArrayRef<Expr *> Args,
5265  SmallVectorImpl<Expr *> &AllArgs,
5266  VariadicCallType CallType, bool AllowExplicit,
5267  bool IsListInitialization) {
5268  unsigned NumParams = Proto->getNumParams();
5269  bool Invalid = false;
5270  size_t ArgIx = 0;
5271  // Continue to check argument types (even if we have too few/many args).
5272  for (unsigned i = FirstParam; i < NumParams; i++) {
5273  QualType ProtoArgType = Proto->getParamType(i);
5274 
5275  Expr *Arg;
5276  ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5277  if (ArgIx < Args.size()) {
5278  Arg = Args[ArgIx++];
5279 
5280  if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5281  diag::err_call_incomplete_argument, Arg))
5282  return true;
5283 
5284  // Strip the unbridged-cast placeholder expression off, if applicable.
5285  bool CFAudited = false;
5286  if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5287  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5288  (!Param || !Param->hasAttr<CFConsumedAttr>()))
5289  Arg = stripARCUnbridgedCast(Arg);
5290  else if (getLangOpts().ObjCAutoRefCount &&
5291  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5292  (!Param || !Param->hasAttr<CFConsumedAttr>()))
5293  CFAudited = true;
5294 
5295  if (Proto->getExtParameterInfo(i).isNoEscape())
5296  if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5297  BE->getBlockDecl()->setDoesNotEscape();
5298 
5299  InitializedEntity Entity =
5300  Param ? InitializedEntity::InitializeParameter(Context, Param,
5301  ProtoArgType)
5303  Context, ProtoArgType, Proto->isParamConsumed(i));
5304 
5305  // Remember that parameter belongs to a CF audited API.
5306  if (CFAudited)
5307  Entity.setParameterCFAudited();
5308 
5309  ExprResult ArgE = PerformCopyInitialization(
5310  Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5311  if (ArgE.isInvalid())
5312  return true;
5313 
5314  Arg = ArgE.getAs<Expr>();
5315  } else {
5316  assert(Param && "can't use default arguments without a known callee");
5317 
5318  ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5319  if (ArgExpr.isInvalid())
5320  return true;
5321 
5322  Arg = ArgExpr.getAs<Expr>();
5323  }
5324 
5325  // Check for array bounds violations for each argument to the call. This
5326  // check only triggers warnings when the argument isn't a more complex Expr
5327  // with its own checking, such as a BinaryOperator.
5328  CheckArrayAccess(Arg);
5329 
5330  // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5331  CheckStaticArrayArgument(CallLoc, Param, Arg);
5332 
5333  AllArgs.push_back(Arg);
5334  }
5335 
5336  // If this is a variadic call, handle args passed through "...".
5337  if (CallType != VariadicDoesNotApply) {
5338  // Assume that extern "C" functions with variadic arguments that
5339  // return __unknown_anytype aren't *really* variadic.
5340  if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5341  FDecl->isExternC()) {
5342  for (Expr *A : Args.slice(ArgIx)) {
5343  QualType paramType; // ignored
5344  ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5345  Invalid |= arg.isInvalid();
5346  AllArgs.push_back(arg.get());
5347  }
5348 
5349  // Otherwise do argument promotion, (C99 6.5.2.2p7).
5350  } else {
5351  for (Expr *A : Args.slice(ArgIx)) {
5352  ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5353  Invalid |= Arg.isInvalid();
5354  // Copy blocks to the heap.
5355  if (A->getType()->isBlockPointerType())
5356  maybeExtendBlockObject(Arg);
5357  AllArgs.push_back(Arg.get());
5358  }
5359  }
5360 
5361  // Check for array bounds violations.
5362  for (Expr *A : Args.slice(ArgIx))
5363  CheckArrayAccess(A);
5364  }
5365  return Invalid;
5366 }
5367 
5369  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5370  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5371  TL = DTL.getOriginalLoc();
5372  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5373  S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5374  << ATL.getLocalSourceRange();
5375 }
5376 
5377 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5378 /// array parameter, check that it is non-null, and that if it is formed by
5379 /// array-to-pointer decay, the underlying array is sufficiently large.
5380 ///
5381 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5382 /// array type derivation, then for each call to the function, the value of the
5383 /// corresponding actual argument shall provide access to the first element of
5384 /// an array with at least as many elements as specified by the size expression.
5385 void
5387  ParmVarDecl *Param,
5388  const Expr *ArgExpr) {
5389  // Static array parameters are not supported in C++.
5390  if (!Param || getLangOpts().CPlusPlus)
5391  return;
5392 
5393  QualType OrigTy = Param->getOriginalType();
5394 
5395  const ArrayType *AT = Context.getAsArrayType(OrigTy);
5396  if (!AT || AT->getSizeModifier() != ArrayType::Static)
5397  return;
5398 
5399  if (ArgExpr->isNullPointerConstant(Context,
5401  Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5402  DiagnoseCalleeStaticArrayParam(*this, Param);
5403  return;
5404  }
5405 
5406  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5407  if (!CAT)
5408  return;
5409 
5410  const ConstantArrayType *ArgCAT =
5411  Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5412  if (!ArgCAT)
5413  return;
5414 
5415  if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5416  ArgCAT->getElementType())) {
5417  if (ArgCAT->getSize().ult(CAT->getSize())) {
5418  Diag(CallLoc, diag::warn_static_array_too_small)
5419  << ArgExpr->getSourceRange()
5420  << (unsigned)ArgCAT->getSize().getZExtValue()
5421  << (unsigned)CAT->getSize().getZExtValue() << 0;
5422  DiagnoseCalleeStaticArrayParam(*this, Param);
5423  }
5424  return;
5425  }
5426 
5427  Optional<CharUnits> ArgSize =
5428  getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5429  Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5430  if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5431  Diag(CallLoc, diag::warn_static_array_too_small)
5432  << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5433  << (unsigned)ParmSize->getQuantity() << 1;
5434  DiagnoseCalleeStaticArrayParam(*this, Param);
5435  }
5436 }
5437 
5438 /// Given a function expression of unknown-any type, try to rebuild it
5439 /// to have a function type.
5441 
5442 /// Is the given type a placeholder that we need to lower out
5443 /// immediately during argument processing?
5445  // Placeholders are never sugared.
5446  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5447  if (!placeholder) return false;
5448 
5449  switch (placeholder->getKind()) {
5450  // Ignore all the non-placeholder types.
5451 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5452  case BuiltinType::Id:
5453 #include "clang/Basic/OpenCLImageTypes.def"
5454 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5455  case BuiltinType::Id:
5456 #include "clang/Basic/OpenCLExtensionTypes.def"
5457  // In practice we'll never use this, since all SVE types are sugared
5458  // via TypedefTypes rather than exposed directly as BuiltinTypes.
5459 #define SVE_TYPE(Name, Id, SingletonId) \
5460  case BuiltinType::Id:
5461 #include "clang/Basic/AArch64SVEACLETypes.def"
5462 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5463 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5464 #include "clang/AST/BuiltinTypes.def"
5465  return false;
5466 
5467  // We cannot lower out overload sets; they might validly be resolved
5468  // by the call machinery.
5469  case BuiltinType::Overload:
5470  return false;
5471 
5472  // Unbridged casts in ARC can be handled in some call positions and
5473  // should be left in place.
5474  case BuiltinType::ARCUnbridgedCast:
5475  return false;
5476 
5477  // Pseudo-objects should be converted as soon as possible.
5478  case BuiltinType::PseudoObject:
5479  return true;
5480 
5481  // The debugger mode could theoretically but currently does not try
5482  // to resolve unknown-typed arguments based on known parameter types.
5483  case BuiltinType::UnknownAny:
5484  return true;
5485 
5486  // These are always invalid as call arguments and should be reported.
5487  case BuiltinType::BoundMember:
5488  case BuiltinType::BuiltinFn:
5489  case BuiltinType::OMPArraySection:
5490  return true;
5491 
5492  }
5493  llvm_unreachable("bad builtin type kind");
5494 }
5495 
5496 /// Check an argument list for placeholders that we won't try to
5497 /// handle later.
5499  // Apply this processing to all the arguments at once instead of
5500  // dying at the first failure.
5501  bool hasInvalid = false;
5502  for (size_t i = 0, e = args.size(); i != e; i++) {
5503  if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5504  ExprResult result = S.CheckPlaceholderExpr(args[i]);
5505  if (result.isInvalid()) hasInvalid = true;
5506  else args[i] = result.get();
5507  } else if (hasInvalid) {
5508  (void)S.CorrectDelayedTyposInExpr(args[i]);
5509  }
5510  }
5511  return hasInvalid;
5512 }
5513 
5514 /// If a builtin function has a pointer argument with no explicit address
5515 /// space, then it should be able to accept a pointer to any address
5516 /// space as input. In order to do this, we need to replace the
5517 /// standard builtin declaration with one that uses the same address space
5518 /// as the call.
5519 ///
5520 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5521 /// it does not contain any pointer arguments without
5522 /// an address space qualifer. Otherwise the rewritten
5523 /// FunctionDecl is returned.
5524 /// TODO: Handle pointer return types.
5526  FunctionDecl *FDecl,
5527  MultiExprArg ArgExprs) {
5528 
5529  QualType DeclType = FDecl->getType();
5530  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5531 
5532  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5533  ArgExprs.size() < FT->getNumParams())
5534  return nullptr;
5535 
5536  bool NeedsNewDecl = false;
5537  unsigned i = 0;
5538  SmallVector<QualType, 8> OverloadParams;
5539 
5540  for (QualType ParamType : FT->param_types()) {
5541 
5542  // Convert array arguments to pointer to simplify type lookup.
5543  ExprResult ArgRes =
5544  Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5545  if (ArgRes.isInvalid())
5546  return nullptr;
5547  Expr *Arg = ArgRes.get();
5548  QualType ArgType = Arg->getType();
5549  if (!ParamType->isPointerType() ||
5550  ParamType.hasAddressSpace() ||
5551  !ArgType->isPointerType() ||
5552  !ArgType->getPointeeType().hasAddressSpace()) {
5553  OverloadParams.push_back(ParamType);
5554  continue;
5555  }
5556 
5557  QualType PointeeType = ParamType->getPointeeType();
5558  if (PointeeType.hasAddressSpace())
5559  continue;
5560 
5561  NeedsNewDecl = true;
5562  LangAS AS = ArgType->getPointeeType().getAddressSpace();
5563 
5564  PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5565  OverloadParams.push_back(Context.getPointerType(PointeeType));
5566  }
5567 
5568  if (!NeedsNewDecl)
5569  return nullptr;
5570 
5572  EPI.Variadic = FT->isVariadic();
5573  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5574  OverloadParams, EPI);
5575  DeclContext *Parent = FDecl->getParent();
5576  FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5577  FDecl->getLocation(),
5578  FDecl->getLocation(),
5579  FDecl->getIdentifier(),
5580  OverloadTy,
5581  /*TInfo=*/nullptr,
5582  SC_Extern, false,
5583  /*hasPrototype=*/true);
5585  FT = cast<FunctionProtoType>(OverloadTy);
5586  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5587  QualType ParamType = FT->getParamType(i);
5588  ParmVarDecl *Parm =
5589  ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5590  SourceLocation(), nullptr, ParamType,
5591  /*TInfo=*/nullptr, SC_None, nullptr);
5592  Parm->setScopeInfo(0, i);
5593  Params.push_back(Parm);
5594  }
5595  OverloadDecl->setParams(Params);
5596  return OverloadDecl;
5597 }
5598 
5599 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5600  FunctionDecl *Callee,
5601  MultiExprArg ArgExprs) {
5602  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5603  // similar attributes) really don't like it when functions are called with an
5604  // invalid number of args.
5605  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5606  /*PartialOverloading=*/false) &&
5607  !Callee->isVariadic())
5608  return;
5609  if (Callee->getMinRequiredArguments() > ArgExprs.size())
5610  return;
5611 
5612  if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5613  S.Diag(Fn->getBeginLoc(),
5614  isa<CXXMethodDecl>(Callee)
5615  ? diag::err_ovl_no_viable_member_function_in_call
5616  : diag::err_ovl_no_viable_function_in_call)
5617  << Callee << Callee->getSourceRange();
5618  S.Diag(Callee->getLocation(),
5619  diag::note_ovl_candidate_disabled_by_function_cond_attr)
5620  << Attr->getCond()->getSourceRange() << Attr->getMessage();
5621  return;
5622  }
5623 }
5624 
5626  const UnresolvedMemberExpr *const UME, Sema &S) {
5627 
5628  const auto GetFunctionLevelDCIfCXXClass =
5629  [](Sema &S) -> const CXXRecordDecl * {
5630  const DeclContext *const DC = S.getFunctionLevelDeclContext();
5631  if (!DC || !DC->getParent())
5632  return nullptr;
5633 
5634  // If the call to some member function was made from within a member
5635  // function body 'M' return return 'M's parent.
5636  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5637  return MD->getParent()->getCanonicalDecl();
5638  // else the call was made from within a default member initializer of a
5639  // class, so return the class.
5640  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5641  return RD->getCanonicalDecl();
5642  return nullptr;
5643  };
5644  // If our DeclContext is neither a member function nor a class (in the
5645  // case of a lambda in a default member initializer), we can't have an
5646  // enclosing 'this'.
5647 
5648  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5649  if (!CurParentClass)
5650  return false;
5651 
5652  // The naming class for implicit member functions call is the class in which
5653  // name lookup starts.
5654  const CXXRecordDecl *const NamingClass =
5655  UME->getNamingClass()->getCanonicalDecl();
5656  assert(NamingClass && "Must have naming class even for implicit access");
5657 
5658  // If the unresolved member functions were found in a 'naming class' that is
5659  // related (either the same or derived from) to the class that contains the
5660  // member function that itself contained the implicit member access.
5661 
5662  return CurParentClass == NamingClass ||
5663  CurParentClass->isDerivedFrom(NamingClass);
5664 }
5665 
5666 static void
5668  Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5669 
5670  if (!UME)
5671  return;
5672 
5673  LambdaScopeInfo *const CurLSI = S.getCurLambda();
5674  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5675  // already been captured, or if this is an implicit member function call (if
5676  // it isn't, an attempt to capture 'this' should already have been made).
5677  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5678  !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5679  return;
5680 
5681  // Check if the naming class in which the unresolved members were found is
5682  // related (same as or is a base of) to the enclosing class.
5683 
5685  return;
5686 
5687 
5688  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5689  // If the enclosing function is not dependent, then this lambda is
5690  // capture ready, so if we can capture this, do so.
5691  if (!EnclosingFunctionCtx->isDependentContext()) {
5692  // If the current lambda and all enclosing lambdas can capture 'this' -
5693  // then go ahead and capture 'this' (since our unresolved overload set
5694  // contains at least one non-static member function).
5695  if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5696  S.CheckCXXThisCapture(CallLoc);
5697  } else if (S.CurContext->isDependentContext()) {
5698  // ... since this is an implicit member reference, that might potentially
5699  // involve a 'this' capture, mark 'this' for potential capture in
5700  // enclosing lambdas.
5701  if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5702  CurLSI->addPotentialThisCapture(CallLoc);
5703  }
5704 }
5705 
5707  MultiExprArg ArgExprs, SourceLocation RParenLoc,
5708  Expr *ExecConfig) {
5709  ExprResult Call =
5710  BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5711  if (Call.isInvalid())
5712  return Call;
5713 
5714  // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5715  // language modes.
5716  if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5717  if (ULE->hasExplicitTemplateArgs() &&
5718  ULE->decls_begin() == ULE->decls_end()) {
5719  Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5720  ? diag::warn_cxx17_compat_adl_only_template_id
5721  : diag::ext_adl_only_template_id)
5722  << ULE->getName();
5723  }
5724  }
5725 
5726  return Call;
5727 }
5728 
5729 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5730 /// This provides the location of the left/right parens and a list of comma
5731 /// locations.
5733  MultiExprArg ArgExprs, SourceLocation RParenLoc,
5734  Expr *ExecConfig, bool IsExecConfig) {
5735  // Since this might be a postfix expression, get rid of ParenListExprs.
5736  ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5737  if (Result.isInvalid()) return ExprError();
5738  Fn = Result.get();
5739 
5740  if (checkArgsForPlaceholders(*this, ArgExprs))
5741  return ExprError();
5742 
5743  if (getLangOpts().CPlusPlus) {
5744  // If this is a pseudo-destructor expression, build the call immediately.
5745  if (isa<CXXPseudoDestructorExpr>(Fn)) {
5746  if (!ArgExprs.empty()) {
5747  // Pseudo-destructor calls should not have any arguments.
5748  Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5750  SourceRange(ArgExprs.front()->getBeginLoc(),
5751  ArgExprs.back()->getEndLoc()));
5752  }
5753 
5754  return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5755  VK_RValue, RParenLoc);
5756  }
5757  if (Fn->getType() == Context.PseudoObjectTy) {
5758  ExprResult result = CheckPlaceholderExpr(Fn);
5759  if (result.isInvalid()) return ExprError();
5760  Fn = result.get();
5761  }
5762 
5763  // Determine whether this is a dependent call inside a C++ template,
5764  // in which case we won't do any semantic analysis now.
5765  if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5766  if (ExecConfig) {
5768  Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5769  Context.DependentTy, VK_RValue, RParenLoc);
5770  } else {
5771 
5773  *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5774  Fn->getBeginLoc());
5775 
5776  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5777  VK_RValue, RParenLoc);
5778  }
5779  }
5780 
5781  // Determine whether this is a call to an object (C++ [over.call.object]).
5782  if (Fn->getType()->isRecordType())
5783  return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5784  RParenLoc);
5785 
5786  if (Fn->getType() == Context.UnknownAnyTy) {
5787  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5788  if (result.isInvalid()) return ExprError();
5789  Fn = result.get();
5790  }
5791 
5792  if (Fn->getType() == Context.BoundMemberTy) {
5793  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5794  RParenLoc);
5795  }
5796  }
5797 
5798  // Check for overloaded calls. This can happen even in C due to extensions.
5799  if (Fn->getType() == Context.OverloadTy) {
5801 
5802  // We aren't supposed to apply this logic if there's an '&' involved.
5803  if (!find.HasFormOfMemberPointer) {
5804  if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5805  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5806  VK_RValue, RParenLoc);
5807  OverloadExpr *ovl = find.Expression;
5808  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5809  return BuildOverloadedCallExpr(
5810  Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5811  /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5812  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5813  RParenLoc);
5814  }
5815  }
5816 
5817  // If we're directly calling a function, get the appropriate declaration.
5818  if (Fn->getType() == Context.UnknownAnyTy) {
5819  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5820  if (result.isInvalid()) return ExprError();
5821  Fn = result.get();
5822  }
5823 
5824  Expr *NakedFn = Fn->IgnoreParens();
5825 
5826  bool CallingNDeclIndirectly = false;
5827  NamedDecl *NDecl = nullptr;
5828  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5829  if (UnOp->getOpcode() == UO_AddrOf) {
5830  CallingNDeclIndirectly = true;
5831  NakedFn = UnOp->getSubExpr()->IgnoreParens();
5832  }
5833  }
5834 
5835  if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5836  NDecl = DRE->getDecl();
5837 
5838  FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5839  if (FDecl && FDecl->getBuiltinID()) {
5840  // Rewrite the function decl for this builtin by replacing parameters
5841  // with no explicit address space with the address space of the arguments
5842  // in ArgExprs.
5843  if ((FDecl =
5844  rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5845  NDecl = FDecl;
5846  Fn = DeclRefExpr::Create(
5847  Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5848  SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5849  nullptr, DRE->isNonOdrUse());
5850  }
5851  }
5852  } else if (isa<MemberExpr>(NakedFn))
5853  NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5854 
5855  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5856  if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5857  FD, /*Complain=*/true, Fn->getBeginLoc()))
5858  return ExprError();
5859 
5860  if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5861  return ExprError();
5862 
5863  checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5864  }
5865 
5866  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5867  ExecConfig, IsExecConfig);
5868 }
5869 
5870 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5871 ///
5872 /// __builtin_astype( value, dst type )
5873 ///
5875  SourceLocation BuiltinLoc,
5876  SourceLocation RParenLoc) {
5877  ExprValueKind VK = VK_RValue;
5879  QualType DstTy = GetTypeFromParser(ParsedDestTy);
5880  QualType SrcTy = E->getType();
5881  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5882  return ExprError(Diag(BuiltinLoc,
5883  diag::err_invalid_astype_of_different_size)
5884  << DstTy
5885  << SrcTy
5886  << E->getSourceRange());
5887  return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5888 }
5889 
5890 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5891 /// provided arguments.
5892 ///
5893 /// __builtin_convertvector( value, dst type )
5894 ///
5896  SourceLocation BuiltinLoc,
5897  SourceLocation RParenLoc) {
5898  TypeSourceInfo *TInfo;
5899  GetTypeFromParser(ParsedDestTy, &TInfo);
5900  return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5901 }
5902 
5903 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5904 /// i.e. an expression not of \p OverloadTy. The expression should
5905 /// unary-convert to an expression of function-pointer or
5906 /// block-pointer type.
5907 ///
5908 /// \param NDecl the declaration being called, if available
5910  SourceLocation LParenLoc,
5911  ArrayRef<Expr *> Args,
5912  SourceLocation RParenLoc, Expr *Config,
5913  bool IsExecConfig, ADLCallKind UsesADL) {
5914  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5915  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5916 
5917  // Functions with 'interrupt' attribute cannot be called directly.
5918  if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5919  Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5920  return ExprError();
5921  }
5922 
5923  // Interrupt handlers don't save off the VFP regs automatically on ARM,
5924  // so there's some risk when calling out to non-interrupt handler functions
5925  // that the callee might not preserve them. This is easy to diagnose here,
5926  // but can be very challenging to debug.
5927  if (auto *Caller = getCurFunctionDecl())
5928  if (Caller->hasAttr<ARMInterruptAttr>()) {
5929  bool VFP = Context.getTargetInfo().hasFeature("vfp");
5930  if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5931  Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5932  }
5933 
5934  // Promote the function operand.
5935  // We special-case function promotion here because we only allow promoting
5936  // builtin functions to function pointers in the callee of a call.
5937  ExprResult Result;
5938  QualType ResultTy;
5939  if (BuiltinID &&
5940  Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5941  // Extract the return type from the (builtin) function pointer type.
5942  // FIXME Several builtins still have setType in
5943  // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5944  // Builtins.def to ensure they are correct before removing setType calls.
5945  QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5946  Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5947  ResultTy = FDecl->getCallResultType();
5948  } else {
5949  Result = CallExprUnaryConversions(Fn);
5950  ResultTy = Context.BoolTy;
5951  }
5952  if (Result.isInvalid())
5953  return ExprError();
5954  Fn = Result.get();
5955 
5956  // Check for a valid function type, but only if it is not a builtin which
5957  // requires custom type checking. These will be handled by
5958  // CheckBuiltinFunctionCall below just after creation of the call expression.
5959  const FunctionType *FuncT = nullptr;
5960  if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5961  retry:
5962  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5963  // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5964  // have type pointer to function".
5965  FuncT = PT->getPointeeType()->getAs<FunctionType>();
5966  if (!FuncT)
5967  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5968  << Fn->getType() << Fn->getSourceRange());
5969  } else if (const BlockPointerType *BPT =
5970  Fn->getType()->getAs<BlockPointerType>()) {
5971  FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5972  } else {
5973  // Handle calls to expressions of unknown-any type.
5974  if (Fn->getType() == Context.UnknownAnyTy) {
5975  ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5976  if (rewrite.isInvalid())
5977  return ExprError();
5978  Fn = rewrite.get();
5979  goto retry;
5980  }
5981 
5982  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5983  << Fn->getType() << Fn->getSourceRange());
5984  }
5985  }
5986 
5987  // Get the number of parameters in the function prototype, if any.
5988  // We will allocate space for max(Args.size(), NumParams) arguments
5989  // in the call expression.
5990  const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5991  unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5992 
5993  CallExpr *TheCall;
5994  if (Config) {
5995  assert(UsesADL == ADLCallKind::NotADL &&
5996  "CUDAKernelCallExpr should not use ADL");
5997  TheCall =
5998  CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5999  ResultTy, VK_RValue, RParenLoc, NumParams);
6000  } else {
6001  TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6002  RParenLoc, NumParams, UsesADL);
6003  }
6004 
6005  if (!getLangOpts().CPlusPlus) {
6006  // Forget about the nulled arguments since typo correction
6007  // do not handle them well.
6008  TheCall->shrinkNumArgs(Args.size());
6009  // C cannot always handle TypoExpr nodes in builtin calls and direct
6010  // function calls as their argument checking don't necessarily handle
6011  // dependent types properly, so make sure any TypoExprs have been
6012  // dealt with.
6013  ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6014  if (!Result.isUsable()) return ExprError();
6015  CallExpr *TheOldCall = TheCall;
6016  TheCall = dyn_cast<CallExpr>(Result.get());
6017  bool CorrectedTypos = TheCall != TheOldCall;
6018  if (!TheCall) return Result;
6019  Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6020 
6021  // A new call expression node was created if some typos were corrected.
6022  // However it may not have been constructed with enough storage. In this
6023  // case, rebuild the node with enough storage. The waste of space is
6024  // immaterial since this only happens when some typos were corrected.
6025  if (CorrectedTypos && Args.size() < NumParams) {
6026  if (Config)
6027  TheCall = CUDAKernelCallExpr::Create(
6028  Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6029  RParenLoc, NumParams);
6030  else
6031  TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6032  RParenLoc, NumParams, UsesADL);
6033  }
6034  // We can now handle the nulled arguments for the default arguments.
6035  TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6036  }
6037 
6038  // Bail out early if calling a builtin with custom type checking.
6039  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6040  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6041 
6042  if (getLangOpts().CUDA) {
6043  if (Config) {
6044  // CUDA: Kernel calls must be to global functions
6045  if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6046  return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6047  << FDecl << Fn->getSourceRange());
6048 
6049  // CUDA: Kernel function must have 'void' return type
6050  if (!FuncT->getReturnType()->isVoidType() &&
6051  !FuncT->getReturnType()->getAs<AutoType>() &&
6053  return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6054  << Fn->getType() << Fn->getSourceRange());
6055  } else {
6056  // CUDA: Calls to global functions must be configured
6057  if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6058  return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6059  << FDecl << Fn->getSourceRange());
6060  }
6061  }
6062 
6063  // Check for a valid return type
6064  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6065  FDecl))
6066  return ExprError();
6067 
6068  // We know the result type of the call, set it.
6069  TheCall->setType(FuncT->getCallResultType(Context));
6071 
6072  if (Proto) {
6073  if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6074  IsExecConfig))
6075  return ExprError();
6076  } else {
6077  assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6078 
6079  if (FDecl) {
6080  // Check if we have too few/too many template arguments, based
6081  // on our knowledge of the function definition.
6082  const FunctionDecl *Def = nullptr;
6083  if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6084  Proto = Def->getType()->getAs<FunctionProtoType>();
6085  if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6086  Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6087  << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6088  }
6089 
6090  // If the function we're calling isn't a function prototype, but we have
6091  // a function prototype from a prior declaratiom, use that prototype.
6092  if (!FDecl->hasPrototype())
6093  Proto = FDecl->getType()->getAs<FunctionProtoType>();
6094  }
6095 
6096  // Promote the arguments (C99 6.5.2.2p6).
6097  for (unsigned i = 0, e = Args.size(); i != e; i++) {
6098  Expr *Arg = Args[i];
6099 
6100  if (Proto && i < Proto->getNumParams()) {
6102  Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6103  ExprResult ArgE =
6104  PerformCopyInitialization(Entity, SourceLocation(), Arg);
6105  if (ArgE.isInvalid())
6106  return true;
6107 
6108  Arg = ArgE.getAs<Expr>();
6109 
6110  } else {
6111  ExprResult ArgE = DefaultArgumentPromotion(Arg);
6112 
6113  if (ArgE.isInvalid())
6114  return true;
6115 
6116  Arg = ArgE.getAs<Expr>();
6117  }
6118 
6119  if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6120  diag::err_call_incomplete_argument, Arg))
6121  return ExprError();
6122 
6123  TheCall->setArg(i, Arg);
6124  }
6125  }
6126 
6127  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6128  if (!Method->isStatic())
6129  return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6130  << Fn->getSourceRange());
6131 
6132  // Check for sentinels
6133  if (NDecl)
6134  DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6135 
6136  // Do special checking on direct calls to functions.
6137  if (FDecl) {
6138  if (CheckFunctionCall(FDecl, TheCall, Proto))
6139  return ExprError();
6140 
6141  checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6142 
6143  if (BuiltinID)
6144  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6145  } else if (NDecl) {
6146  if (CheckPointerCall(NDecl, TheCall, Proto))
6147  return ExprError();
6148  } else {
6149  if (CheckOtherCall(TheCall, Proto))
6150  return ExprError();
6151  }
6152 
6153  return MaybeBindToTemporary(TheCall);
6154 }
6155 
6156 ExprResult
6158  SourceLocation RParenLoc, Expr *InitExpr) {
6159  assert(Ty && "ActOnCompoundLiteral(): missing type");
6160  assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6161 
6162  TypeSourceInfo *TInfo;
6163  QualType literalType = GetTypeFromParser(Ty, &TInfo);
6164  if (!TInfo)
6165  TInfo = Context.getTrivialTypeSourceInfo(literalType);
6166 
6167  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6168 }
6169 
6170 ExprResult
6172  SourceLocation RParenLoc, Expr *LiteralExpr) {
6173  QualType literalType = TInfo->getType();
6174 
6175  if (literalType->isArrayType()) {
6176  if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6177  diag::err_illegal_decl_array_incomplete_type,
6178  SourceRange(LParenLoc,
6179  LiteralExpr->getSourceRange().getEnd())))
6180  return ExprError();
6181  if (literalType->isVariableArrayType())
6182  return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6183  << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6184  } else if (!literalType->isDependentType() &&
6185  RequireCompleteType(LParenLoc, literalType,
6186  diag::err_typecheck_decl_incomplete_type,
6187  SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6188  return ExprError();
6189 
6190  InitializedEntity Entity
6194  SourceRange(LParenLoc, RParenLoc),
6195  /*InitList=*/true);
6196  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6197  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6198  &literalType);
6199  if (Result.isInvalid())
6200  return ExprError();
6201  LiteralExpr = Result.get();
6202 
6203  bool isFileScope = !CurContext->isFunctionOrMethod();
6204 
6205  // In C, compound literals are l-values for some reason.
6206  // For GCC compatibility, in C++, file-scope array compound literals with
6207  // constant initializers are also l-values, and compound literals are
6208  // otherwise prvalues.
6209  //
6210  // (GCC also treats C++ list-initialized file-scope array prvalues with
6211  // constant initializers as l-values, but that's non-conforming, so we don't
6212  // follow it there.)
6213  //
6214  // FIXME: It would be better to handle the lvalue cases as materializing and
6215  // lifetime-extending a temporary object, but our materialized temporaries
6216  // representation only supports lifetime extension from a variable, not "out
6217  // of thin air".
6218  // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6219  // is bound to the result of applying array-to-pointer decay to the compound
6220  // literal.
6221  // FIXME: GCC supports compound literals of reference type, which should
6222  // obviously have a value kind derived from the kind of reference involved.
6223  ExprValueKind VK =
6224  (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6225  ? VK_RValue
6226  : VK_LValue;
6227 
6228  if (isFileScope)
6229  if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6230  for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6231  Expr *Init = ILE->getInit(i);
6232  ILE->setInit(i, ConstantExpr::Create(Context, Init));
6233  }
6234 
6235  auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6236  VK, LiteralExpr, isFileScope);
6237  if (isFileScope) {
6238  if (!LiteralExpr->isTypeDependent() &&
6239  !LiteralExpr->isValueDependent() &&
6240  !literalType->isDependentType()) // C99 6.5.2.5p3
6241  if (CheckForConstantInitializer(LiteralExpr, literalType))
6242  return ExprError();
6243  } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6244  literalType.getAddressSpace() != LangAS::Default) {
6245  // Embedded-C extensions to C99 6.5.2.5:
6246  // "If the compound literal occurs inside the body of a function, the
6247  // type name shall not be qualified by an address-space qualifier."
6248  Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6249  << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6250  return ExprError();
6251  }
6252 
6253  // Compound literals that have automatic storage duration are destroyed at
6254  // the end of the scope. Emit diagnostics if it is or contains a C union type
6255  // that is non-trivial to destruct.
6256  if (!isFileScope)
6258  checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6259  NTCUC_CompoundLiteral, NTCUK_Destruct);
6260 
6263  checkNonTrivialCUnionInInitializer(E->getInitializer(),
6264  E->getInitializer()->getExprLoc());
6265 
6266  return MaybeBindToTemporary(E);
6267 }
6268 
6269 ExprResult
6271  SourceLocation RBraceLoc) {
6272  // Only produce each kind of designated initialization diagnostic once.
6273  SourceLocation FirstDesignator;
6274  bool DiagnosedArrayDesignator = false;
6275  bool DiagnosedNestedDesignator = false;
6276  bool DiagnosedMixedDesignator = false;
6277 
6278  // Check that any designated initializers are syntactically valid in the
6279  // current language mode.
6280  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6281  if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6282  if (FirstDesignator.isInvalid())
6283  FirstDesignator = DIE->getBeginLoc();
6284 
6285  if (!getLangOpts().CPlusPlus)
6286  break;
6287 
6288  if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6289  DiagnosedNestedDesignator = true;
6290  Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6291  << DIE->getDesignatorsSourceRange();
6292  }
6293 
6294  for (auto &Desig : DIE->designators()) {
6295  if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6296  DiagnosedArrayDesignator = true;
6297  Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6298  << Desig.getSourceRange();
6299  }
6300  }
6301 
6302  if (!DiagnosedMixedDesignator &&
6303  !isa<DesignatedInitExpr>(InitArgList[0])) {
6304  DiagnosedMixedDesignator = true;
6305  Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6306  << DIE->getSourceRange();
6307  Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6308  << InitArgList[0]->getSourceRange();
6309  }
6310  } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6311  isa<DesignatedInitExpr>(InitArgList[0])) {
6312  DiagnosedMixedDesignator = true;
6313  auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6314  Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6315  << DIE->getSourceRange();
6316  Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6317  << InitArgList[I]->getSourceRange();
6318  }
6319  }
6320 
6321  if (FirstDesignator.isValid()) {
6322  // Only diagnose designated initiaization as a C++20 extension if we didn't
6323  // already diagnose use of (non-C++20) C99 designator syntax.
6324  if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6325  !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6326  Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6327  ? diag::warn_cxx17_compat_designated_init
6328  : diag::ext_cxx_designated_init);
6329  } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6330  Diag(FirstDesignator, diag::ext_designated_init);
6331  }
6332  }
6333 
6334  return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6335 }
6336 
6337 ExprResult
6339  SourceLocation RBraceLoc) {
6340  // Semantic analysis for initializers is done by ActOnDeclarator() and
6341  // CheckInitializer() - it requires knowledge of the object being initialized.
6342 
6343  // Immediately handle non-overload placeholders. Overloads can be
6344  // resolved contextually, but everything else here can't.
6345  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6346  if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6347  ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6348 
6349  // Ignore failures; dropping the entire initializer list because
6350  // of one failure would be terrible for indexing/etc.
6351  if (result.isInvalid()) continue;
6352 
6353  InitArgList[I] = result.get();
6354  }
6355  }
6356 
6357  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6358  RBraceLoc);
6359  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6360  return E;
6361 }
6362 
6363 /// Do an explicit extend of the given block pointer if we're in ARC.
6365  assert(E.get()->getType()->isBlockPointerType());
6366  assert(E.get()->isRValue());
6367 
6368  // Only do this in an r-value context.
6369  if (!getLangOpts().ObjCAutoRefCount) return;
6370 
6371  E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6372  CK_ARCExtendBlockObject, E.get(),
6373  /*base path*/ nullptr, VK_RValue);
6374  Cleanup.setExprNeedsCleanups(true);
6375 }
6376 
6377 /// Prepare a conversion of the given expression to an ObjC object
6378 /// pointer type.
6380  QualType type = E.get()->getType();
6381  if (type->isObjCObjectPointerType()) {
6382  return CK_BitCast;
6383  } else if (type->isBlockPointerType()) {
6384  maybeExtendBlockObject(E);
6385  return CK_BlockPointerToObjCPointerCast;
6386  } else {
6387  assert(type->isPointerType());
6388  return CK_CPointerToObjCPointerCast;
6389  }
6390 }
6391 
6392 /// Prepares for a scalar cast, performing all the necessary stages
6393 /// except the final cast and returning the kind required.
6395  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6396  // Also, callers should have filtered out the invalid cases with
6397  // pointers. Everything else should be possible.
6398 
6399  QualType SrcTy = Src.get()->getType();
6400  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6401  return CK_NoOp;
6402 
6403  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6405  llvm_unreachable("member pointer type in C");
6406 
6407  case Type::STK_CPointer:
6410  switch (DestTy->getScalarTypeKind()) {
6411  case Type::STK_CPointer: {
6412  LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6413  LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6414  if (SrcAS != DestAS)
6415  return CK_AddressSpaceConversion;
6416  if (Context.hasCvrSimilarType(SrcTy, DestTy))
6417  return CK_NoOp;
6418  return CK_BitCast;
6419  }
6421  return (SrcKind == Type::STK_BlockPointer
6422  ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6424  if (SrcKind == Type::STK_ObjCObjectPointer)
6425  return CK_BitCast;
6426  if (SrcKind == Type::STK_CPointer)
6427  return CK_CPointerToObjCPointerCast;
6428  maybeExtendBlockObject(Src);
6429  return CK_BlockPointerToObjCPointerCast;
6430  case Type::STK_Bool:
6431  return CK_PointerToBoolean;
6432  case Type::STK_Integral:
6433  return CK_PointerToIntegral;
6434  case Type::STK_Floating:
6438  case Type::STK_FixedPoint:
6439  llvm_unreachable("illegal cast from pointer");
6440  }
6441  llvm_unreachable("Should have returned before this");
6442 
6443  case Type::STK_FixedPoint:
6444  switch (DestTy->getScalarTypeKind()) {
6445  case Type::STK_FixedPoint:
6446  return CK_FixedPointCast;
6447  case Type::STK_Bool:
6448  return CK_FixedPointToBoolean;
6449  case Type::STK_Integral:
6450  return CK_FixedPointToIntegral;
6451  case Type::STK_Floating:
6454  Diag(Src.get()->getExprLoc(),
6455  diag::err_unimplemented_conversion_with_fixed_point_type)
6456  << DestTy;
6457  return CK_IntegralCast;
6458  case Type::STK_CPointer:
6462  llvm_unreachable("illegal cast to pointer type");
6463  }
6464  llvm_unreachable("Should have returned before this");
6465 
6466  case Type::STK_Bool: // casting from bool is like casting from an integer
6467  case Type::STK_Integral:
6468  switch (DestTy->getScalarTypeKind()) {
6469  case Type::STK_CPointer:
6472  if (Src.get()->isNullPointerConstant(Context,
6474  return CK_NullToPointer;
6475  return CK_IntegralToPointer;
6476  case Type::STK_Bool:
6477  return CK_IntegralToBoolean;
6478  case Type::STK_Integral:
6479  return CK_IntegralCast;
6480  case Type::STK_Floating:
6481  return CK_IntegralToFloating;
6483  Src = ImpCastExprToType(Src.get(),
6484  DestTy->castAs<ComplexType>()->getElementType(),
6485  CK_IntegralCast);
6486  return CK_IntegralRealToComplex;
6488  Src = ImpCastExprToType(Src.get(),
6489  DestTy->castAs<ComplexType>()->getElementType(),
6490  CK_IntegralToFloating);
6491  return CK_FloatingRealToComplex;
6493  llvm_unreachable("member pointer type in C");
6494  case Type::STK_FixedPoint:
6495  return CK_IntegralToFixedPoint;
6496  }
6497  llvm_unreachable("Should have returned before this");
6498 
6499  case Type::STK_Floating:
6500  switch (DestTy->getScalarTypeKind()) {
6501  case Type::STK_Floating:
6502  return CK_FloatingCast;
6503  case Type::STK_Bool:
6504  return CK_FloatingToBoolean;
6505  case Type::STK_Integral:
6506  return CK_FloatingToIntegral;
6508  Src = ImpCastExprToType(Src.get(),
6509  DestTy->castAs<ComplexType>()->getElementType(),
6510  CK_FloatingCast);
6511  return CK_FloatingRealToComplex;
6513  Src = ImpCastExprToType(Src.get(),
6514  DestTy->castAs<ComplexType>()->getElementType(),
6515  CK_FloatingToIntegral);
6516  return CK_IntegralRealToComplex;
6517  case Type::STK_CPointer:
6520  llvm_unreachable("valid float->pointer cast?");
6522  llvm_unreachable("member pointer type in C");
6523  case Type::STK_FixedPoint:
6524  Diag(Src.get()->getExprLoc(),
6525  diag::err_unimplemented_conversion_with_fixed_point_type)
6526  << SrcTy;
6527  return CK_IntegralCast;
6528  }
6529  llvm_unreachable("Should have returned before this");
6530 
6532  switch (DestTy->getScalarTypeKind()) {
6534  return CK_FloatingComplexCast;
6536  return CK_FloatingComplexToIntegralComplex;
6537  case Type::STK_Floating: {
6538  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6539  if (Context.hasSameType(ET, DestTy))
6540  return CK_FloatingComplexToReal;
6541  Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6542  return CK_FloatingCast;
6543  }
6544  case Type::STK_Bool:
6545  return CK_FloatingComplexToBoolean;
6546  case Type::STK_Integral:
6547  Src = ImpCastExprToType(Src.get(),
6548  SrcTy->castAs<ComplexType>()->getElementType(),
6549  CK_FloatingComplexToReal);
6550  return CK_FloatingToIntegral;
6551  case Type::STK_CPointer:
6554  llvm_unreachable("valid complex float->pointer cast?");
6556  llvm_unreachable("member pointer type in C");
6557  case Type::STK_FixedPoint:
6558  Diag(Src.get()->getExprLoc(),
6559  diag::err_unimplemented_conversion_with_fixed_point_type)
6560  << SrcTy;
6561  return CK_IntegralCast;
6562  }
6563  llvm_unreachable("Should have returned before this");
6564 
6566  switch (DestTy->getScalarTypeKind()) {
6568  return CK_IntegralComplexToFloatingComplex;
6570  return CK_IntegralComplexCast;
6571  case Type::STK_Integral: {
6572  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6573  if (Context.hasSameType(ET, DestTy))
6574  return CK_IntegralComplexToReal;
6575  Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6576  return CK_IntegralCast;
6577  }
6578  case Type::STK_Bool:
6579  return CK_IntegralComplexToBoolean;
6580  case Type::STK_Floating:
6581  Src = ImpCastExprToType(Src.get(),
6582  SrcTy->castAs<ComplexType>()->getElementType(),
6583  CK_IntegralComplexToReal);
6584  return CK_IntegralToFloating;
6585  case Type::STK_CPointer:
6588  llvm_unreachable("valid complex int->pointer cast?");
6590  llvm_unreachable("member pointer type in C");
6591  case Type::STK_FixedPoint:
6592  Diag(Src.get()->getExprLoc(),
6593  diag::err_unimplemented_conversion_with_fixed_point_type)
6594  << SrcTy;
6595  return CK_IntegralCast;
6596  }
6597  llvm_unreachable("Should have returned before this");
6598  }
6599 
6600  llvm_unreachable("Unhandled scalar cast");
6601 }
6602 
6603 static bool breakDownVectorType(QualType type, uint64_t &len,
6604  QualType &eltType) {
6605  // Vectors are simple.
6606  if (const VectorType *vecType = type->getAs<VectorType>()) {
6607  len = vecType->getNumElements();
6608  eltType = vecType->getElementType();
6609  assert(eltType->isScalarType());
6610  return true;
6611  }
6612 
6613  // We allow lax conversion to and from non-vector types, but only if
6614  // they're real types (i.e. non-complex, non-pointer scalar types).
6615  if (!type->isRealType()) return false;
6616 
6617  len = 1;
6618  eltType = type;
6619  return true;
6620 }
6621 
6622 /// Are the two types lax-compatible vector types? That is, given
6623 /// that one of them is a vector, do they have equal storage sizes,
6624 /// where the storage size is the number of elements times the element
6625 /// size?
6626 ///
6627 /// This will also return false if either of the types is neither a
6628 /// vector nor a real type.
6630  assert(destTy->isVectorType() || srcTy->isVectorType());
6631 
6632  // Disallow lax conversions between scalars and ExtVectors (these
6633  // conversions are allowed for other vector types because common headers
6634  // depend on them). Most scalar OP ExtVector cases are handled by the
6635  // splat path anyway, which does what we want (convert, not bitcast).
6636  // What this rules out for ExtVectors is crazy things like char4*float.
6637  if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6638  if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6639 
6640  uint64_t srcLen, destLen;
6641  QualType srcEltTy, destEltTy;
6642  if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6643  if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6644 
6645  // ASTContext::getTypeSize will return the size rounded up to a
6646  // power of 2, so instead of using that, we need to use the raw
6647  // element size multiplied by the element count.
6648  uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6649  uint64_t destEltSize = Context.getTypeSize(destEltTy);
6650 
6651  return (srcLen * srcEltSize == destLen * destEltSize);
6652 }
6653 
6654 /// Is this a legal conversion between two types, one of which is
6655 /// known to be a vector type?
6657  assert(destTy->isVectorType() || srcTy->isVectorType());
6658 
6659  switch (Context.getLangOpts().getLaxVectorConversions()) {
6661  return false;
6662 
6664  if (!srcTy->isIntegralOrEnumerationType()) {
6665  auto *Vec = srcTy->getAs<VectorType>();
6666  if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6667  return false;
6668  }
6669  if (!destTy->isIntegralOrEnumerationType()) {
6670  auto *Vec = destTy->getAs<VectorType>();
6671  if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6672  return false;
6673  }
6674  // OK, integer (vector) -> integer (vector) bitcast.
6675  break;
6676 
6678  break;
6679  }
6680 
6681  return areLaxCompatibleVectorTypes(srcTy, destTy);
6682 }
6683 
6685  CastKind &Kind) {
6686  assert(VectorTy->isVectorType() && "Not a vector type!");
6687 
6688  if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6689  if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6690  return Diag(R.getBegin(),
6691  Ty->isVectorType() ?
6692  diag::err_invalid_conversion_between_vectors :
6693  diag::err_invalid_conversion_between_vector_and_integer)
6694  << VectorTy << Ty << R;
6695  } else
6696  return Diag(R.getBegin(),
6697  diag::err_invalid_conversion_between_vector_and_scalar)
6698  << VectorTy << Ty << R;
6699 
6700  Kind = CK_BitCast;
6701  return false;
6702 }
6703 
6705  QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6706 
6707  if (DestElemTy == SplattedExpr->getType())
6708  return SplattedExpr;
6709 
6710  assert(DestElemTy->isFloatingType() ||
6711  DestElemTy->isIntegralOrEnumerationType());
6712 
6713  CastKind CK;
6714  if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6715  // OpenCL requires that we convert `true` boolean expressions to -1, but
6716  // only when splatting vectors.
6717  if (DestElemTy->isFloatingType()) {
6718  // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6719  // in two steps: boolean to signed integral, then to floating.
6720  ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6721  CK_BooleanToSignedIntegral);
6722  SplattedExpr = CastExprRes.get();
6723  CK = CK_IntegralToFloating;
6724  } else {
6725  CK = CK_BooleanToSignedIntegral;
6726  }
6727  } else {
6728  ExprResult CastExprRes = SplattedExpr;
6729  CK = PrepareScalarCast(CastExprRes, DestElemTy);
6730  if (CastExprRes.isInvalid())
6731  return ExprError();
6732  SplattedExpr = CastExprRes.get();
6733  }
6734  return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6735 }
6736 
6738  Expr *CastExpr, CastKind &Kind) {
6739  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6740 
6741  QualType SrcTy = CastExpr->getType();
6742 
6743  // If SrcTy is a VectorType, the total size must match to explicitly cast to
6744  // an ExtVectorType.
6745  // In OpenCL, casts between vectors of different types are not allowed.
6746  // (See OpenCL 6.2).
6747  if (SrcTy->isVectorType()) {
6748  if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6749  (getLangOpts().OpenCL &&
6750  !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6751  Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6752  << DestTy << SrcTy << R;
6753  return ExprError();
6754  }
6755  Kind = CK_BitCast;
6756  return CastExpr;
6757  }
6758 
6759  // All non-pointer scalars can be cast to ExtVector type. The appropriate
6760  // conversion will take place first from scalar to elt type, and then
6761  // splat from elt type to vector.
6762  if (SrcTy->isPointerType())
6763  return Diag(R.getBegin(),
6764  diag::err_invalid_conversion_between_vector_and_scalar)
6765  << DestTy << SrcTy << R;
6766 
6767  Kind = CK_VectorSplat;
6768  return prepareVectorSplat(DestTy, CastExpr);
6769 }
6770 
6771 ExprResult
6773  Declarator &D, ParsedType &Ty,
6774  SourceLocation RParenLoc, Expr *CastExpr) {
6775  assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6776  "ActOnCastExpr(): missing type or expr");
6777 
6778  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6779  if (D.isInvalidType())
6780  return ExprError();
6781 
6782  if (getLangOpts().CPlusPlus) {
6783  // Check that there are no default arguments (C++ only).
6784  CheckExtraCXXDefaultArguments(D);
6785  } else {
6786  // Make sure any TypoExprs have been dealt with.
6787  ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6788  if (!Res.isUsable())
6789  return ExprError();
6790  CastExpr = Res.get();
6791  }
6792 
6793  checkUnusedDeclAttributes(D);
6794 
6795  QualType castType = castTInfo->getType();
6796  Ty = CreateParsedType(castType, castTInfo);
6797 
6798  bool isVectorLiteral = false;
6799 
6800  // Check for an altivec or OpenCL literal,
6801  // i.e. all the elements are integer constants.
6802  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6803  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6804  if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6805  && castType->isVectorType() && (PE || PLE)) {
6806  if (PLE && PLE->getNumExprs() == 0) {
6807  Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6808  return ExprError();
6809  }
6810  if (PE || PLE->getNumExprs() == 1) {
6811  Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6812  if (!E->getType()->isVectorType())
6813  isVectorLiteral = true;
6814  }
6815  else
6816  isVectorLiteral = true;
6817  }
6818 
6819  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6820  // then handle it as such.
6821  if (isVectorLiteral)
6822  return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6823 
6824  // If the Expr being casted is a ParenListExpr, handle it specially.
6825  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6826  // sequence of BinOp comma operators.
6827  if (isa<ParenListExpr>(CastExpr)) {
6828  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6829  if (Result.isInvalid()) return ExprError();
6830  CastExpr = Result.get();
6831  }
6832 
6833  if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6834  !getSourceManager().isInSystemMacro(LParenLoc))
6835  Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6836 
6837  CheckTollFreeBridgeCast(castType, CastExpr);
6838 
6839  CheckObjCBridgeRelatedCast(castType, CastExpr);
6840 
6841  DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6842 
6843  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6844 }
6845 
6847  SourceLocation RParenLoc, Expr *E,
6848  TypeSourceInfo *TInfo) {
6849  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6850  "Expected paren or paren list expression");
6851 
6852  Expr **exprs;
6853  unsigned numExprs;
6854  Expr *subExpr;
6855  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6856  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6857  LiteralLParenLoc = PE->getLParenLoc();
6858  LiteralRParenLoc = PE->getRParenLoc();
6859  exprs = PE->getExprs();
6860  numExprs = PE->getNumExprs();
6861  } else { // isa<ParenExpr> by assertion at function entrance
6862  LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6863  LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6864  subExpr = cast<ParenExpr>(E)->getSubExpr();
6865  exprs = &subExpr;
6866  numExprs = 1;
6867  }
6868 
6869  QualType Ty = TInfo->getType();
6870  assert(Ty->isVectorType() && "Expected vector type");
6871 
6872  SmallVector<Expr *, 8> initExprs;
6873  const VectorType *VTy = Ty->castAs<VectorType>();
6874  unsigned numElems = VTy->getNumElements();
6875 
6876  // '(...)' form of vector initialization in AltiVec: the number of
6877  // initializers must be one or must match the size of the vector.
6878  // If a single value is specified in the initializer then it will be
6879  // replicated to all the components of the vector
6880  if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6881  // The number of initializers must be one or must match the size of the
6882  // vector. If a single value is specified in the initializer then it will
6883  // be replicated to all the components of the vector
6884  if (numExprs == 1) {
6885  QualType ElemTy = VTy->getElementType();
6886  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6887  if (Literal.isInvalid())
6888  return ExprError();
6889  Literal = ImpCastExprToType(Literal.get(), ElemTy,
6890  PrepareScalarCast(Literal, ElemTy));
6891  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6892  }
6893  else if (numExprs < numElems) {
6894  Diag(E->getExprLoc(),
6895  diag::err_incorrect_number_of_vector_initializers);
6896  return ExprError();
6897  }
6898  else
6899  initExprs.append(exprs, exprs + numExprs);
6900  }
6901  else {
6902  // For OpenCL, when the number of initializers is a single value,
6903  // it will be replicated to all components of the vector.
6904  if (getLangOpts().OpenCL &&
6906  numExprs == 1) {
6907  QualType ElemTy = VTy->getElementType();
6908  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6909  if (Literal.isInvalid())
6910  return ExprError();
6911  Literal = ImpCastExprToType(Literal.get(), ElemTy,
6912  PrepareScalarCast(Literal, ElemTy));
6913  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6914  }
6915 
6916  initExprs.append(exprs, exprs + numExprs);
6917  }
6918  // FIXME: This means that pretty-printing the final AST will produce curly
6919  // braces instead of the original commas.
6920  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6921  initExprs, LiteralRParenLoc);
6922  initE->setType(Ty);
6923  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6924 }
6925 
6926 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6927 /// the ParenListExpr into a sequence of comma binary operators.
6928 ExprResult
6930  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6931  if (!E)
6932  return OrigExpr;
6933 
6934  ExprResult Result(E->getExpr(0));
6935 
6936  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6937  Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6938  E->getExpr(i));
6939 
6940  if (Result.isInvalid()) return ExprError();
6941 
6942  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6943 }
6944 
6946  SourceLocation R,
6947  MultiExprArg Val) {
6948  return ParenListExpr::Create(Context, L, Val, R);
6949 }
6950 
6951 /// Emit a specialized diagnostic when one expression is a null pointer
6952 /// constant and the other is not a pointer. Returns true if a diagnostic is
6953 /// emitted.
6955  SourceLocation QuestionLoc) {
6956  Expr *NullExpr = LHSExpr;
6957  Expr *NonPointerExpr = RHSExpr;
6959  NullExpr->isNullPointerConstant(Context,
6961 
6962  if (NullKind == Expr::NPCK_NotNull) {
6963  NullExpr = RHSExpr;
6964  NonPointerExpr = LHSExpr;
6965  NullKind =
6966  NullExpr->isNullPointerConstant(Context,
6968  }
6969 
6970  if (NullKind == Expr::NPCK_NotNull)
6971  return false;
6972 
6973  if (NullKind == Expr::NPCK_ZeroExpression)
6974  return false;
6975 
6976  if (NullKind == Expr::NPCK_ZeroLiteral) {
6977  // In this case, check to make sure that we got here from a "NULL"
6978  // string in the source code.
6979  NullExpr = NullExpr->IgnoreParenImpCasts();
6980  SourceLocation loc = NullExpr->getExprLoc();
6981  if (!findMacroSpelling(loc, "NULL"))
6982  return false;
6983  }
6984 
6985  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6986  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6987  << NonPointerExpr->getType() << DiagType
6988  << NonPointerExpr->getSourceRange();
6989  return true;
6990 }
6991 
6992 /// Return false if the condition expression is valid, true otherwise.
6993 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6994  QualType CondTy = Cond->getType();
6995 
6996  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6997  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6998  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6999  << CondTy << Cond->getSourceRange();
7000  return true;
7001  }
7002 
7003  // C99 6.5.15p2
7004  if (CondTy->isScalarType()) return false;
7005 
7006  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7007  << CondTy << Cond->getSourceRange();
7008  return true;
7009 }
7010 
7011 /// Handle when one or both operands are void type.
7013  ExprResult &RHS) {
7014  Expr *LHSExpr = LHS.get();
7015  Expr *RHSExpr = RHS.get();
7016 
7017  if (!LHSExpr->getType()->isVoidType())
7018  S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7019  << RHSExpr->getSourceRange();
7020  if (!RHSExpr->getType()->isVoidType())
7021  S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7022  << LHSExpr->getSourceRange();
7023  LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7024  RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7025  return S.Context.VoidTy;
7026 }
7027 
7028 /// Return false if the NullExpr can be promoted to PointerTy,
7029 /// true otherwise.
7030 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7031  QualType PointerTy) {
7032  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7033  !NullExpr.get()->isNullPointerConstant(S.Context,
7035  return true;
7036 
7037  NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7038  return false;
7039 }
7040 
7041 /// Checks compatibility between two pointers and return the resulting
7042 /// type.
7044  ExprResult &RHS,
7045  SourceLocation Loc) {
7046  QualType LHSTy = LHS.get()->getType();
7047  QualType RHSTy = RHS.get()->getType();
7048 
7049  if (S.Context.hasSameType(LHSTy, RHSTy)) {
7050  // Two identical pointers types are always compatible.
7051  return LHSTy;
7052  }
7053 
7054  QualType lhptee, rhptee;
7055 
7056  // Get the pointee types.
7057  bool IsBlockPointer = false;
7058  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7059  lhptee = LHSBTy->getPointeeType();
7060  rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7061  IsBlockPointer = true;
7062  } else {
7063  lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7064  rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7065  }
7066 
7067  // C99 6.5.15p6: If both operands are pointers to compatible types or to
7068  // differently qualified versions of compatible types, the result type is
7069  // a pointer to an appropriately qualified version of the composite
7070  // type.
7071 
7072  // Only CVR-qualifiers exist in the standard, and the differently-qualified
7073  // clause doesn't make sense for our extensions. E.g. address space 2 should
7074  // be incompatible with address space 3: they may live on different devices or
7075  // anything.
7076  Qualifiers lhQual = lhptee.getQualifiers();
7077  Qualifiers rhQual = rhptee.getQualifiers();
7078 
7079  LangAS ResultAddrSpace = LangAS::Default;
7080  LangAS LAddrSpace = lhQual.getAddressSpace();
7081  LangAS RAddrSpace = rhQual.getAddressSpace();
7082 
7083  // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7084  // spaces is disallowed.
7085  if (lhQual.isAddressSpaceSupersetOf(rhQual))
7086  ResultAddrSpace = LAddrSpace;
7087  else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7088  ResultAddrSpace = RAddrSpace;
7089  else {
7090  S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7091  << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7092  << RHS.get()->getSourceRange();
7093  return QualType();
7094  }
7095 
7096  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7097  auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7098  lhQual.removeCVRQualifiers();
7099  rhQual.removeCVRQualifiers();
7100 
7101  // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7102  // (C99 6.7.3) for address spaces. We assume that the check should behave in
7103  // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7104  // qual types are compatible iff
7105  // * corresponded types are compatible
7106  // * CVR qualifiers are equal
7107  // * address spaces are equal
7108  // Thus for conditional operator we merge CVR and address space unqualified
7109  // pointees and if there is a composite type we return a pointer to it with
7110  // merged qualifiers.
7111  LHSCastKind =
7112  LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7113  RHSCastKind =
7114  RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7115  lhQual.removeAddressSpace();
7116  rhQual.removeAddressSpace();
7117 
7118  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7119  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7120 
7121  QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7122 
7123  if (CompositeTy.isNull()) {
7124  // In this situation, we assume void* type. No especially good
7125  // reason, but this is what gcc does, and we do have to pick
7126  // to get a consistent AST.
7127  QualType incompatTy;
7128  incompatTy = S.Context.getPointerType(
7129  S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7130  LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7131  RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7132 
7133  // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7134  // for casts between types with incompatible address space qualifiers.
7135  // For the following code the compiler produces casts between global and
7136  // local address spaces of the corresponded innermost pointees:
7137  // local int *global *a;
7138  // global int *global *b;
7139  // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7140  S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7141  << LHSTy << RHSTy << LHS.get()->getSourceRange()
7142  << RHS.get()->getSourceRange();
7143 
7144  return incompatTy;
7145  }
7146 
7147  // The pointer types are compatible.
7148  // In case of OpenCL ResultTy should have the address space qualifier
7149  // which is a superset of address spaces of both the 2nd and the 3rd
7150  // operands of the conditional operator.
7151  QualType ResultTy = [&, ResultAddrSpace]() {
7152  if (S.getLangOpts().OpenCL) {
7153  Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7154  CompositeQuals.setAddressSpace(ResultAddrSpace);
7155  return S.Context
7156  .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7157  .withCVRQualifiers(MergedCVRQual);
7158  }
7159  return CompositeTy.withCVRQualifiers(MergedCVRQual);
7160  }();
7161  if (IsBlockPointer)
7162  ResultTy = S.Context.getBlockPointerType(ResultTy);
7163  else
7164  ResultTy = S.Context.getPointerType(ResultTy);
7165 
7166  LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7167  RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7168  return ResultTy;
7169 }
7170 
7171 /// Return the resulting type when the operands are both block pointers.
7173  ExprResult &LHS,
7174  ExprResult &RHS,
7175  SourceLocation Loc) {
7176  QualType LHSTy = LHS.get()->getType();
7177  QualType RHSTy = RHS.get()->getType();
7178 
7179  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7180  if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7181  QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7182  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7183  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7184  return destType;
7185  }
7186  S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7187  << LHSTy << RHSTy << LHS.get()->getSourceRange()
7188  << RHS.get()->getSourceRange();
7189  return QualType();
7190  }
7191 
7192  // We have 2 block pointer types.
7193  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7194 }
7195 
7196 /// Return the resulting type when the operands are both pointers.
7197 static QualType
7199  ExprResult &RHS,
7200  SourceLocation Loc) {
7201  // get the pointer types
7202  QualType LHSTy = LHS.get()->getType();
7203  QualType RHSTy = RHS.get()->getType();
7204 
7205  // get the "pointed to" types
7206  QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7207  QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7208 
7209  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7210  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7211  // Figure out necessary qualifiers (C99 6.5.15p6)
7212  QualType destPointee
7213  = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7214  QualType destType = S.Context.getPointerType(destPointee);
7215  // Add qualifiers if necessary.
7216  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7217  // Promote to void*.
7218  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7219  return destType;
7220  }
7221  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7222  QualType destPointee
7223  = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7224  QualType destType = S.Context.getPointerType(destPointee);
7225  // Add qualifiers if necessary.
7226  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7227  // Promote to void*.
7228  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7229  return destType;
7230  }
7231 
7232  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7233 }
7234 
7235 /// Return false if the first expression is not an integer and the second
7236 /// expression is not a pointer, true otherwise.
7238  Expr* PointerExpr, SourceLocation Loc,
7239  bool IsIntFirstExpr) {
7240  if (!PointerExpr->getType()->isPointerType() ||
7241  !Int.get()->getType()->isIntegerType())
7242  return false;
7243 
7244  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7245  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7246 
7247  S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7248  << Expr1->getType() << Expr2->getType()
7249  << Expr1->getSourceRange() << Expr2->getSourceRange();
7250  Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7251  CK_IntegralToPointer);
7252  return true;
7253 }
7254 
7255 /// Simple conversion between integer and floating point types.
7256 ///
7257 /// Used when handling the OpenCL conditional operator where the
7258 /// condition is a vector while the other operands are scalar.
7259 ///
7260 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7261 /// types are either integer or floating type. Between the two
7262 /// operands, the type with the higher rank is defined as the "result
7263 /// type". The other operand needs to be promoted to the same type. No
7264 /// other type promotion is allowed. We cannot use
7265 /// UsualArithmeticConversions() for this purpose, since it always
7266 /// promotes promotable types.
7268  ExprResult &RHS,
7269  SourceLocation QuestionLoc) {
7271  if (LHS.isInvalid())
7272  return QualType();
7274  if (RHS.isInvalid())
7275  return QualType();
7276 
7277  // For conversion purposes, we ignore any qualifiers.
7278  // For example, "const float" and "float" are equivalent.
7279  QualType LHSType =
7280  S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7281  QualType RHSType =
7282  S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7283 
7284  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7285  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7286  << LHSType << LHS.get()->getSourceRange();
7287  return QualType();
7288  }
7289 
7290  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7291  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7292  << RHSType << RHS.get()->getSourceRange();
7293  return QualType();
7294  }
7295 
7296  // If both types are identical, no conversion is needed.
7297  if (LHSType == RHSType)
7298  return LHSType;
7299 
7300  // Now handle "real" floating types (i.e. float, double, long double).
7301  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7302  return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7303  /*IsCompAssign = */ false);
7304 
7305  // Finally, we have two differing integer types.
7306  return handleIntegerConversion<doIntegralCast, doIntegralCast>
7307  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7308 }
7309 
7310 /// Convert scalar operands to a vector that matches the
7311 /// condition in length.
7312 ///
7313 /// Used when handling the OpenCL conditional operator where the
7314 /// condition is a vector while the other operands are scalar.
7315 ///
7316 /// We first compute the "result type" for the scalar operands
7317 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7318 /// into a vector of that type where the length matches the condition
7319 /// vector type. s6.11.6 requires that the element types of the result
7320 /// and the condition must have the same number of bits.
7321 static QualType
7323  QualType CondTy, SourceLocation QuestionLoc) {
7324  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7325  if (ResTy.isNull()) return QualType();
7326 
7327  const VectorType *CV = CondTy->getAs<VectorType>();
7328  assert(CV);
7329 
7330  // Determine the vector result type
7331  unsigned NumElements = CV->getNumElements();
7332  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7333 
7334  // Ensure that all types have the same number of bits
7335  if (S.Context.getTypeSize(CV->getElementType())
7336  != S.Context.getTypeSize(ResTy)) {
7337  // Since VectorTy is created internally, it does not pretty print
7338  // with an OpenCL name. Instead, we just print a description.
7339  std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7340  SmallString<64> Str;
7341  llvm::raw_svector_ostream OS(Str);
7342  OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7343  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7344  << CondTy << OS.str();
7345  return QualType();
7346  }
7347 
7348  // Convert operands to the vector result type
7349  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7350  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7351 
7352  return VectorTy;
7353 }
7354 
7355 /// Return false if this is a valid OpenCL condition vector
7356 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7357  SourceLocation QuestionLoc) {
7358  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7359  // integral type.
7360  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7361  assert(CondTy);
7362  QualType EleTy = CondTy->getElementType();
7363  if (EleTy->isIntegerType()) return false;
7364 
7365  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7366  << Cond->getType() << Cond->getSourceRange();
7367  return true;
7368 }
7369 
7370 /// Return false if the vector condition type and the vector
7371 /// result type are compatible.
7372 ///
7373 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7374 /// number of elements, and their element types have the same number
7375 /// of bits.
7376 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7377  SourceLocation QuestionLoc) {
7378  const VectorType *CV = CondTy->getAs<VectorType>();
7379  const VectorType *RV = VecResTy->getAs<VectorType>();
7380  assert(CV && RV);
7381 
7382  if (CV->getNumElements() != RV->getNumElements()) {
7383  S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7384  << CondTy << VecResTy;
7385  return true;
7386  }
7387 
7388  QualType CVE = CV->getElementType();
7389  QualType RVE = RV->getElementType();
7390 
7391  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7392  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7393  << CondTy << VecResTy;
7394  return true;
7395  }
7396 
7397  return false;
7398 }
7399 
7400 /// Return the resulting type for the conditional operator in
7401 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
7402 /// s6.3.i) when the condition is a vector type.
7403 static QualType
7405  ExprResult &LHS, ExprResult &RHS,
7406  SourceLocation QuestionLoc) {
7407  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7408  if (Cond.isInvalid())
7409  return QualType();
7410  QualType CondTy = Cond.get()->getType();
7411 
7412  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7413  return QualType();
7414 
7415  // If either operand is a vector then find the vector type of the
7416  // result as specified in OpenCL v1.1 s6.3.i.
7417  if (LHS.get()->getType()->isVectorType() ||
7418  RHS.get()->getType()->isVectorType()) {
7419  QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7420  /*isCompAssign*/false,
7421  /*AllowBothBool*/true,
7422  /*AllowBoolConversions*/false);
7423  if (VecResTy.isNull()) return QualType();
7424  // The result type must match the condition type as specified in
7425  // OpenCL v1.1 s6.11.6.
7426  if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7427  return QualType();
7428  return VecResTy;
7429  }
7430 
7431  // Both operands are scalar.
7432  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7433 }
7434 
7435 /// Return true if the Expr is block type
7436 static bool checkBlockType(Sema &S, const Expr *E) {
7437  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7438  QualType Ty = CE->getCallee()->getType();
7439  if (Ty->isBlockPointerType()) {
7440  S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7441  return true;
7442  }
7443  }
7444  return false;
7445 }
7446 
7447 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7448 /// In that case, LHS = cond.
7449 /// C99 6.5.15
7451  ExprResult &RHS, ExprValueKind &VK,
7452  ExprObjectKind &OK,
7453  SourceLocation QuestionLoc) {
7454 
7455  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7456  if (!LHSResult.isUsable()) return QualType();
7457  LHS = LHSResult;
7458 
7459  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7460  if (!RHSResult.isUsable()) return QualType();
7461  RHS = RHSResult;
7462 
7463  // C++ is sufficiently different to merit its own checker.
7464  if (getLangOpts().CPlusPlus)
7465  return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7466 
7467  VK = VK_RValue;
7468  OK = OK_Ordinary;
7469 
7470  // The OpenCL operator with a vector condition is sufficiently
7471  // different to merit its own checker.
7472  if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7473  return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7474 
7475  // First, check the condition.
7476  Cond = UsualUnaryConversions(Cond.get());
7477  if (Cond.isInvalid())
7478  return QualType();
7479  if (checkCondition(*this, Cond.get(), QuestionLoc))
7480  return QualType();
7481 
7482  // Now check the two expressions.
7483  if (LHS.get()->getType()->isVectorType() ||
7484  RHS.get()->getType()->isVectorType())
7485  return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7486  /*AllowBothBool*/true,
7487  /*AllowBoolConversions*/false);
7488 
7489  QualType ResTy =
7490  UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7491  if (LHS.isInvalid() || RHS.isInvalid())
7492  return QualType();
7493 
7494  QualType LHSTy = LHS.get()->getType();
7495  QualType RHSTy = RHS.get()->getType();
7496 
7497  // Diagnose attempts to convert between __float128 and long double where
7498  // such conversions currently can't be handled.
7499  if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7500  Diag(QuestionLoc,
7501  diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7502  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7503  return QualType();
7504  }
7505 
7506  // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7507  // selection operator (?:).
7508  if (getLangOpts().OpenCL &&
7509  (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7510  return QualType();
7511  }
7512 
7513  // If both operands have arithmetic type, do the usual arithmetic conversions
7514  // to find a common type: C99 6.5.15p3,5.
7515  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7516  LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7517  RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7518 
7519  return ResTy;
7520  }
7521 
7522  // If both operands are the same structure or union type, the result is that
7523  // type.
7524  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
7525  if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7526  if (LHSRT->getDecl() == RHSRT->getDecl())
7527  // "If both the operands have structure or union type, the result has
7528  // that type." This implies that CV qualifiers are dropped.
7529  return LHSTy.getUnqualifiedType();
7530  // FIXME: Type of conditional expression must be complete in C mode.
7531  }
7532 
7533  // C99 6.5.15p5: "If both operands have void type, the result has void type."
7534  // The following || allows only one side to be void (a GCC-ism).
7535  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7536  return checkConditionalVoidType(*this, LHS, RHS);
7537  }
7538 
7539  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7540  // the type of the other operand."
7541  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7542  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7543 
7544  // All objective-c pointer type analysis is done here.
7545  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7546  QuestionLoc);
7547  if (LHS.isInvalid() || RHS.isInvalid())
7548  return QualType();
7549  if (!compositeType.isNull())
7550  return compositeType;
7551 
7552 
7553  // Handle block pointer types.
7554  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7555  return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7556  QuestionLoc);
7557 
7558  // Check constraints for C object pointers types (C99 6.5.15p3,6).
7559  if (LHSTy->isPointerType() && RHSTy->isPointerType())
7560  return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7561  QuestionLoc);
7562 
7563  // GCC compatibility: soften pointer/integer mismatch. Note that
7564  // null pointers have been filtered out by this point.
7565  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7566  /*IsIntFirstExpr=*/true))
7567  return RHSTy;
7568  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7569  /*IsIntFirstExpr=*/false))
7570  return LHSTy;
7571 
7572  // Emit a better diagnostic if one of the expressions is a null pointer
7573  // constant and the other is not a pointer type. In this case, the user most
7574  // likely forgot to take the address of the other expression.
7575  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7576  return QualType();
7577 
7578  // Otherwise, the operands are not compatible.
7579  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7580  << LHSTy << RHSTy << LHS.get()->getSourceRange()
7581  << RHS.get()->getSourceRange();
7582  return QualType();
7583 }
7584 
7585 /// FindCompositeObjCPointerType - Helper method to find composite type of
7586 /// two objective-c pointer types of the two input expressions.
7588  SourceLocation QuestionLoc) {
7589  QualType LHSTy = LHS.get()->getType();
7590  QualType RHSTy = RHS.get()->getType();
7591 
7592  // Handle things like Class and struct objc_class*. Here we case the result
7593  // to the pseudo-builtin, because that will be implicitly cast back to the
7594  // redefinition type if an attempt is made to access its fields.
7595  if (LHSTy->isObjCClassType() &&
7596  (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7597  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7598  return LHSTy;
7599  }
7600  if (RHSTy->isObjCClassType() &&
7601  (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7602  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7603  return RHSTy;
7604  }
7605  // And the same for struct objc_object* / id
7606  if (LHSTy->isObjCIdType() &&
7607  (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7608  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7609  return LHSTy;
7610  }
7611  if (RHSTy->isObjCIdType() &&
7612  (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7613  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7614  return RHSTy;
7615  }
7616  // And the same for struct objc_selector* / SEL
7617  if (Context.isObjCSelType(LHSTy) &&
7618  (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7619  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7620  return LHSTy;
7621  }
7622  if (Context.isObjCSelType(RHSTy) &&
7623  (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7624  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7625  return RHSTy;
7626  }
7627  // Check constraints for Objective-C object pointers types.
7628  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7629 
7630  if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7631  // Two identical object pointer types are always compatible.
7632  return LHSTy;
7633  }
7634  const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7635  const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7636  QualType compositeType = LHSTy;
7637 
7638  // If both operands are interfaces and either operand can be
7639  // assigned to the other, use that type as the composite
7640  // type. This allows
7641  // xxx ? (A*) a : (B*) b
7642  // where B is a subclass of A.
7643  //
7644  // Additionally, as for assignment, if either type is 'id'
7645  // allow silent coercion. Finally, if the types are
7646  // incompatible then make sure to use 'id' as the composite
7647  // type so the result is acceptable for sending messages to.
7648 
7649  // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7650  // It could return the composite type.
7651  if (!(compositeType =
7652  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7653  // Nothing more to do.
7654  } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7655  compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7656  } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7657  compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7658  } else if ((LHSOPT->isObjCQualifiedIdType() ||
7659  RHSOPT->isObjCQualifiedIdType()) &&
7660  Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7661  true)) {
7662  // Need to handle "id<xx>" explicitly.
7663  // GCC allows qualified id and any Objective-C type to devolve to
7664  // id. Currently localizing to here until clear this should be
7665  // part of ObjCQualifiedIdTypesAreCompatible.
7666  compositeType = Context.getObjCIdType();
7667  } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7668  compositeType = Context.getObjCIdType();
7669  } else {
7670  Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7671  << LHSTy << RHSTy
7672  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7673  QualType incompatTy = Context.getObjCIdType();
7674  LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7675  RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7676  return incompatTy;
7677  }
7678  // The object pointer types are compatible.
7679  LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7680  RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7681  return compositeType;
7682  }
7683  // Check Objective-C object pointer types and 'void *'
7684  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7685  if (getLangOpts().ObjCAutoRefCount) {
7686  // ARC forbids the implicit conversion of object pointers to 'void *',
7687  // so these types are not compatible.
7688  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7689  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7690  LHS = RHS = true;
7691  return QualType();
7692  }
7693  QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7694  QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7695  QualType destPointee
7696  = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7697  QualType destType = Context.getPointerType(destPointee);
7698  // Add qualifiers if necessary.
7699  LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7700  // Promote to void*.
7701  RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7702  return destType;
7703  }
7704  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7705  if (getLangOpts().ObjCAutoRefCount) {
7706  // ARC forbids the implicit conversion of object pointers to 'void *',
7707  // so these types are not compatible.
7708  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7709  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7710  LHS = RHS = true;
7711  return QualType();
7712  }
7713  QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7714  QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7715  QualType destPointee
7716  = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7717  QualType destType = Context.getPointerType(destPointee);
7718  // Add qualifiers if necessary.
7719  RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7720  // Promote to void*.
7721  LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7722  return destType;
7723  }
7724  return QualType();
7725 }
7726 
7727 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7728 /// ParenRange in parentheses.
7729 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7730  const PartialDiagnostic &Note,
7731  SourceRange ParenRange) {
7732  SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7733  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7734  EndLoc.isValid()) {
7735  Self.Diag(Loc, Note)
7736  << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7737  << FixItHint::CreateInsertion(EndLoc, ")");
7738  } else {
7739  // We can't display the parentheses, so just show the bare note.
7740  Self.Diag(Loc, Note) << ParenRange;
7741  }
7742 }
7743 
7745  return BinaryOperator::isAdditiveOp(Opc) ||
7747  BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
7748  // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
7749  // not any of the logical operators. Bitwise-xor is commonly used as a
7750  // logical-xor because there is no logical-xor operator. The logical
7751  // operators, including uses of xor, have a high false positive rate for
7752  // precedence warnings.
7753 }
7754 
7755 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7756 /// expression, either using a built-in or overloaded operator,
7757 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7758 /// expression.
7760  Expr **RHSExprs) {
7761  // Don't strip parenthesis: we should not warn if E is in parenthesis.
7762  E = E->IgnoreImpCasts();
7763  E = E->IgnoreConversionOperator();
7764  E = E->IgnoreImpCasts();
7765  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7766  E = MTE->getSubExpr();
7767  E = E->IgnoreImpCasts();
7768  }
7769 
7770  // Built-in binary operator.
7771  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7772  if (IsArithmeticOp(OP->getOpcode())) {
7773  *Opcode = OP->getOpcode();
7774  *RHSExprs = OP->getRHS();
7775  return true;
7776  }
7777  }
7778 
7779  // Overloaded operator.
7780  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7781  if (Call->getNumArgs() != 2)
7782  return false;
7783 
7784  // Make sure this is really a binary operator that is safe to pass into
7785  // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7786  OverloadedOperatorKind OO = Call->getOperator();
7787  if (OO < OO_Plus || OO > OO_Arrow ||
7788  OO == OO_PlusPlus || OO == OO_MinusMinus)
7789  return false;
7790 
7792  if (IsArithmeticOp(OpKind)) {
7793  *Opcode = OpKind;
7794  *RHSExprs = Call->getArg(1);
7795  return true;
7796  }
7797  }
7798 
7799  return false;
7800 }
7801 
7802 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7803 /// or is a logical expression such as (x==y) which has int type, but is
7804 /// commonly interpreted as boolean.
7805 static bool ExprLooksBoolean(Expr *E) {
7806  E = E->IgnoreParenImpCasts();
7807 
7808  if (E->getType()->isBooleanType())
7809  return true;
7810  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7811  return OP->isComparisonOp() || OP->isLogicalOp();
7812  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7813  return OP->getOpcode() == UO_LNot;
7814  if (E->getType()->isPointerType())
7815  return true;
7816  // FIXME: What about overloaded operator calls returning "unspecified boolean
7817  // type"s (commonly pointer-to-members)?
7818 
7819  return false;
7820 }
7821 
7822 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7823 /// and binary operator are mixed in a way that suggests the programmer assumed
7824 /// the conditional operator has higher precedence, for example:
7825 /// "int x = a + someBinaryCondition ? 1 : 2".
7827  SourceLocation OpLoc,
7828  Expr *Condition,
7829  Expr *LHSExpr,
7830  Expr *RHSExpr) {
7831  BinaryOperatorKind CondOpcode;
7832  Expr *CondRHS;
7833 
7834  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7835  return;
7836  if (!ExprLooksBoolean(CondRHS))
7837  return;
7838 
7839  // The condition is an arithmetic binary expression, with a right-
7840  // hand side that looks boolean, so warn.
7841 
7842  unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
7843  ? diag::warn_precedence_bitwise_conditional
7844  : diag::warn_precedence_conditional;
7845 
7846  Self.Diag(OpLoc, DiagID)
7847  << Condition->getSourceRange()
7848  << BinaryOperator::getOpcodeStr(CondOpcode);
7849 
7851  Self, OpLoc,
7852  Self.PDiag(diag::note_precedence_silence)
7853  << BinaryOperator::getOpcodeStr(CondOpcode),
7854  SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7855 
7856  SuggestParentheses(Self, OpLoc,
7857  Self.PDiag(diag::note_precedence_conditional_first),
7858  SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7859 }
7860 
7861 /// Compute the nullability of a conditional expression.
7863  QualType LHSTy, QualType RHSTy,
7864  ASTContext &Ctx) {
7865  if (!ResTy->isAnyPointerType())
7866  return ResTy;
7867 
7868  auto GetNullability = [&Ctx](QualType Ty) {
7869  Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7870  if (Kind)
7871  return *Kind;
7873  };
7874 
7875  auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7876  NullabilityKind MergedKind;
7877 
7878  // Compute nullability of a binary conditional expression.
7879  if (IsBin) {
7880  if (LHSKind == NullabilityKind::NonNull)
7881  MergedKind = NullabilityKind::NonNull;
7882  else
7883  MergedKind = RHSKind;
7884  // Compute nullability of a normal conditional expression.
7885  } else {
7886  if (LHSKind == NullabilityKind::Nullable ||
7887  RHSKind == NullabilityKind::Nullable)
7888  MergedKind = NullabilityKind::Nullable;
7889  else if (LHSKind == NullabilityKind::NonNull)
7890  MergedKind = RHSKind;
7891  else if (RHSKind == NullabilityKind::NonNull)
7892  MergedKind = LHSKind;
7893  else
7894  MergedKind = NullabilityKind::Unspecified;
7895  }
7896 
7897  // Return if ResTy already has the correct nullability.
7898  if (GetNullability(ResTy) == MergedKind)
7899  return ResTy;
7900 
7901  // Strip all nullability from ResTy.
7902  while (ResTy->getNullability(Ctx))
7903  ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7904 
7905  // Create a new AttributedType with the new nullability kind.
7906  auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7907  return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7908 }
7909 
7910 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7911 /// in the case of a the GNU conditional expr extension.
7914  Expr *CondExpr, Expr *LHSExpr,
7915  Expr *RHSExpr) {
7916  if (!getLangOpts().CPlusPlus) {
7917  // C cannot handle TypoExpr nodes in the condition because it
7918  // doesn't handle dependent types properly, so make sure any TypoExprs have
7919  // been dealt with before checking the operands.
7920  ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7921  ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7922  ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7923 
7924  if (!CondResult.isUsable())
7925  return ExprError();
7926 
7927  if (LHSExpr) {
7928  if (!LHSResult.isUsable())
7929  return ExprError();
7930  }
7931 
7932  if (!RHSResult.isUsable())
7933  return ExprError();
7934 
7935  CondExpr = CondResult.get();
7936  LHSExpr = LHSResult.get();
7937  RHSExpr = RHSResult.get();
7938  }
7939 
7940  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7941  // was the condition.
7942  OpaqueValueExpr *opaqueValue = nullptr;
7943  Expr *commonExpr = nullptr;
7944  if (!LHSExpr) {
7945  commonExpr = CondExpr;
7946  // Lower out placeholder types first. This is important so that we don't
7947  // try to capture a placeholder. This happens in few cases in C++; such
7948  // as Objective-C++'s dictionary subscripting syntax.
7949  if (commonExpr->hasPlaceholderType()) {
7950  ExprResult result = CheckPlaceholderExpr(commonExpr);
7951  if (!result.isUsable()) return ExprError();
7952  commonExpr = result.get();
7953  }
7954  // We usually want to apply unary conversions *before* saving, except
7955  // in the special case of a C++ l-value conditional.
7956  if (!(getLangOpts().CPlusPlus
7957  && !commonExpr->isTypeDependent()
7958  && commonExpr->getValueKind() == RHSExpr->getValueKind()
7959  && commonExpr->isGLValue()
7960  && commonExpr->isOrdinaryOrBitFieldObject()
7961  && RHSExpr->isOrdinaryOrBitFieldObject()
7962  && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7963  ExprResult commonRes = UsualUnaryConversions(commonExpr);
7964  if (commonRes.isInvalid())
7965  return ExprError();
7966  commonExpr = commonRes.get();
7967  }
7968 
7969  // If the common expression is a class or array prvalue, materialize it
7970  // so that we can safely refer to it multiple times.
7971  if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7972  commonExpr->getType()->isArrayType())) {
7973  ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7974  if (MatExpr.isInvalid())
7975  return ExprError();
7976  commonExpr = MatExpr.get();
7977  }
7978 
7979  opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7980  commonExpr->getType(),
7981  commonExpr->getValueKind(),
7982  commonExpr->getObjectKind(),
7983  commonExpr);
7984  LHSExpr = CondExpr = opaqueValue;
7985  }
7986 
7987  QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7988  ExprValueKind VK = VK_RValue;
7990  ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7991  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7992  VK, OK, QuestionLoc);
7993  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7994  RHS.isInvalid())
7995  return ExprError();
7996 
7997  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7998  RHS.get());
7999 
8000  CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8001 
8002  result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8003  Context);
8004 
8005  if (!commonExpr)
8006  return new (Context)
8007  ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8008  RHS.get(), result, VK, OK);
8009 
8010  return new (Context) BinaryConditionalOperator(
8011  commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8012  ColonLoc, result, VK, OK);
8013 }
8014 
8015 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8016 // being closely modeled after the C99 spec:-). The odd characteristic of this
8017 // routine is it effectively iqnores the qualifiers on the top level pointee.
8018 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8019 // FIXME: add a couple examples in this comment.
8022  assert(LHSType.isCanonical() && "LHS not canonicalized!");
8023  assert(RHSType.isCanonical() && "RHS not canonicalized!");
8024 
8025  // get the "pointed to" type (ignoring qualifiers at the top level)
8026  const Type *lhptee, *rhptee;
8027  Qualifiers lhq, rhq;
8028  std::tie(lhptee, lhq) =
8029  cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8030  std::tie(rhptee, rhq) =
8031  cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8032 
8034 
8035  // C99 6.5.16.1p1: This following citation is common to constraints
8036  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8037  // qualifiers of the type *pointed to* by the right;
8038 
8039  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8040  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8041  lhq.compatiblyIncludesObjCLifetime(rhq)) {
8042  // Ignore lifetime for further calculation.
8043  lhq.removeObjCLifetime();
8044  rhq.removeObjCLifetime();
8045  }
8046 
8047  if (!lhq.compatiblyIncludes(rhq)) {
8048  // Treat address-space mismatches as fatal.
8049  if (!lhq.isAddressSpaceSupersetOf(rhq))
8051 
8052  // It's okay to add or remove GC or lifetime qualifiers when converting to
8053  // and from void*.
8054  else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8057  && (lhptee->isVoidType() || rhptee->isVoidType()))
8058  ; // keep old
8059 
8060  // Treat lifetime mismatches as fatal.
8061  else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8063 
8064  // For GCC/MS compatibility, other qualifier mismatches are treated
8065  // as still compatible in C.
8067  }
8068 
8069  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8070  // incomplete type and the other is a pointer to a qualified or unqualified
8071  // version of void...
8072  if (lhptee->isVoidType()) {
8073  if (rhptee->isIncompleteOrObjectType())
8074  return ConvTy;
8075 
8076  // As an extension, we allow cast to/from void* to function pointer.
8077  assert(rhptee->isFunctionType());
8079  }
8080 
8081  if (rhptee->isVoidType()) {
8082  if (lhptee->isIncompleteOrObjectType())
8083  return ConvTy;
8084 
8085  // As an extension, we allow cast to/from void* to function pointer.
8086  assert(lhptee->isFunctionType());
8088  }
8089 
8090  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8091  // unqualified versions of compatible types, ...
8092  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8093  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8094  // Check if the pointee types are compatible ignoring the sign.
8095  // We explicitly check for char so that we catch "char" vs
8096  // "unsigned char" on systems where "char" is unsigned.
8097  if (lhptee->isCharType())
8098  ltrans = S.Context.UnsignedCharTy;
8099  else if (lhptee->hasSignedIntegerRepresentation())
8100  ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8101 
8102  if (rhptee->isCharType())
8103  rtrans = S.Context.UnsignedCharTy;
8104  else if (rhptee->hasSignedIntegerRepresentation())
8105  rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8106 
8107  if (ltrans == rtrans) {
8108  // Types are compatible ignoring the sign. Qualifier incompatibility
8109  // takes priority over sign incompatibility because the sign
8110  // warning can be disabled.
8111  if (ConvTy != Sema::Compatible)
8112  return ConvTy;
8113 
8115  }
8116 
8117  // If we are a multi-level pointer, it's possible that our issue is simply
8118  // one of qualification - e.g. char ** -> const char ** is not allowed. If
8119  // the eventual target type is the same and the pointers have the same
8120  // level of indirection, this must be the issue.
8121  if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8122  do {
8123  std::tie(lhptee, lhq) =
8124  cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8125  std::tie(rhptee, rhq) =
8126  cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8127 
8128  // Inconsistent address spaces at this point is invalid, even if the
8129  // address spaces would be compatible.
8130  // FIXME: This doesn't catch address space mismatches for pointers of
8131  // different nesting levels, like:
8132  // __local int *** a;
8133  // int ** b = a;
8134  // It's not clear how to actually determine when such pointers are
8135  // invalidly incompatible.
8136  if (lhq.getAddressSpace() != rhq.getAddressSpace())
8138 
8139  } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8140 
8141  if (lhptee == rhptee)
8143  }
8144 
8145  // General pointer incompatibility takes priority over qualifiers.
8147  }
8148  if (!S.getLangOpts().CPlusPlus &&
8149  S.IsFunctionConversion(ltrans, rtrans, ltrans))
8151  return ConvTy;
8152 }
8153 
8154 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8155 /// block pointer types are compatible or whether a block and normal pointer
8156 /// are compatible. It is more restrict than comparing two function pointer
8157 // types.
8160  QualType RHSType) {
8161  assert(LHSType.isCanonical() && "LHS not canonicalized!");
8162  assert(RHSType.isCanonical() && "RHS not canonicalized!");
8163 
8164  QualType lhptee, rhptee;
8165 
8166  // get the "pointed to" type (ignoring qualifiers at the top level)
8167  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8168  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8169 
8170  // In C++, the types have to match exactly.
8171  if (S.getLangOpts().CPlusPlus)
8173 
8175 
8176  // For blocks we enforce that qualifiers are identical.
8177  Qualifiers LQuals = lhptee.getLocalQualifiers();
8178  Qualifiers RQuals = rhptee.getLocalQualifiers();
8179  if (S.getLangOpts().OpenCL) {
8180  LQuals.removeAddressSpace();
8181  RQuals.removeAddressSpace();
8182  }
8183  if (LQuals != RQuals)
8185 
8186  // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8187  // assignment.
8188  // The current behavior is similar to C++ lambdas. A block might be
8189  // assigned to a variable iff its return type and parameters are compatible
8190  // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8191  // an assignment. Presumably it should behave in way that a function pointer
8192  // assignment does in C, so for each parameter and return type:
8193  // * CVR and address space of LHS should be a superset of CVR and address
8194  // space of RHS.
8195  // * unqualified types should be compatible.
8196  if (S.getLangOpts().OpenCL) {
8198  S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8199  S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8201  } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8203 
8204  return ConvTy;
8205 }
8206 
8207 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8208 /// for assignment compatibility.
8211  QualType RHSType) {
8212  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8213  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8214 
8215  if (LHSType->isObjCBuiltinType()) {
8216  // Class is not compatible with ObjC object pointers.
8217  if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8218  !RHSType->isObjCQualifiedClassType())
8220  return Sema::Compatible;
8221  }
8222  if (RHSType->isObjCBuiltinType()) {
8223  if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8224  !LHSType->isObjCQualifiedClassType())
8226  return Sema::Compatible;
8227  }
8228  QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8229  QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8230 
8231  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8232  // make an exception for id<P>
8233  !LHSType->isObjCQualifiedIdType())
8235 
8236  if (S.Context.typesAreCompatible(LHSType, RHSType))
8237  return Sema::Compatible;
8238  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8241 }
8242 
8245  QualType LHSType, QualType RHSType) {
8246  // Fake up an opaque expression. We don't actually care about what
8247  // cast operations are required, so if CheckAssignmentConstraints
8248  // adds casts to this they'll be wasted, but fortunately that doesn't
8249  // usually happen on valid code.
8250  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8251  ExprResult RHSPtr = &RHSExpr;
8252  CastKind K;
8253 
8254  return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8255 }
8256 
8257 /// This helper function returns true if QT is a vector type that has element
8258 /// type ElementType.
8259 static bool isVector(QualType QT, QualType ElementType) {
8260  if (const VectorType *VT = QT->getAs<VectorType>())
8261  return VT->getElementType() == ElementType;
8262  return false;
8263 }
8264 
8265 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8266 /// has code to accommodate several GCC extensions when type checking
8267 /// pointers. Here are some objectionable examples that GCC considers warnings:
8268 ///
8269 /// int a, *pint;
8270 /// short *pshort;
8271 /// struct foo *pfoo;
8272 ///
8273 /// pint = pshort; // warning: assignment from incompatible pointer type
8274 /// a = pint; // warning: assignment makes integer from pointer without a cast
8275 /// pint = a; // warning: assignment makes pointer from integer without a cast
8276 /// pint = pfoo; // warning: assignment from incompatible pointer type
8277 ///
8278 /// As a result, the code for dealing with pointers is more complex than the
8279 /// C99 spec dictates.
8280 ///
8281 /// Sets 'Kind' for any result kind except Incompatible.
8284  CastKind &Kind, bool ConvertRHS) {
8285  QualType RHSType = RHS.get()->getType();
8286  QualType OrigLHSType = LHSType;
8287 
8288  // Get canonical types. We're not formatting these types, just comparing
8289  // them.
8290  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8291  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8292 
8293  // Common case: no conversion required.
8294  if (LHSType == RHSType) {
8295  Kind = CK_NoOp;
8296  return Compatible;
8297  }
8298 
8299  // If we have an atomic type, try a non-atomic assignment, then just add an
8300  // atomic qualification step.
8301  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8302  Sema::AssignConvertType result =
8303  CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8304  if (result != Compatible)
8305  return result;
8306  if (Kind != CK_NoOp && ConvertRHS)
8307  RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8308  Kind = CK_NonAtomicToAtomic;
8309  return Compatible;
8310  }
8311 
8312  // If the left-hand side is a reference type, then we are in a
8313  // (rare!) case where we've allowed the use of references in C,
8314  // e.g., as a parameter type in a built-in function. In this case,
8315  // just make sure that the type referenced is compatible with the
8316  // right-hand side type. The caller is responsible for adjusting
8317  // LHSType so that the resulting expression does not have reference
8318  // type.
8319  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8320  if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8321  Kind = CK_LValueBitCast;
8322  return Compatible;
8323  }
8324  return Incompatible;
8325  }
8326 
8327  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8328  // to the same ExtVector type.
8329  if (LHSType->isExtVectorType()) {
8330  if (RHSType->isExtVectorType())
8331  return Incompatible;
8332  if (RHSType->isArithmeticType()) {
8333  // CK_VectorSplat does T -> vector T, so first cast to the element type.
8334  if (ConvertRHS)
8335  RHS = prepareVectorSplat(LHSType, RHS.get());
8336  Kind = CK_VectorSplat;
8337  return Compatible;
8338  }
8339  }
8340 
8341  // Conversions to or from vector type.
8342  if (LHSType->isVectorType() || RHSType->isVectorType()) {
8343  if (LHSType->isVectorType() && RHSType->isVectorType()) {
8344  // Allow assignments of an AltiVec vector type to an equivalent GCC
8345  // vector type and vice versa
8346  if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8347  Kind = CK_BitCast;
8348  return Compatible;
8349  }
8350 
8351  // If we are allowing lax vector conversions, and LHS and RHS are both
8352  // vectors, the total size only needs to be the same. This is a bitcast;
8353  // no bits are changed but the result type is different.
8354  if (isLaxVectorConversion(RHSType, LHSType)) {
8355  Kind = CK_BitCast;
8356  return IncompatibleVectors;
8357  }
8358  }
8359 
8360  // When the RHS comes from another lax conversion (e.g. binops between
8361  // scalars and vectors) the result is canonicalized as a vector. When the
8362  // LHS is also a vector, the lax is allowed by the condition above. Handle
8363  // the case where LHS is a scalar.
8364  if (LHSType->isScalarType()) {
8365  const VectorType *VecType = RHSType->getAs<VectorType>();
8366  if (VecType && VecType->getNumElements() == 1 &&
8367  isLaxVectorConversion(RHSType, LHSType)) {
8368  ExprResult *VecExpr = &RHS;
8369  *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8370  Kind = CK_BitCast;
8371  return Compatible;
8372  }
8373  }
8374 
8375  return Incompatible;
8376  }
8377 
8378  // Diagnose attempts to convert between __float128 and long double where
8379  // such conversions currently can't be handled.
8380  if (unsupportedTypeConversion(*this, LHSType, RHSType))
8381  return Incompatible;
8382 
8383  // Disallow assigning a _Complex to a real type in C++ mode since it simply
8384  // discards the imaginary part.
8385  if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8386  !LHSType->getAs<ComplexType>())
8387  return Incompatible;
8388 
8389  // Arithmetic conversions.
8390  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8391  !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8392  if (ConvertRHS)
8393  Kind = PrepareScalarCast(RHS, LHSType);
8394  return Compatible;
8395  }
8396 
8397  // Conversions to normal pointers.
8398  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8399  // U* -> T*
8400  if (isa<PointerType>(RHSType)) {
8401  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8402  LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8403  if (AddrSpaceL != AddrSpaceR)
8404  Kind = CK_AddressSpaceConversion;
8405  else if (Context.hasCvrSimilarType(RHSType, LHSType))
8406  Kind = CK_NoOp;
8407  else
8408  Kind = CK_BitCast;
8409  return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8410  }
8411 
8412  // int -> T*
8413  if (RHSType->isIntegerType()) {
8414  Kind = CK_IntegralToPointer; // FIXME: null?
8415  return IntToPointer;
8416  }
8417 
8418  // C pointers are not compatible with ObjC object pointers,
8419  // with two exceptions:
8420  if (isa<ObjCObjectPointerType>(RHSType)) {
8421  // - conversions to void*
8422  if (LHSPointer->getPointeeType()->isVoidType()) {
8423  Kind = CK_BitCast;
8424  return Compatible;
8425  }
8426 
8427  // - conversions from 'Class' to the redefinition type
8428  if (RHSType->isObjCClassType() &&
8429  Context.hasSameType(LHSType,
8430  Context.getObjCClassRedefinitionType())) {
8431  Kind = CK_BitCast;
8432  return Compatible;
8433  }
8434 
8435  Kind = CK_BitCast;
8436  return IncompatiblePointer;
8437  }
8438 
8439  // U^ -> void*
8440  if (RHSType->getAs<BlockPointerType>()) {
8441  if (LHSPointer->getPointeeType()->isVoidType()) {
8442  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8443  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8444  ->getPointeeType()
8445  .getAddressSpace();
8446  Kind =
8447  AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8448  return Compatible;
8449  }
8450  }
8451 
8452  return Incompatible;
8453  }
8454 
8455  // Conversions to block pointers.
8456  if (isa<BlockPointerType>(LHSType)) {
8457  // U^ -> T^
8458  if (RHSType->isBlockPointerType()) {
8459  LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8460  ->getPointeeType()
8461  .getAddressSpace();
8462  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8463  ->getPointeeType()
8464  .getAddressSpace();
8465  Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8466  return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8467  }
8468 
8469  // int or null -> T^
8470  if (RHSType->isIntegerType()) {
8471  Kind = CK_IntegralToPointer; // FIXME: null
8472  return IntToBlockPointer;
8473  }
8474 
8475  // id -> T^
8476  if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8477  Kind = CK_AnyPointerToBlockPointerCast;
8478  return Compatible;
8479  }
8480 
8481  // void* -> T^
8482  if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8483  if (RHSPT->getPointeeType()->isVoidType()) {
8484  Kind = CK_AnyPointerToBlockPointerCast;
8485  return Compatible;
8486  }
8487 
8488  return Incompatible;
8489  }
8490 
8491  // Conversions to Objective-C pointers.
8492  if (isa<ObjCObjectPointerType>(LHSType)) {
8493  // A* -> B*
8494  if (RHSType->isObjCObjectPointerType()) {
8495  Kind = CK_BitCast;
8496  Sema::AssignConvertType result =
8497  checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8498  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8499  result == Compatible &&
8500  !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8501  result = IncompatibleObjCWeakRef;
8502  return result;
8503  }
8504 
8505  // int or null -> A*
8506  if (RHSType->isIntegerType()) {
8507  Kind = CK_IntegralToPointer; // FIXME: null
8508  return IntToPointer;
8509  }
8510 
8511  // In general, C pointers are not compatible with ObjC object pointers,
8512  // with two exceptions:
8513  if (isa<PointerType>(RHSType)) {
8514  Kind = CK_CPointerToObjCPointerCast;
8515 
8516  // - conversions from 'void*'
8517  if (RHSType->isVoidPointerType()) {
8518  return Compatible;
8519  }
8520 
8521  // - conversions to 'Class' from its redefinition type
8522  if (LHSType->isObjCClassType() &&
8523  Context.hasSameType(RHSType,
8524  Context.getObjCClassRedefinitionType())) {
8525  return Compatible;
8526  }
8527 
8528  return IncompatiblePointer;
8529  }
8530 
8531  // Only under strict condition T^ is compatible with an Objective-C pointer.
8532  if (RHSType->isBlockPointerType() &&
8533  LHSType->isBlockCompatibleObjCPointerType(Context)) {
8534  if (ConvertRHS)
8535  maybeExtendBlockObject(RHS);
8536  Kind = CK_BlockPointerToObjCPointerCast;
8537  return Compatible;
8538  }
8539 
8540  return Incompatible;
8541  }
8542 
8543  // Conversions from pointers that are not covered by the above.
8544  if (isa<PointerType>(RHSType)) {
8545  // T* -> _Bool
8546  if (LHSType == Context.BoolTy) {
8547  Kind = CK_PointerToBoolean;
8548  return Compatible;
8549  }
8550 
8551  // T* -> int
8552  if (LHSType->isIntegerType()) {
8553  Kind = CK_PointerToIntegral;
8554  return PointerToInt;
8555  }
8556 
8557  return Incompatible;
8558  }
8559 
8560  // Conversions from Objective-C pointers that are not covered by the above.
8561  if (isa<ObjCObjectPointerType>(RHSType)) {
8562  // T* -> _Bool
8563  if (LHSType == Context.BoolTy) {
8564  Kind = CK_PointerToBoolean;
8565  return Compatible;
8566  }
8567 
8568  // T* -> int
8569  if (LHSType->isIntegerType()) {
8570  Kind = CK_PointerToIntegral;
8571  return PointerToInt;
8572  }
8573 
8574  return Incompatible;
8575  }
8576 
8577  // struct A -> struct B
8578  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8579  if (Context.typesAreCompatible(LHSType, RHSType)) {
8580  Kind = CK_NoOp;
8581  return Compatible;
8582  }
8583  }
8584 
8585  if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8586  Kind = CK_IntToOCLSampler;
8587  return Compatible;
8588  }
8589 
8590  return Incompatible;
8591 }
8592 
8593 /// Constructs a transparent union from an expression that is
8594 /// used to initialize the transparent union.
8596  ExprResult &EResult, QualType UnionType,
8597  FieldDecl *Field) {
8598  // Build an initializer list that designates the appropriate member
8599  // of the transparent union.
8600  Expr *E = EResult.get();
8602  E, SourceLocation());
8603  Initializer->setType(UnionType);
8604  Initializer->setInitializedFieldInUnion(Field);
8605 
8606  // Build a compound literal constructing a value of the transparent
8607  // union type from this initializer list.
8608  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8609  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8610  VK_RValue, Initializer, false);
8611 }
8612 
8615  ExprResult &RHS) {
8616  QualType RHSType = RHS.get()->getType();
8617 
8618  // If the ArgType is a Union type, we want to handle a potential
8619  // transparent_union GCC extension.
8620  const RecordType *UT = ArgType->getAsUnionType();
8621  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8622  return Incompatible;
8623 
8624  // The field to initialize within the transparent union.
8625  RecordDecl *UD = UT->getDecl();
8626  FieldDecl *InitField = nullptr;
8627  // It's compatible if the expression matches any of the fields.
8628  for (auto *it : UD->fields()) {
8629  if (it->getType()->isPointerType()) {
8630  // If the transparent union contains a pointer type, we allow:
8631  // 1) void pointer
8632  // 2) null pointer constant
8633  if (RHSType->isPointerType())
8634  if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8635  RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8636  InitField = it;
8637  break;
8638  }
8639 
8640  if (RHS.get()->isNullPointerConstant(Context,
8642  RHS = ImpCastExprToType(RHS.get(), it->getType(),
8643  CK_NullToPointer);
8644  InitField = it;
8645  break;
8646  }
8647  }
8648 
8649  CastKind Kind;
8650  if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8651  == Compatible) {
8652  RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8653  InitField = it;
8654  break;
8655  }
8656  }
8657 
8658  if (!InitField)
8659  return Incompatible;
8660 
8661  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8662  return Compatible;
8663 }
8664 
8667  bool Diagnose,
8668  bool DiagnoseCFAudited,
8669  bool ConvertRHS) {
8670  // We need to be able to tell the caller whether we diagnosed a problem, if
8671  // they ask us to issue diagnostics.
8672  assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8673 
8674  // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8675  // we can't avoid *all* modifications at the moment, so we need some somewhere
8676  // to put the updated value.
8677  ExprResult LocalRHS = CallerRHS;
8678  ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8679 
8680  if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8681  if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8682  if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8683  !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8684  Diag(RHS.get()->getExprLoc(),
8685  diag::warn_noderef_to_dereferenceable_pointer)
8686  << RHS.get()->getSourceRange();
8687  }
8688  }
8689  }
8690 
8691  if (getLangOpts().CPlusPlus) {
8692  if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8693  // C++ 5.17p3: If the left operand is not of class type, the
8694  // expression is implicitly converted (C++ 4) to the
8695  // cv-unqualified type of the left operand.
8696  QualType RHSType = RHS.get()->getType();
8697  if (Diagnose) {
8698  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8699  AA_Assigning);
8700  } else {
8702  TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8703  /*SuppressUserConversions=*/false,
8704  /*AllowExplicit=*/false,
8705  /*InOverloadResolution=*/false,
8706  /*CStyle=*/false,
8707  /*AllowObjCWritebackConversion=*/false);
8708  if (ICS.isFailure())
8709  return Incompatible;
8710  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8711  ICS, AA_Assigning);
8712  }
8713  if (RHS.isInvalid())
8714  return Incompatible;
8715  Sema::AssignConvertType result = Compatible;
8716  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8717  !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8718  result = IncompatibleObjCWeakRef;
8719  return result;
8720  }
8721 
8722  // FIXME: Currently, we fall through and treat C++ classes like C
8723  // structures.
8724  // FIXME: We also fall through for atomics; not sure what should
8725  // happen there, though.
8726  } else if (RHS.get()->getType() == Context.OverloadTy) {
8727  // As a set of extensions to C, we support overloading on functions. These
8728  // functions need to be resolved here.
8729  DeclAccessPair DAP;
8730  if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8731  RHS.get(), LHSType, /*Complain=*/false, DAP))
8732  RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8733  else
8734  return Incompatible;
8735  }
8736 
8737  // C99 6.5.16.1p1: the left operand is a pointer and the right is
8738  // a null pointer constant.
8739  if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8740  LHSType->isBlockPointerType()) &&
8741  RHS.get()->isNullPointerConstant(Context,
8743  if (Diagnose || ConvertRHS) {
8744  CastKind Kind;
8745  CXXCastPath Path;
8746  CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8747  /*IgnoreBaseAccess=*/false, Diagnose);
8748  if (ConvertRHS)
8749  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8750  }
8751  return Compatible;
8752  }
8753 
8754  // OpenCL queue_t type assignment.
8755  if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8756  Context, Expr::NPC_ValueDependentIsNull)) {
8757  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8758  return Compatible;
8759  }
8760 
8761  // This check seems unnatural, however it is necessary to ensure the proper
8762  // conversion of functions/arrays. If the conversion were done for all
8763  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8764  // expressions that suppress this implicit conversion (&, sizeof).
8765  //
8766  // Suppress this for references: C++ 8.5.3p5.
8767  if (!LHSType->isReferenceType()) {
8768  // FIXME: We potentially allocate here even if ConvertRHS is false.
8769  RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8770  if (RHS.isInvalid())
8771  return Incompatible;
8772  }
8773  CastKind Kind;
8774  Sema::AssignConvertType result =
8775  CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8776 
8777  // C99 6.5.16.1p2: The value of the right operand is converted to the
8778  // type of the assignment expression.
8779  // CheckAssignmentConstraints allows the left-hand side to be a reference,
8780  // so that we can use references in built-in functions even in C.
8781  // The getNonReferenceType() call makes sure that the resulting expression
8782  // does not have reference type.
8783  if (result != Incompatible && RHS.get()->getType() != LHSType) {
8784  QualType Ty = LHSType.getNonLValueExprType(Context);
8785  Expr *E = RHS.get();
8786 
8787  // Check for various Objective-C errors. If we are not reporting
8788  // diagnostics and just checking for errors, e.g., during overload
8789  // resolution, return Incompatible to indicate the failure.
8790  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8791  CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8792  Diagnose, DiagnoseCFAudited) != ACR_okay) {
8793  if (!Diagnose)
8794  return Incompatible;
8795  }
8796  if (getLangOpts().ObjC &&
8797  (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8798  E->getType(), E, Diagnose) ||
8799  ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8800  if (!Diagnose)
8801  return Incompatible;
8802  // Replace the expression with a corrected version and continue so we
8803  // can find further errors.
8804  RHS = E;
8805  return Compatible;
8806  }
8807 
8808  if (ConvertRHS)
8809  RHS = ImpCastExprToType(E, Ty, Kind);
8810  }
8811 
8812  return result;
8813 }
8814 
8815 namespace {
8816 /// The original operand to an operator, prior to the application of the usual
8817 /// arithmetic conversions and converting the arguments of a builtin operator
8818 /// candidate.
8819 struct OriginalOperand {
8820  explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8821  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8822  Op = MTE->getSubExpr();
8823  if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8824  Op = BTE->getSubExpr();
8825  if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8826  Orig = ICE->getSubExprAsWritten();
8827  Conversion = ICE->getConversionFunction();
8828  }
8829  }
8830 
8831  QualType getType() const { return Orig->getType(); }
8832 
8833  Expr *Orig;
8834  NamedDecl *Conversion;
8835 };
8836 }
8837 
8839  ExprResult &RHS) {
8840  OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8841 
8842  Diag(Loc, diag::err_typecheck_invalid_operands)
8843  << OrigLHS.getType() << OrigRHS.getType()
8844  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8845 
8846  // If a user-defined conversion was applied to either of the operands prior
8847  // to applying the built-in operator rules, tell the user about it.
8848  if (OrigLHS.Conversion) {
8849  Diag(OrigLHS.Conversion->getLocation(),
8850  diag::note_typecheck_invalid_operands_converted)
8851  << 0 << LHS.get()->getType();
8852  }
8853  if (OrigRHS.Conversion) {
8854  Diag(OrigRHS.Conversion->getLocation(),
8855  diag::note_typecheck_invalid_operands_converted)
8856  << 1 << RHS.get()->getType();
8857  }
8858 
8859  return QualType();
8860 }
8861 
8862 // Diagnose cases where a scalar was implicitly converted to a vector and
8863 // diagnose the underlying types. Otherwise, diagnose the error
8864 // as invalid vector logical operands for non-C++ cases.
8866  ExprResult &RHS) {
8867  QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8868  QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8869 
8870  bool LHSNatVec = LHSType->isVectorType();
8871  bool RHSNatVec = RHSType->isVectorType();
8872 
8873  if (!(LHSNatVec && RHSNatVec)) {
8874  Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8875  Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8876  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8877  << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8878  << Vector->getSourceRange();
8879  return QualType();
8880  }
8881 
8882  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8883  << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8884  << RHS.get()->getSourceRange();
8885 
8886  return QualType();
8887 }
8888 
8889 /// Try to convert a value of non-vector type to a vector type by converting
8890 /// the type to the element type of the vector and then performing a splat.
8891 /// If the language is OpenCL, we only use conversions that promote scalar
8892 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8893 /// for float->int.
8894 ///
8895 /// OpenCL V2.0 6.2.6.p2:
8896 /// An error shall occur if any scalar operand type has greater rank
8897 /// than the type of the vector element.
8898 ///
8899 /// \param scalar - if non-null, actually perform the conversions
8900 /// \return true if the operation fails (but without diagnosing the failure)
8901 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8902  QualType scalarTy,
8903  QualType vectorEltTy,
8904  QualType vectorTy,
8905  unsigned &DiagID) {
8906  // The conversion to apply to the scalar before splatting it,
8907  // if necessary.
8908  CastKind scalarCast = CK_NoOp;
8909 
8910  if (vectorEltTy->isIntegralType(S.Context)) {
8911  if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8912  (scalarTy->isIntegerType() &&
8913  S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8914  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8915  return true;
8916  }
8917  if (!scalarTy->isIntegralType(S.Context))
8918  return true;
8919  scalarCast = CK_IntegralCast;
8920  } else if (vectorEltTy->isRealFloatingType()) {
8921  if (scalarTy->isRealFloatingType()) {
8922  if (S.getLangOpts().OpenCL &&
8923  S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8924  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8925  return true;
8926  }
8927  scalarCast = CK_FloatingCast;
8928  }
8929  else if (scalarTy->isIntegralType(S.Context))
8930  scalarCast = CK_IntegralToFloating;
8931  else
8932  return true;
8933  } else {
8934  return true;
8935  }
8936 
8937  // Adjust scalar if desired.
8938  if (scalar) {
8939  if (scalarCast != CK_NoOp)
8940  *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8941  *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8942  }
8943  return false;
8944 }
8945 
8946 /// Convert vector E to a vector with the same number of elements but different
8947 /// element type.
8948 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8949  const auto *VecTy = E->getType()->getAs<VectorType>();
8950  assert(VecTy && "Expression E must be a vector");
8951  QualType NewVecTy = S.Context.getVectorType(ElementType,
8952  VecTy->getNumElements(),
8953  VecTy->getVectorKind());
8954 
8955  // Look through the implicit cast. Return the subexpression if its type is
8956  // NewVecTy.
8957  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8958  if (ICE->getSubExpr()->getType() == NewVecTy)
8959  return ICE->getSubExpr();
8960 
8961  auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8962  return S.ImpCastExprToType(E, NewVecTy, Cast);
8963 }
8964 
8965 /// Test if a (constant) integer Int can be casted to another integer type
8966 /// IntTy without losing precision.
8968  QualType OtherIntTy) {
8969  QualType IntTy = Int->get()->getType().getUnqualifiedType();
8970 
8971  // Reject cases where the value of the Int is unknown as that would
8972  // possibly cause truncation, but accept cases where the scalar can be
8973  // demoted without loss of precision.
8974  Expr::EvalResult EVResult;
8975  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8976  int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8977  bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8978  bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8979 
8980  if (CstInt) {
8981  // If the scalar is constant and is of a higher order and has more active
8982  // bits that the vector element type, reject it.
8983  llvm::APSInt Result = EVResult.Val.getInt();
8984  unsigned NumBits = IntSigned
8985  ? (Result.isNegative() ? Result.getMinSignedBits()
8986  : Result.getActiveBits())
8987  : Result.getActiveBits();
8988  if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8989  return true;
8990 
8991  // If the signedness of the scalar type and the vector element type
8992  // differs and the number of bits is greater than that of the vector
8993  // element reject it.
8994  return (IntSigned != OtherIntSigned &&
8995  NumBits > S.Context.getIntWidth(OtherIntTy));
8996  }
8997 
8998  // Reject cases where the value of the scalar is not constant and it's
8999  // order is greater than that of the vector element type.
9000  return (Order < 0);
9001 }
9002 
9003 /// Test if a (constant) integer Int can be casted to floating point type
9004 /// FloatTy without losing precision.
9006  QualType FloatTy) {
9007  QualType IntTy = Int->get()->getType().getUnqualifiedType();
9008 
9009  // Determine if the integer constant can be expressed as a floating point
9010  // number of the appropriate type.
9011  Expr::EvalResult EVResult;
9012  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9013 
9014  uint64_t Bits = 0;
9015  if (CstInt) {
9016  // Reject constants that would be truncated if they were converted to
9017  // the floating point type. Test by simple to/from conversion.
9018  // FIXME: Ideally the conversion to an APFloat and from an APFloat
9019  // could be avoided if there was a convertFromAPInt method
9020  // which could signal back if implicit truncation occurred.
9021  llvm::APSInt Result = EVResult.Val.getInt();
9022  llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9023  Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9024  llvm::APFloat::rmTowardZero);
9025  llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9026  !IntTy->hasSignedIntegerRepresentation());
9027  bool Ignored = false;
9028  Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9029  &Ignored);
9030  if (Result != ConvertBack)
9031  return true;
9032  } else {
9033  // Reject types that cannot be fully encoded into the mantissa of
9034  // the float.
9035  Bits = S.Context.getTypeSize(IntTy);
9036  unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9037  S.Context.getFloatTypeSemantics(FloatTy));
9038  if (Bits > FloatPrec)
9039  return true;
9040  }
9041 
9042  return false;
9043 }
9044 
9045 /// Attempt to convert and splat Scalar into a vector whose types matches
9046 /// Vector following GCC conversion rules. The rule is that implicit
9047 /// conversion can occur when Scalar can be casted to match Vector's element
9048 /// type without causing truncation of Scalar.
9050  ExprResult *Vector) {
9051  QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9052  QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9053  const VectorType *VT = VectorTy->getAs<VectorType>();
9054 
9055  assert(!isa<ExtVectorType>(VT) &&
9056  "ExtVectorTypes should not be handled here!");
9057 
9058  QualType VectorEltTy = VT->getElementType();
9059 
9060  // Reject cases where the vector element type or the scalar element type are
9061  // not integral or floating point types.
9062  if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9063  return true;
9064 
9065  // The conversion to apply to the scalar before splatting it,
9066  // if necessary.
9067  CastKind ScalarCast = CK_NoOp;
9068 
9069  // Accept cases where the vector elements are integers and the scalar is
9070  // an integer.
9071  // FIXME: Notionally if the scalar was a floating point value with a precise
9072  // integral representation, we could cast it to an appropriate integer
9073  // type and then perform the rest of the checks here. GCC will perform
9074  // this conversion in some cases as determined by the input language.
9075  // We should accept it on a language independent basis.
9076  if (VectorEltTy->isIntegralType(S.Context) &&
9077  ScalarTy->isIntegralType(S.Context) &&
9078  S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9079 
9080  if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9081  return true;
9082 
9083  ScalarCast = CK_IntegralCast;
9084  } else if (VectorEltTy->isIntegralType(S.Context) &&
9085  ScalarTy->isRealFloatingType()) {
9086  if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9087  ScalarCast = CK_FloatingToIntegral;
9088  else
9089  return true;
9090  } else if (VectorEltTy->isRealFloatingType()) {
9091  if (ScalarTy->isRealFloatingType()) {
9092 
9093  // Reject cases where the scalar type is not a constant and has a higher
9094  // Order than the vector element type.
9095  llvm::APFloat Result(0.0);
9096  bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
9097  int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9098  if (!CstScalar && Order < 0)
9099  return true;
9100 
9101  // If the scalar cannot be safely casted to the vector element type,
9102  // reject it.
9103  if (CstScalar) {
9104  bool Truncated = false;
9105  Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9106  llvm::APFloat::rmNearestTiesToEven, &Truncated);
9107  if (Truncated)
9108  return true;
9109  }
9110 
9111  ScalarCast = CK_FloatingCast;
9112  } else if (ScalarTy->isIntegralType(S.Context)) {
9113  if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9114  return true;
9115 
9116  ScalarCast = CK_IntegralToFloating;
9117  } else
9118  return true;
9119  }
9120 
9121  // Adjust scalar if desired.
9122  if (Scalar) {
9123  if (ScalarCast != CK_NoOp)
9124  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9125  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9126  }
9127  return false;
9128 }
9129 
9131  SourceLocation Loc, bool IsCompAssign,
9132  bool AllowBothBool,
9133  bool AllowBoolConversions) {
9134  if (!IsCompAssign) {
9135  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9136  if (LHS.isInvalid())
9137  return QualType();
9138  }
9139  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9140  if (RHS.isInvalid())
9141  return QualType();
9142 
9143  // For conversion purposes, we ignore any qualifiers.
9144  // For example, "const float" and "float" are equivalent.
9145  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9146  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9147 
9148  const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9149  const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9150  assert(LHSVecType || RHSVecType);
9151 
9152  // AltiVec-style "vector bool op vector bool" combinations are allowed
9153  // for some operators but not others.
9154  if (!AllowBothBool &&
9155  LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9156  RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9157  return InvalidOperands(Loc, LHS, RHS);
9158 
9159  // If the vector types are identical, return.
9160  if (Context.hasSameType(LHSType, RHSType))
9161  return LHSType;
9162 
9163  // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9164  if (LHSVecType && RHSVecType &&
9165  Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9166  if (isa<ExtVectorType>(LHSVecType)) {
9167  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9168  return LHSType;
9169  }
9170 
9171  if (!IsCompAssign)
9172  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9173  return RHSType;
9174  }
9175 
9176  // AllowBoolConversions says that bool and non-bool AltiVec vectors
9177  // can be mixed, with the result being the non-bool type. The non-bool
9178  // operand must have integer element type.
9179  if (AllowBoolConversions && LHSVecType && RHSVecType &&
9180  LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9181  (Context.getTypeSize(LHSVecType->getElementType()) ==
9182  Context.getTypeSize(RHSVecType->getElementType()))) {
9183  if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9184  LHSVecType->getElementType()->isIntegerType() &&
9185  RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9186  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9187  return LHSType;
9188  }
9189  if (!IsCompAssign &&
9190  LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9191  RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9192  RHSVecType->getElementType()->isIntegerType()) {
9193  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9194  return RHSType;
9195  }
9196  }
9197 
9198  // If there's a vector type and a scalar, try to convert the scalar to
9199  // the vector element type and splat.
9200  unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9201  if (!RHSVecType) {
9202  if (isa<ExtVectorType>(LHSVecType)) {
9203  if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9204  LHSVecType->getElementType(), LHSType,
9205  DiagID))
9206  return LHSType;
9207  } else {
9208  if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9209  return LHSType;
9210  }
9211  }
9212  if (!LHSVecType) {
9213  if (isa<ExtVectorType>(RHSVecType)) {
9214  if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9215  LHSType, RHSVecType->getElementType(),
9216  RHSType, DiagID))
9217  return RHSType;
9218  } else {
9219  if (LHS.get()->getValueKind() == VK_LValue ||
9220  !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9221  return RHSType;
9222  }
9223  }
9224 
9225  // FIXME: The code below also handles conversion between vectors and
9226  // non-scalars, we should break this down into fine grained specific checks
9227  // and emit proper diagnostics.
9228  QualType VecType = LHSVecType ? LHSType : RHSType;
9229  const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9230  QualType OtherType = LHSVecType ? RHSType : LHSType;
9231  ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9232  if (isLaxVectorConversion(OtherType, VecType)) {
9233  // If we're allowing lax vector conversions, only the total (data) size
9234  // needs to be the same. For non compound assignment, if one of the types is
9235  // scalar, the result is always the vector type.
9236  if (!IsCompAssign) {
9237  *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9238  return VecType;
9239  // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9240  // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9241  // type. Note that this is already done by non-compound assignments in
9242  // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9243  // <1 x T> -> T. The result is also a vector type.
9244  } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9245  (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9246  ExprResult *RHSExpr = &RHS;
9247  *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9248  return VecType;
9249  }
9250  }
9251 
9252  // Okay, the expression is invalid.
9253 
9254  // If there's a non-vector, non-real operand, diagnose that.
9255  if ((!RHSVecType && !RHSType->isRealType()) ||
9256  (!LHSVecType && !LHSType->isRealType())) {
9257  Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9258  << LHSType << RHSType
9259  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9260  return QualType();
9261  }
9262 
9263  // OpenCL V1.1 6.2.6.p1:
9264  // If the operands are of more than one vector type, then an error shall
9265  // occur. Implicit conversions between vector types are not permitted, per
9266  // section 6.2.1.
9267  if (getLangOpts().OpenCL &&
9268  RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9269  LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9270  Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9271  << RHSType;
9272  return QualType();
9273  }
9274 
9275 
9276  // If there is a vector type that is not a ExtVector and a scalar, we reach
9277  // this point if scalar could not be converted to the vector's element type
9278  // without truncation.
9279  if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9280  (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9281  QualType Scalar = LHSVecType ? RHSType : LHSType;
9282  QualType Vector = LHSVecType ? LHSType : RHSType;
9283  unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9284  Diag(Loc,
9285  diag::err_typecheck_vector_not_convertable_implict_truncation)
9286  << ScalarOrVector << Scalar << Vector;
9287 
9288  return QualType();
9289  }
9290 
9291  // Otherwise, use the generic diagnostic.
9292  Diag(Loc, DiagID)
9293  << LHSType << RHSType
9294  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9295  return QualType();
9296 }
9297 
9298 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9299 // expression. These are mainly cases where the null pointer is used as an
9300 // integer instead of a pointer.
9301 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9302  SourceLocation Loc, bool IsCompare) {
9303  // The canonical way to check for a GNU null is with isNullPointerConstant,
9304  // but we use a bit of a hack here for speed; this is a relatively
9305  // hot path, and isNullPointerConstant is slow.
9306  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9307  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9308 
9309  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9310 
9311  // Avoid analyzing cases where the result will either be invalid (and
9312  // diagnosed as such) or entirely valid and not something to warn about.
9313  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9314  NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9315  return;
9316 
9317  // Comparison operations would not make sense with a null pointer no matter
9318  // what the other expression is.
9319  if (!IsCompare) {
9320  S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9321  << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9322  << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9323  return;
9324  }
9325 
9326  // The rest of the operations only make sense with a null pointer
9327  // if the other expression is a pointer.
9328  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9329  NonNullType->canDecayToPointerType())
9330  return;
9331 
9332  S.Diag(Loc, diag::warn_null_in_comparison_operation)
9333  << LHSNull /* LHS is NULL */ << NonNullType
9334  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9335 }
9336 
9338  SourceLocation Loc) {
9339  const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9340  const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9341  if (!LUE || !RUE)
9342  return;
9343  if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9344  RUE->getKind() != UETT_SizeOf)
9345  return;
9346 
9347  const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9348  QualType LHSTy = LHSArg->getType();
9349  QualType RHSTy;
9350 
9351  if (RUE->isArgumentType())
9352  RHSTy = RUE->getArgumentType();
9353  else
9354  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9355 
9356  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9357  if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9358  return;
9359 
9360  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9361  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9362  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9363  S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9364  << LHSArgDecl;
9365  }
9366  } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9367  QualType ArrayElemTy = ArrayTy->getElementType();
9368  if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9369  ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9370  ArrayElemTy->isCharType() ||
9371  S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9372  return;
9373  S.Diag(Loc, diag::warn_division_sizeof_array)
9374  << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9375  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9376  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9377  S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9378  << LHSArgDecl;
9379  }
9380 
9381  S.Diag(Loc, diag::note_precedence_silence) << RHS;
9382  }
9383 }
9384 
9386  ExprResult &RHS,
9387  SourceLocation Loc, bool IsDiv) {
9388  // Check for division/remainder by zero.
9389  Expr::EvalResult RHSValue;
9390  if (!RHS.get()->isValueDependent() &&
9391  RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9392  RHSValue.Val.getInt() == 0)
9393  S.DiagRuntimeBehavior(Loc, RHS.get(),
9394  S.PDiag(diag::warn_remainder_division_by_zero)
9395  << IsDiv << RHS.get()->getSourceRange());
9396 }
9397 
9399  SourceLocation Loc,
9400  bool IsCompAssign, bool IsDiv) {
9401  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9402 
9403  if (LHS.get()->getType()->isVectorType() ||
9404  RHS.get()->getType()->isVectorType())
9405  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9406  /*AllowBothBool*/getLangOpts().AltiVec,
9407  /*AllowBoolConversions*/false);
9408 
9409  QualType compType = UsualArithmeticConversions(
9410  LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9411  if (LHS.isInvalid() || RHS.isInvalid())
9412  return QualType();
9413 
9414 
9415  if (compType.isNull() || !compType->isArithmeticType())
9416  return InvalidOperands(Loc, LHS, RHS);
9417  if (IsDiv) {
9418  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9419  DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9420  }
9421  return compType;
9422 }
9423 
9425  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9426  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9427 
9428  if (LHS.get()->getType()->isVectorType() ||
9429  RHS.get()->getType()->isVectorType()) {
9430  if (LHS.get()->getType()->hasIntegerRepresentation() &&
9431  RHS.get()->getType()->hasIntegerRepresentation())
9432  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9433  /*AllowBothBool*/getLangOpts().AltiVec,
9434  /*AllowBoolConversions*/false);
9435  return InvalidOperands(Loc, LHS, RHS);
9436  }
9437 
9438  QualType compType = UsualArithmeticConversions(
9439  LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9440  if (LHS.isInvalid() || RHS.isInvalid())
9441  return QualType();
9442 
9443  if (compType.isNull() || !compType->isIntegerType())
9444  return InvalidOperands(Loc, LHS, RHS);
9445  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9446  return compType;
9447 }
9448 
9449 /// Diagnose invalid arithmetic on two void pointers.
9451  Expr *LHSExpr, Expr *RHSExpr) {
9452  S.Diag(Loc, S.getLangOpts().CPlusPlus
9453  ? diag::err_typecheck_pointer_arith_void_type
9454  : diag::ext_gnu_void_ptr)
9455  << 1 /* two pointers */ << LHSExpr->getSourceRange()
9456  << RHSExpr->getSourceRange();
9457 }
9458 
9459 /// Diagnose invalid arithmetic on a void pointer.
9461  Expr *Pointer) {
9462  S.Diag(Loc, S.getLangOpts().CPlusPlus
9463  ? diag::err_typecheck_pointer_arith_void_type
9464  : diag::ext_gnu_void_ptr)
9465  << 0 /* one pointer */ << Pointer->getSourceRange();
9466 }
9467 
9468 /// Diagnose invalid arithmetic on a null pointer.
9469 ///
9470 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9471 /// idiom, which we recognize as a GNU extension.
9472 ///
9474  Expr *Pointer, bool IsGNUIdiom) {
9475  if (IsGNUIdiom)
9476  S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9477  << Pointer->getSourceRange();
9478  else
9479  S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9480  << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9481 }
9482 
9483 /// Diagnose invalid arithmetic on two function pointers.
9485  Expr *LHS, Expr *RHS) {
9486  assert(LHS->getType()->isAnyPointerType());
9487  assert(RHS->getType()->isAnyPointerType());
9488  S.Diag(Loc, S.getLangOpts().CPlusPlus
9489  ? diag::err_typecheck_pointer_arith_function_type
9490  : diag::ext_gnu_ptr_func_arith)
9491  << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9492  // We only show the second type if it differs from the first.
9493  << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9494  RHS->getType())
9495  << RHS->getType()->getPointeeType()
9496  << LHS->getSourceRange() << RHS->getSourceRange();
9497 }
9498 
9499 /// Diagnose invalid arithmetic on a function pointer.
9501  Expr *Pointer) {
9502  assert(Pointer->getType()->isAnyPointerType());
9503  S.Diag(Loc, S.getLangOpts().CPlusPlus
9504  ? diag::err_typecheck_pointer_arith_function_type
9505  : diag::ext_gnu_ptr_func_arith)
9506  << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9507  << 0 /* one pointer, so only one type */
9508  << Pointer->getSourceRange();
9509 }
9510 
9511 /// Emit error if Operand is incomplete pointer type
9512 ///
9513 /// \returns True if pointer has incomplete type
9515  Expr *Operand) {
9516  QualType ResType = Operand->getType();
9517  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9518  ResType = ResAtomicType->getValueType();
9519 
9520  assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9521  QualType PointeeTy = ResType->getPointeeType();
9522  return S.RequireCompleteType(Loc, PointeeTy,
9523  diag::err_typecheck_arithmetic_incomplete_type,
9524  PointeeTy, Operand->getSourceRange());
9525 }
9526 
9527 /// Check the validity of an arithmetic pointer operand.
9528 ///
9529 /// If the operand has pointer type, this code will check for pointer types
9530 /// which are invalid in arithmetic operations. These will be diagnosed
9531 /// appropriately, including whether or not the use is supported as an
9532 /// extension.
9533 ///
9534 /// \returns True when the operand is valid to use (even if as an extension).
9536  Expr *Operand) {
9537  QualType ResType = Operand->getType();
9538  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9539  ResType = ResAtomicType->getValueType();
9540 
9541  if (!ResType->isAnyPointerType()) return true;
9542 
9543  QualType PointeeTy = ResType->getPointeeType();
9544  if (PointeeTy->isVoidType()) {
9545  diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9546  return !S.getLangOpts().CPlusPlus;
9547  }
9548  if (PointeeTy->isFunctionType()) {
9549  diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9550  return !S.getLangOpts().CPlusPlus;
9551  }
9552 
9553  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9554 
9555  return true;
9556 }
9557 
9558 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9559 /// operands.
9560 ///
9561 /// This routine will diagnose any invalid arithmetic on pointer operands much
9562 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9563 /// for emitting a single diagnostic even for operations where both LHS and RHS
9564 /// are (potentially problematic) pointers.
9565 ///
9566 /// \returns True when the operand is valid to use (even if as an extension).
9568  Expr *LHSExpr, Expr *RHSExpr) {
9569  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9570  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9571  if (!isLHSPointer && !isRHSPointer) return true;
9572 
9573  QualType LHSPointeeTy, RHSPointeeTy;
9574  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9575  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9576 
9577  // if both are pointers check if operation is valid wrt address spaces
9578  if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9579  const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9580  const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9581  if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9582  S.Diag(Loc,
9583  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9584  << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9585  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9586  return false;
9587  }
9588  }
9589 
9590  // Check for arithmetic on pointers to incomplete types.
9591  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9592  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9593  if (isLHSVoidPtr || isRHSVoidPtr) {
9594  if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9595  else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9596  else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9597 
9598  return !S.getLangOpts().CPlusPlus;
9599  }
9600 
9601  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9602  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9603  if (isLHSFuncPtr || isRHSFuncPtr) {
9604  if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9605  else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9606  RHSExpr);
9607  else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9608 
9609  return !S.getLangOpts().CPlusPlus;
9610  }
9611 
9612  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9613  return false;
9614  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9615  return false;
9616 
9617  return true;
9618 }
9619 
9620 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9621 /// literal.
9622 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9623  Expr *LHSExpr, Expr *RHSExpr) {
9624  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9625  Expr* IndexExpr = RHSExpr;
9626  if (!StrExpr) {
9627  StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9628  IndexExpr = LHSExpr;
9629  }
9630 
9631  bool IsStringPlusInt = StrExpr &&
9633  if (!IsStringPlusInt || IndexExpr->isValueDependent())
9634  return;
9635 
9636  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9637  Self.Diag(OpLoc, diag::warn_string_plus_int)
9638  << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9639 
9640  // Only print a fixit for "str" + int, not for int + "str".
9641  if (IndexExpr == RHSExpr) {
9642  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9643  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9644  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9646  << FixItHint::CreateInsertion(EndLoc, "]");
9647  } else
9648  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9649 }
9650 
9651 /// Emit a warning when adding a char literal to a string.
9652 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9653  Expr *LHSExpr, Expr *RHSExpr) {
9654  const Expr *StringRefExpr = LHSExpr;
9655  const CharacterLiteral *CharExpr =
9656  dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9657 
9658  if (!CharExpr) {
9659  CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9660  StringRefExpr = RHSExpr;
9661  }
9662 
9663  if (!CharExpr || !StringRefExpr)
9664  return;
9665 
9666  const QualType StringType = StringRefExpr->getType();
9667 
9668  // Return if not a PointerType.
9669  if (!StringType->isAnyPointerType())
9670  return;
9671 
9672  // Return if not a CharacterType.
9673  if (!StringType->getPointeeType()->isAnyCharacterType())
9674  return;
9675 
9676  ASTContext &Ctx = Self.getASTContext();
9677  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9678 
9679  const QualType CharType = CharExpr->getType();
9680  if (!CharType->isAnyCharacterType() &&
9681  CharType->isIntegerType() &&
9682  llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9683  Self.Diag(OpLoc, diag::warn_string_plus_char)
9684  << DiagRange << Ctx.CharTy;
9685  } else {
9686  Self.Diag(OpLoc, diag::warn_string_plus_char)
9687  << DiagRange << CharExpr->getType();
9688  }
9689 
9690  // Only print a fixit for str + char, not for char + str.
9691  if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9692  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9693  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9694  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9696  << FixItHint::CreateInsertion(EndLoc, "]");
9697  } else {
9698  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9699  }
9700 }
9701 
9702 /// Emit error when two pointers are incompatible.
9704  Expr *LHSExpr, Expr *RHSExpr) {
9705  assert(LHSExpr->getType()->isAnyPointerType());
9706  assert(RHSExpr->getType()->isAnyPointerType());
9707  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9708  << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9709  << RHSExpr->getSourceRange();
9710 }
9711 
9712 // C99 6.5.6
9715  QualType* CompLHSTy) {
9716  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9717 
9718  if (LHS.get()->getType()->isVectorType() ||
9719  RHS.get()->getType()->isVectorType()) {
9720  QualType compType = CheckVectorOperands(
9721  LHS, RHS, Loc, CompLHSTy,
9722  /*AllowBothBool*/getLangOpts().AltiVec,
9723  /*AllowBoolConversions*/getLangOpts().ZVector);
9724  if (CompLHSTy) *CompLHSTy = compType;
9725  return compType;
9726  }
9727 
9728  QualType compType = UsualArithmeticConversions(
9729  LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9730  if (LHS.isInvalid() || RHS.isInvalid())
9731  return QualType();
9732 
9733  // Diagnose "string literal" '+' int and string '+' "char literal".
9734  if (Opc == BO_Add) {
9735  diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9736  diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9737  }
9738 
9739  // handle the common case first (both operands are arithmetic).
9740  if (!compType.isNull() && compType->isArithmeticType()) {
9741  if (CompLHSTy) *CompLHSTy = compType;
9742  return compType;
9743  }
9744 
9745  // Type-checking. Ultimately the pointer's going to be in PExp;
9746  // note that we bias towards the LHS being the pointer.
9747  Expr *PExp = LHS.get(), *IExp = RHS.get();
9748 
9749  bool isObjCPointer;
9750  if (PExp->getType()->isPointerType()) {
9751  isObjCPointer = false;
9752  } else if (PExp->getType()->isObjCObjectPointerType()) {
9753  isObjCPointer = true;
9754  } else {
9755  std::swap(PExp, IExp);
9756  if (PExp->getType()->isPointerType()) {
9757  isObjCPointer = false;
9758  } else if (PExp->getType()->isObjCObjectPointerType()) {
9759  isObjCPointer = true;
9760  } else {
9761  return InvalidOperands(Loc, LHS, RHS);
9762  }
9763  }
9764  assert(PExp->getType()->isAnyPointerType());
9765 
9766  if (!IExp->getType()->isIntegerType())
9767  return InvalidOperands(Loc, LHS, RHS);
9768 
9769  // Adding to a null pointer results in undefined behavior.
9772  // In C++ adding zero to a null pointer is defined.
9773  Expr::EvalResult KnownVal;
9774  if (!getLangOpts().CPlusPlus ||
9775  (!IExp->isValueDependent() &&
9776  (!IExp->EvaluateAsInt(KnownVal, Context) ||
9777  KnownVal.Val.getInt() != 0))) {
9778  // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9780  Context, BO_Add, PExp, IExp);
9781  diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9782  }
9783  }
9784 
9785  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9786  return QualType();
9787 
9788  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9789  return QualType();
9790 
9791  // Check array bounds for pointer arithemtic
9792  CheckArrayAccess(PExp, IExp);
9793 
9794  if (CompLHSTy) {
9795  QualType LHSTy = Context.isPromotableBitField(LHS.get());
9796  if (LHSTy.isNull()) {
9797  LHSTy = LHS.get()->getType();
9798  if (LHSTy->isPromotableIntegerType())
9799  LHSTy = Context.getPromotedIntegerType(LHSTy);
9800  }
9801  *CompLHSTy = LHSTy;
9802  }
9803 
9804  return PExp->getType();
9805 }
9806 
9807 // C99 6.5.6
9809  SourceLocation Loc,
9810  QualType* CompLHSTy) {
9811  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9812 
9813  if (LHS.get()->getType()->isVectorType() ||
9814  RHS.get()->getType()->isVectorType()) {
9815  QualType compType = CheckVectorOperands(
9816  LHS, RHS, Loc, CompLHSTy,
9817  /*AllowBothBool*/getLangOpts().AltiVec,
9818  /*AllowBoolConversions*/getLangOpts().ZVector);
9819  if (CompLHSTy) *CompLHSTy = compType;
9820  return compType;
9821  }
9822 
9823  QualType compType = UsualArithmeticConversions(
9824  LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9825  if (LHS.isInvalid() || RHS.isInvalid())
9826  return QualType();
9827 
9828  // Enforce type constraints: C99 6.5.6p3.
9829 
9830  // Handle the common case first (both operands are arithmetic).
9831  if (!compType.isNull() && compType->isArithmeticType()) {
9832  if (CompLHSTy) *CompLHSTy = compType;
9833  return compType;
9834  }
9835 
9836  // Either ptr - int or ptr - ptr.
9837  if (LHS.get()->getType()->isAnyPointerType()) {
9838  QualType lpointee = LHS.get()->getType()->getPointeeType();
9839 
9840  // Diagnose bad cases where we step over interface counts.
9841  if (LHS.get()->getType()->isObjCObjectPointerType() &&
9842  checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9843  return QualType();
9844 
9845  // The result type of a pointer-int computation is the pointer type.
9846  if (RHS.get()->getType()->isIntegerType()) {
9847  // Subtracting from a null pointer should produce a warning.
9848  // The last argument to the diagnose call says this doesn't match the
9849  // GNU int-to-pointer idiom.
9850  if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9852  // In C++ adding zero to a null pointer is defined.
9853  Expr::EvalResult KnownVal;
9854  if (!getLangOpts().CPlusPlus ||
9855  (!RHS.get()->isValueDependent() &&
9856  (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9857  KnownVal.Val.getInt() != 0))) {
9858  diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9859  }
9860  }
9861 
9862  if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9863  return QualType();
9864 
9865  // Check array bounds for pointer arithemtic
9866  CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9867  /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9868 
9869  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9870  return LHS.get()->getType();
9871  }
9872 
9873  // Handle pointer-pointer subtractions.
9874  if (const PointerType *RHSPTy
9875  = RHS.get()->getType()->getAs<PointerType>()) {
9876  QualType rpointee = RHSPTy->getPointeeType();
9877 
9878  if (getLangOpts().CPlusPlus) {
9879  // Pointee types must be the same: C++ [expr.add]
9880  if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9881  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9882  }
9883  } else {
9884  // Pointee types must be compatible C99 6.5.6p3
9885  if (!Context.typesAreCompatible(
9886  Context.getCanonicalType(lpointee).getUnqualifiedType(),
9887  Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9888  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9889  return QualType();
9890  }
9891  }
9892 
9893  if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9894  LHS.get(), RHS.get()))
9895  return QualType();
9896 
9897  // FIXME: Add warnings for nullptr - ptr.
9898 
9899  // The pointee type may have zero size. As an extension, a structure or
9900  // union may have zero size or an array may have zero length. In this
9901  // case subtraction does not make sense.
9902  if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9903  CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9904  if (ElementSize.isZero()) {
9905  Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9906  << rpointee.getUnqualifiedType()
9907  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9908  }
9909  }
9910 
9911  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9912  return Context.getPointerDiffType();
9913  }
9914  }
9915 
9916  return InvalidOperands(Loc, LHS, RHS);
9917 }
9918 
9920  if (const EnumType *ET = T->getAs<EnumType>())
9921  return ET->getDecl()->isScoped();
9922  return false;
9923 }
9924 
9927  QualType LHSType) {
9928  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9929  // so skip remaining warnings as we don't want to modify values within Sema.
9930  if (S.getLangOpts().OpenCL)
9931  return;
9932 
9933  // Check right/shifter operand
9934  Expr::EvalResult RHSResult;
9935  if (RHS.get()->isValueDependent() ||
9936  !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9937  return;
9938  llvm::APSInt Right = RHSResult.Val.getInt();
9939 
9940  if (Right.isNegative()) {
9941  S.DiagRuntimeBehavior(Loc, RHS.get(),
9942  S.PDiag(diag::warn_shift_negative)
9943  << RHS.get()->getSourceRange());
9944  return;
9945  }
9946  llvm::APInt LeftBits(Right.getBitWidth(),
9947  S.Context.getTypeSize(LHS.get()->getType()));
9948  if (Right.uge(LeftBits)) {
9949  S.DiagRuntimeBehavior(Loc, RHS.get(),
9950  S.PDiag(diag::warn_shift_gt_typewidth)
9951  << RHS.get()->getSourceRange());
9952  return;
9953  }
9954  if (Opc != BO_Shl)
9955  return;
9956 
9957  // When left shifting an ICE which is signed, we can check for overflow which
9958  // according to C++ standards prior to C++2a has undefined behavior
9959  // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9960  // more than the maximum value representable in the result type, so never
9961  // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9962  // expression is still probably a bug.)
9963  Expr::EvalResult LHSResult;
9964  if (LHS.get()->isValueDependent() ||
9965  LHSType->hasUnsignedIntegerRepresentation() ||
9966  !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9967  return;
9968  llvm::APSInt Left = LHSResult.Val.getInt();
9969 
9970  // If LHS does not have a signed type and non-negative value
9971  // then, the behavior is undefined before C++2a. Warn about it.
9972  if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9973  !S.getLangOpts().CPlusPlus2a) {
9974  S.DiagRuntimeBehavior(Loc, LHS.get(),
9975  S.PDiag(diag::warn_shift_lhs_negative)
9976  << LHS.get()->getSourceRange());
9977  return;
9978  }
9979 
9980  llvm::APInt ResultBits =
9981  static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9982  if (LeftBits.uge(ResultBits))
9983  return;
9984  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9985  Result = Result.shl(Right);
9986 
9987  // Print the bit representation of the signed integer as an unsigned
9988  // hexadecimal number.
9989  SmallString<40> HexResult;
9990  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9991 
9992  // If we are only missing a sign bit, this is less likely to result in actual
9993  // bugs -- if the result is cast back to an unsigned type, it will have the
9994  // expected value. Thus we place this behind a different warning that can be
9995  // turned off separately if needed.
9996  if (LeftBits == ResultBits - 1) {
9997  S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9998  << HexResult << LHSType
9999  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10000  return;
10001  }
10002 
10003  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10004  << HexResult.str() << Result.getMinSignedBits() << LHSType
10005  << Left.getBitWidth() << LHS.get()->getSourceRange()
10006  << RHS.get()->getSourceRange();
10007 }
10008 
10009 /// Return the resulting type when a vector is shifted
10010 /// by a scalar or vector shift amount.
10012  SourceLocation Loc, bool IsCompAssign) {
10013  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10014  if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10015  !LHS.get()->getType()->isVectorType()) {
10016  S.Diag(Loc, diag::err_shift_rhs_only_vector)
10017  << RHS.get()->getType() << LHS.get()->getType()
10018  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10019  return QualType();
10020  }
10021 
10022  if (!IsCompAssign) {
10023  LHS = S.UsualUnaryConversions(LHS.get());
10024  if (LHS.isInvalid()) return QualType();
10025  }
10026 
10027  RHS = S.UsualUnaryConversions(RHS.get());
10028  if (RHS.isInvalid()) return QualType();
10029 
10030  QualType LHSType = LHS.get()->getType();
10031  // Note that LHS might be a scalar because the routine calls not only in
10032  // OpenCL case.
10033  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10034  QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10035 
10036  // Note that RHS might not be a vector.
10037  QualType RHSType = RHS.get()->getType();
10038  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10039  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10040 
10041  // The operands need to be integers.
10042  if (!LHSEleType->isIntegerType()) {
10043  S.Diag(Loc, diag::err_typecheck_expect_int)
10044  << LHS.get()->getType() << LHS.get()->getSourceRange();
10045  return QualType();
10046  }
10047 
10048  if (!RHSEleType->isIntegerType()) {
10049  S.Diag(Loc, diag::err_typecheck_expect_int)
10050  << RHS.get()->getType() << RHS.get()->getSourceRange();
10051  return QualType();
10052  }
10053 
10054  if (!LHSVecTy) {
10055  assert(RHSVecTy);
10056  if (IsCompAssign)
10057  return RHSType;
10058  if (LHSEleType != RHSEleType) {
10059  LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10060  LHSEleType = RHSEleType;
10061  }
10062  QualType VecTy =
10063  S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10064  LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10065  LHSType = VecTy;
10066  } else if (RHSVecTy) {
10067  // OpenCL v1.1 s6.3.j says that for vector types, the operators
10068  // are applied component-wise. So if RHS is a vector, then ensure
10069  // that the number of elements is the same as LHS...
10070  if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10071  S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10072  << LHS.get()->getType() << RHS.get()->getType()
10073  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10074  return QualType();
10075  }
10076  if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10077  const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10078  const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10079  if (LHSBT != RHSBT &&
10080  S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10081  S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10082  << LHS.get()->getType() << RHS.get()->getType()
10083  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10084  }
10085  }
10086  } else {
10087  // ...else expand RHS to match the number of elements in LHS.
10088  QualType VecTy =
10089  S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10090  RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10091  }
10092 
10093  return LHSType;
10094 }
10095 
10096 // C99 6.5.7
10099  bool IsCompAssign) {
10100  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10101 
10102  // Vector shifts promote their scalar inputs to vector type.
10103  if (LHS.get()->getType()->isVectorType() ||
10104  RHS.get()->getType()->isVectorType()) {
10105  if (LangOpts.ZVector) {
10106  // The shift operators for the z vector extensions work basically
10107  // like general shifts, except that neither the LHS nor the RHS is
10108  // allowed to be a "vector bool".
10109  if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10110  if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10111  return InvalidOperands(Loc, LHS, RHS);
10112  if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10113  if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10114  return InvalidOperands(Loc, LHS, RHS);
10115  }
10116  return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10117  }
10118 
10119  // Shifts don't perform usual arithmetic conversions, they just do integer
10120  // promotions on each operand. C99 6.5.7p3
10121 
10122  // For the LHS, do usual unary conversions, but then reset them away
10123  // if this is a compound assignment.
10124  ExprResult OldLHS = LHS;
10125  LHS = UsualUnaryConversions(LHS.get());
10126  if (LHS.isInvalid())
10127  return QualType();
10128  QualType LHSType = LHS.get()->getType();
10129  if (IsCompAssign) LHS = OldLHS;
10130 
10131  // The RHS is simpler.
10132  RHS = UsualUnaryConversions(RHS.get());
10133  if (RHS.isInvalid())
10134  return QualType();
10135  QualType RHSType = RHS.get()->getType();
10136 
10137  // C99 6.5.7p2: Each of the operands shall have integer type.
10138  if (!LHSType->hasIntegerRepresentation() ||
10139  !RHSType->hasIntegerRepresentation())
10140  return InvalidOperands(Loc, LHS, RHS);
10141 
10142  // C++0x: Don't allow scoped enums. FIXME: Use something better than
10143  // hasIntegerRepresentation() above instead of this.
10144  if (isScopedEnumerationType(LHSType) ||
10145  isScopedEnumerationType(RHSType)) {
10146  return InvalidOperands(Loc, LHS, RHS);
10147  }
10148  // Sanity-check shift operands
10149  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10150 
10151  // "The type of the result is that of the promoted left operand."
10152  return LHSType;
10153 }
10154 
10155 /// Diagnose bad pointer comparisons.
10157  ExprResult &LHS, ExprResult &RHS,
10158  bool IsError) {
10159  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10160  : diag::ext_typecheck_comparison_of_distinct_pointers)
10161  << LHS.get()->getType() << RHS.get()->getType()
10162  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10163 }
10164 
10165 /// Returns false if the pointers are converted to a composite type,
10166 /// true otherwise.
10168  ExprResult &LHS, ExprResult &RHS) {
10169  // C++ [expr.rel]p2:
10170  // [...] Pointer conversions (4.10) and qualification
10171  // conversions (4.4) are performed on pointer operands (or on
10172  // a pointer operand and a null pointer constant) to bring
10173  // them to their composite pointer type. [...]
10174  //
10175  // C++ [expr.eq]p1 uses the same notion for (in)equality
10176  // comparisons of pointers.
10177 
10178  QualType LHSType = LHS.get()->getType();
10179  QualType RHSType = RHS.get()->getType();
10180  assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10181  LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10182 
10183  QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10184  if (T.isNull()) {
10185  if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10186  (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10187  diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10188  else
10189  S.InvalidOperands(Loc, LHS, RHS);
10190  return true;
10191  }
10192 
10193  return false;
10194 }
10195 
10197  ExprResult &LHS,
10198  ExprResult &RHS,
10199  bool IsError) {
10200  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10201  : diag::ext_typecheck_comparison_of_fptr_to_void)
10202  << LHS.get()->getType() << RHS.get()->getType()
10203  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10204 }
10205 
10207  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10208  case Stmt::ObjCArrayLiteralClass:
10209  case Stmt::ObjCDictionaryLiteralClass:
10210  case Stmt::ObjCStringLiteralClass:
10211  case Stmt::ObjCBoxedExprClass:
10212  return true;
10213  default:
10214  // Note that ObjCBoolLiteral is NOT an object literal!
10215  return false;
10216  }
10217 }
10218 
10219 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10220  const ObjCObjectPointerType *Type =
10221  LHS->getType()->getAs<ObjCObjectPointerType>();
10222 
10223  // If this is not actually an Objective-C object, bail out.
10224  if (!Type)
10225  return false;
10226 
10227  // Get the LHS object's interface type.
10228  QualType InterfaceType = Type->getPointeeType();
10229 
10230  // If the RHS isn't an Objective-C object, bail out.
10231  if (!RHS->getType()->isObjCObjectPointerType())
10232  return false;
10233 
10234  // Try to find the -isEqual: method.
10235  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10236  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10237  InterfaceType,
10238  /*IsInstance=*/true);
10239  if (!Method) {
10240  if (Type->isObjCIdType()) {
10241  // For 'id', just check the global pool.
10242  Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10243  /*receiverId=*/true);
10244  } else {
10245  // Check protocols.
10246  Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10247  /*IsInstance=*/true);
10248  }
10249  }
10250 
10251  if (!Method)
10252  return false;
10253 
10254  QualType T = Method->parameters()[0]->getType();
10255  if (!T->isObjCObjectPointerType())
10256  return false;
10257 
10258  QualType R = Method->getReturnType();
10259  if (!R->isScalarType())
10260  return false;
10261 
10262  return true;
10263 }
10264 
10266  FromE = FromE->IgnoreParenImpCasts();
10267  switch (FromE->getStmtClass()) {
10268  default:
10269  break;
10270  case Stmt::ObjCStringLiteralClass:
10271  // "string literal"
10272  return LK_String;
10273  case Stmt::ObjCArrayLiteralClass:
10274  // "array literal"
10275  return LK_Array;
10276  case Stmt::ObjCDictionaryLiteralClass:
10277  // "dictionary literal"
10278  return LK_Dictionary;
10279  case Stmt::BlockExprClass:
10280  return LK_Block;
10281  case Stmt::ObjCBoxedExprClass: {
10282  Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10283  switch (Inner->getStmtClass()) {
10284  case Stmt::IntegerLiteralClass:
10285  case Stmt::FloatingLiteralClass:
10286  case Stmt::CharacterLiteralClass:
10287  case Stmt::ObjCBoolLiteralExprClass:
10288  case Stmt::CXXBoolLiteralExprClass:
10289  // "numeric literal"
10290  return LK_Numeric;
10291  case Stmt::ImplicitCastExprClass: {
10292  CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10293  // Boolean literals can be represented by implicit casts.
10294  if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10295  return LK_Numeric;
10296  break;
10297  }
10298  default:
10299  break;
10300  }
10301  return LK_Boxed;
10302  }
10303  }
10304  return LK_None;
10305 }
10306 
10308  ExprResult &LHS, ExprResult &RHS,
10310  Expr *Literal;
10311  Expr *Other;
10312  if (isObjCObjectLiteral(LHS)) {
10313  Literal = LHS.get();
10314  Other = RHS.get();
10315  } else {
10316  Literal = RHS.get();
10317  Other = LHS.get();
10318  }
10319 
10320  // Don't warn on comparisons against nil.
10321  Other = Other->IgnoreParenCasts();
10322  if (Other->isNullPointerConstant(S.getASTContext(),
10324  return;
10325 
10326  // This should be kept in sync with warn_objc_literal_comparison.
10327  // LK_String should always be after the other literals, since it has its own
10328  // warning flag.
10329  Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10330  assert(LiteralKind != Sema::LK_Block);
10331  if (LiteralKind == Sema::LK_None) {
10332  llvm_unreachable("Unknown Objective-C object literal kind");
10333  }
10334 
10335  if (LiteralKind == Sema::LK_String)
10336  S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10337  << Literal->getSourceRange();
10338  else
10339  S.Diag(Loc, diag::warn_objc_literal_comparison)
10340  << LiteralKind << Literal->getSourceRange();
10341 
10342  if (BinaryOperator::isEqualityOp(Opc) &&
10343  hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10344  SourceLocation Start = LHS.get()->getBeginLoc();
10345  SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10346  CharSourceRange OpRange =
10348 
10349  S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10350  << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10351  << FixItHint::CreateReplacement(OpRange, " isEqual:")
10352  << FixItHint::CreateInsertion(End, "]");
10353  }
10354 }
10355 
10356 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10358  ExprResult &RHS, SourceLocation Loc,
10359  BinaryOperatorKind Opc) {
10360  // Check that left hand side is !something.
10361  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10362  if (!UO || UO->getOpcode() != UO_LNot) return;
10363 
10364  // Only check if the right hand side is non-bool arithmetic type.
10365  if (RHS.get()->isKnownToHaveBooleanValue()) return;
10366 
10367  // Make sure that the something in !something is not bool.
10368  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10369  if (SubExpr->isKnownToHaveBooleanValue()) return;
10370 
10371  // Emit warning.
10372  bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10373  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10374  << Loc << IsBitwiseOp;
10375 
10376  // First note suggest !(x < y)
10377  SourceLocation FirstOpen = SubExpr->getBeginLoc();
10378  SourceLocation FirstClose = RHS.get()->getEndLoc();
10379  FirstClose = S.getLocForEndOfToken(FirstClose);
10380  if (FirstClose.isInvalid())
10381  FirstOpen = SourceLocation();
10382  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10383  << IsBitwiseOp
10384  << FixItHint::CreateInsertion(FirstOpen, "(")
10385  << FixItHint::CreateInsertion(FirstClose, ")");
10386 
10387  // Second note suggests (!x) < y
10388  SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10389  SourceLocation SecondClose = LHS.get()->getEndLoc();
10390  SecondClose = S.getLocForEndOfToken(SecondClose);
10391  if (SecondClose.isInvalid())
10392  SecondOpen = SourceLocation();
10393  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10394  << FixItHint::CreateInsertion(SecondOpen, "(")
10395  << FixItHint::CreateInsertion(SecondClose, ")");
10396 }
10397 
10398 // Returns true if E refers to a non-weak array.
10399 static bool checkForArray(const Expr *E) {
10400  const ValueDecl *D = nullptr;
10401  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10402  D = DR->getDecl();
10403  } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10404  if (Mem->isImplicitAccess())
10405  D = Mem->getMemberDecl();
10406  }
10407  if (!D)
10408  return false;
10409  return D->getType()->isArrayType() && !D->isWeak();
10410 }
10411 
10412 /// Diagnose some forms of syntactically-obvious tautological comparison.
10414  Expr *LHS, Expr *RHS,
10415  BinaryOperatorKind Opc) {
10416  Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10417  Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10418 
10419  QualType LHSType = LHS->getType();
10420  QualType RHSType = RHS->getType();
10421  if (LHSType->hasFloatingRepresentation() ||
10422  (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10424  return;
10425 
10426  // Comparisons between two array types are ill-formed for operator<=>, so
10427  // we shouldn't emit any additional warnings about it.
10428  if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10429  return;
10430 
10431  // For non-floating point types, check for self-comparisons of the form
10432  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10433  // often indicate logic errors in the program.
10434  //
10435  // NOTE: Don't warn about comparison expressions resulting from macro
10436  // expansion. Also don't warn about comparisons which are only self
10437  // comparisons within a template instantiation. The warnings should catch
10438  // obvious cases in the definition of the template anyways. The idea is to
10439  // warn when the typed comparison operator will always evaluate to the same
10440  // result.
10441 
10442  // Used for indexing into %select in warn_comparison_always
10443  enum {
10444  AlwaysConstant,
10445  AlwaysTrue,
10446  AlwaysFalse,
10447  AlwaysEqual, // std::strong_ordering::equal from operator<=>
10448  };
10449 
10450  // C++2a [depr.array.comp]:
10451  // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10452  // operands of array type are deprecated.
10453  if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10454  RHSStripped->getType()->isArrayType()) {
10455  S.Diag(Loc, diag::warn_depr_array_comparison)
10456  << LHS->getSourceRange() << RHS->getSourceRange()
10457  << LHSStripped->getType() << RHSStripped->getType();
10458  // Carry on to produce the tautological comparison warning, if this
10459  // expression is potentially-evaluated, we can resolve the array to a
10460  // non-weak declaration, and so on.
10461  }
10462 
10463  if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10464  if (Expr::isSameComparisonOperand(LHS, RHS)) {
10465  unsigned Result;
10466  switch (Opc) {
10467  case BO_EQ:
10468  case BO_LE:
10469  case BO_GE:
10470  Result = AlwaysTrue;
10471  break;
10472  case BO_NE:
10473  case BO_LT:
10474  case BO_GT:
10475  Result = AlwaysFalse;
10476  break;
10477  case BO_Cmp:
10478  Result = AlwaysEqual;
10479  break;
10480  default:
10481  Result = AlwaysConstant;
10482  break;
10483  }
10484  S.DiagRuntimeBehavior(Loc, nullptr,
10485  S.PDiag(diag::warn_comparison_always)
10486  << 0 /*self-comparison*/
10487  << Result);
10488  } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10489  // What is it always going to evaluate to?
10490  unsigned Result;
10491  switch (Opc) {
10492  case BO_EQ: // e.g. array1 == array2
10493  Result = AlwaysFalse;
10494  break;
10495  case BO_NE: // e.g. array1 != array2
10496  Result = AlwaysTrue;
10497  break;
10498  default: // e.g. array1 <= array2
10499  // The best we can say is 'a constant'
10500  Result = AlwaysConstant;
10501  break;
10502  }
10503  S.DiagRuntimeBehavior(Loc, nullptr,
10504  S.PDiag(diag::warn_comparison_always)
10505  << 1 /*array comparison*/
10506  << Result);
10507  }
10508  }
10509 
10510  if (isa<CastExpr>(LHSStripped))
10511  LHSStripped = LHSStripped->IgnoreParenCasts();
10512  if (isa<CastExpr>(RHSStripped))
10513  RHSStripped = RHSStripped->IgnoreParenCasts();
10514 
10515  // Warn about comparisons against a string constant (unless the other
10516  // operand is null); the user probably wants string comparison function.
10517  Expr *LiteralString = nullptr;
10518  Expr *LiteralStringStripped = nullptr;
10519  if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10520  !RHSStripped->isNullPointerConstant(S.Context,
10522  LiteralString = LHS;
10523  LiteralStringStripped = LHSStripped;
10524  } else if ((isa<StringLiteral>(RHSStripped) ||
10525  isa<ObjCEncodeExpr>(RHSStripped)) &&
10526  !LHSStripped->isNullPointerConstant(S.Context,
10528  LiteralString = RHS;
10529  LiteralStringStripped = RHSStripped;
10530  }
10531 
10532  if (LiteralString) {
10533  S.DiagRuntimeBehavior(Loc, nullptr,
10534  S.PDiag(diag::warn_stringcompare)
10535  << isa<ObjCEncodeExpr>(LiteralStringStripped)
10536  << LiteralString->getSourceRange());
10537  }
10538 }
10539 
10541  switch (CK) {
10542  default: {
10543 #ifndef NDEBUG
10544  llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10545  << "\n";
10546 #endif
10547  llvm_unreachable("unhandled cast kind");
10548  }
10549  case CK_UserDefinedConversion:
10550  return ICK_Identity;
10551  case CK_LValueToRValue:
10552  return ICK_Lvalue_To_Rvalue;
10553  case CK_ArrayToPointerDecay:
10554  return ICK_Array_To_Pointer;
10555  case CK_FunctionToPointerDecay:
10556  return ICK_Function_To_Pointer;
10557  case CK_IntegralCast:
10558  return ICK_Integral_Conversion;
10559  case CK_FloatingCast:
10560  return ICK_Floating_Conversion;
10561  case CK_IntegralToFloating:
10562  case CK_FloatingToIntegral:
10563  return ICK_Floating_Integral;
10564  case CK_IntegralComplexCast:
10565  case CK_FloatingComplexCast:
10566  case CK_FloatingComplexToIntegralComplex:
10567  case CK_IntegralComplexToFloatingComplex:
10568  return ICK_Complex_Conversion;
10569  case CK_FloatingComplexToReal:
10570  case CK_FloatingRealToComplex:
10571  case CK_IntegralComplexToReal:
10572  case CK_IntegralRealToComplex:
10573  return ICK_Complex_Real;
10574  }
10575 }
10576 
10578  QualType FromType,
10579  SourceLocation Loc) {
10580  // Check for a narrowing implicit conversion.
10583  SCS.setToType(0, FromType);
10584  SCS.setToType(1, ToType);
10585  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10586  SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10587 
10588  APValue PreNarrowingValue;
10589  QualType PreNarrowingType;
10590  switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10591  PreNarrowingType,
10592  /*IgnoreFloatToIntegralConversion*/ true)) {
10594  // Implicit conversion to a narrower type, but the expression is
10595  // value-dependent so we can't tell whether it's actually narrowing.
10596  case NK_Not_Narrowing:
10597  return false;
10598 
10599  case NK_Constant_Narrowing:
10600  // Implicit conversion to a narrower type, and the value is not a constant
10601  // expression.
10602  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10603  << /*Constant*/ 1
10604  << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10605  return true;
10606 
10607  case NK_Variable_Narrowing:
10608  // Implicit conversion to a narrower type, and the value is not a constant
10609  // expression.
10610  case NK_Type_Narrowing:
10611  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10612  << /*Constant*/ 0 << FromType << ToType;
10613  // TODO: It's not a constant expression, but what if the user intended it
10614  // to be? Can we produce notes to help them figure out why it isn't?
10615  return true;
10616  }
10617  llvm_unreachable("unhandled case in switch");
10618 }
10619 
10621  ExprResult &LHS,
10622  ExprResult &RHS,
10623  SourceLocation Loc) {
10624  QualType LHSType = LHS.get()->getType();
10625  QualType RHSType = RHS.get()->getType();
10626  // Dig out the original argument type and expression before implicit casts
10627  // were applied. These are the types/expressions we need to check the
10628  // [expr.spaceship] requirements against.
10629  ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10630  ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10631  QualType LHSStrippedType = LHSStripped.get()->getType();
10632  QualType RHSStrippedType = RHSStripped.get()->getType();
10633 
10634  // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10635  // other is not, the program is ill-formed.
10636  if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10637  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10638  return QualType();
10639  }
10640 
10641  // FIXME: Consider combining this with checkEnumArithmeticConversions.
10642  int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10643  RHSStrippedType->isEnumeralType();
10644  if (NumEnumArgs == 1) {
10645  bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10646  QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10647  if (OtherTy->hasFloatingRepresentation()) {
10648  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10649  return QualType();
10650  }
10651  }
10652  if (NumEnumArgs == 2) {
10653  // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10654  // type E, the operator yields the result of converting the operands
10655  // to the underlying type of E and applying <=> to the converted operands.
10656  if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10657  S.InvalidOperands(Loc, LHS, RHS);
10658  return QualType();
10659  }
10660  QualType IntType =
10661  LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10662  assert(IntType->isArithmeticType());
10663 
10664  // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10665  // promote the boolean type, and all other promotable integer types, to
10666  // avoid this.
10667  if (IntType->isPromotableIntegerType())
10668  IntType = S.Context.getPromotedIntegerType(IntType);
10669 
10670  LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10671  RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10672  LHSType = RHSType = IntType;
10673  }
10674 
10675  // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10676  // usual arithmetic conversions are applied to the operands.
10677  QualType Type =
10679  if (LHS.isInvalid() || RHS.isInvalid())
10680  return QualType();
10681  if (Type.isNull())
10682  return S.InvalidOperands(Loc, LHS, RHS);
10683 
10686  if (!CCT)
10687  return S.InvalidOperands(Loc, LHS, RHS);
10688 
10689  bool HasNarrowing = checkThreeWayNarrowingConversion(
10690  S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10691  HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10692  RHS.get()->getBeginLoc());
10693  if (HasNarrowing)
10694  return QualType();
10695 
10696  assert(!Type.isNull() && "composite type for <=> has not been set");
10697 
10698  return S.CheckComparisonCategoryType(
10700 }
10701 
10703  ExprResult &RHS,
10704  SourceLocation Loc,
10705  BinaryOperatorKind Opc) {
10706  if (Opc == BO_Cmp)
10707  return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10708 
10709  // C99 6.5.8p3 / C99 6.5.9p4
10710  QualType Type =
10712  if (LHS.isInvalid() || RHS.isInvalid())
10713  return QualType();
10714  if (Type.isNull())
10715  return S.InvalidOperands(Loc, LHS, RHS);
10716  assert(Type->isArithmeticType() || Type->isEnumeralType());
10717 
10719  return S.InvalidOperands(Loc, LHS, RHS);
10720 
10721  // Check for comparisons of floating point operands using != and ==.
10723  S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10724 
10725  // The result of comparisons is 'bool' in C++, 'int' in C.
10726  return S.Context.getLogicalOperationType();
10727 }
10728 
10730  if (!NullE.get()->getType()->isAnyPointerType())
10731  return;
10732  int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10733  if (!E.get()->getType()->isAnyPointerType() &&
10734  E.get()->isNullPointerConstant(Context,
10737  if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10738  if (CL->getValue() == 0)
10739  Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10740  << NullValue
10741  << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10742  NullValue ? "NULL" : "(void *)0");
10743  } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10744  TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10745  QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10746  if (T == Context.CharTy)
10747  Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10748  << NullValue
10749  << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10750  NullValue ? "NULL" : "(void *)0");
10751  }
10752  }
10753 }
10754 
10755 // C99 6.5.8, C++ [expr.rel]
10757  SourceLocation Loc,
10758  BinaryOperatorKind Opc) {
10759  bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10760  bool IsThreeWay = Opc == BO_Cmp;
10761  bool IsOrdered = IsRelational || IsThreeWay;
10762  auto IsAnyPointerType = [](ExprResult E) {
10763  QualType Ty = E.get()->getType();
10764  return Ty->isPointerType() || Ty->isMemberPointerType();
10765  };
10766 
10767  // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10768  // type, array-to-pointer, ..., conversions are performed on both operands to
10769  // bring them to their composite type.
10770  // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10771  // any type-related checks.
10772  if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10773  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10774  if (LHS.isInvalid())
10775  return QualType();
10776  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10777  if (RHS.isInvalid())
10778  return QualType();
10779  } else {
10780  LHS = DefaultLvalueConversion(LHS.get());
10781  if (LHS.isInvalid())
10782  return QualType();
10783  RHS = DefaultLvalueConversion(RHS.get());
10784  if (RHS.isInvalid())
10785  return QualType();
10786  }
10787 
10788  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10789  if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10790  CheckPtrComparisonWithNullChar(LHS, RHS);
10791  CheckPtrComparisonWithNullChar(RHS, LHS);
10792  }
10793 
10794  // Handle vector comparisons separately.
10795  if (LHS.get()->getType()->isVectorType() ||
10796  RHS.get()->getType()->isVectorType())
10797  return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10798 
10799  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10800  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10801 
10802  QualType LHSType = LHS.get()->getType();
10803  QualType RHSType = RHS.get()->getType();
10804  if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10805  (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10806  return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10807 
10808  const Expr::NullPointerConstantKind LHSNullKind =
10809  LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10810  const Expr::NullPointerConstantKind RHSNullKind =
10811  RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10812  bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10813  bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10814 
10815  auto computeResultTy = [&]() {
10816  if (Opc != BO_Cmp)
10817  return Context.getLogicalOperationType();
10818  assert(getLangOpts().CPlusPlus);
10819  assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10820 
10821  QualType CompositeTy = LHS.get()->getType();
10822  assert(!CompositeTy->isReferenceType());
10823 
10826  if (!CCT)
10827  return InvalidOperands(Loc, LHS, RHS);
10828 
10829  if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
10830  // P0946R0: Comparisons between a null pointer constant and an object
10831  // pointer result in std::strong_equality, which is ill-formed under
10832  // P1959R0.
10833  Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
10834  << (LHSIsNull ? LHS.get()->getSourceRange()
10835  : RHS.get()->getSourceRange());
10836  return QualType();
10837  }
10838 
10839  return CheckComparisonCategoryType(
10840  *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
10841  };
10842 
10843  if (!IsOrdered && LHSIsNull != RHSIsNull) {
10844  bool IsEquality = Opc == BO_EQ;
10845  if (RHSIsNull)
10846  DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10847  RHS.get()->getSourceRange());
10848  else
10849  DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10850  LHS.get()->getSourceRange());
10851  }
10852 
10853  if ((LHSType->isIntegerType() && !LHSIsNull) ||
10854  (RHSType->isIntegerType() && !RHSIsNull)) {
10855  // Skip normal pointer conversion checks in this case; we have better
10856  // diagnostics for this below.
10857  } else if (getLangOpts().CPlusPlus) {
10858  // Equality comparison of a function pointer to a void pointer is invalid,
10859  // but we allow it as an extension.
10860  // FIXME: If we really want to allow this, should it be part of composite
10861  // pointer type computation so it works in conditionals too?
10862  if (!IsOrdered &&
10863  ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10864  (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10865  // This is a gcc extension compatibility comparison.
10866  // In a SFINAE context, we treat this as a hard error to maintain
10867  // conformance with the C++ standard.
10869  *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10870 
10871  if (isSFINAEContext())
10872  return QualType();
10873 
10874  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10875  return computeResultTy();
10876  }
10877 
10878  // C++ [expr.eq]p2:
10879  // If at least one operand is a pointer [...] bring them to their
10880  // composite pointer type.
10881  // C++ [expr.spaceship]p6
10882  // If at least one of the operands is of pointer type, [...] bring them
10883  // to their composite pointer type.
10884  // C++ [expr.rel]p2:
10885  // If both operands are pointers, [...] bring them to their composite
10886  // pointer type.
10887  // For <=>, the only valid non-pointer types are arrays and functions, and
10888  // we already decayed those, so this is really the same as the relational
10889  // comparison rule.
10890  if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10891  (IsOrdered ? 2 : 1) &&
10892  (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10893  RHSType->isObjCObjectPointerType()))) {
10894  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10895  return QualType();
10896  return computeResultTy();
10897  }
10898  } else if (LHSType->isPointerType() &&
10899  RHSType->isPointerType()) { // C99 6.5.8p2
10900  // All of the following pointer-related warnings are GCC extensions, except
10901  // when handling null pointer constants.
10902  QualType LCanPointeeTy =
10903  LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10904  QualType RCanPointeeTy =
10905  RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10906 
10907  // C99 6.5.9p2 and C99 6.5.8p2
10908  if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10909  RCanPointeeTy.getUnqualifiedType())) {
10910  // Valid unless a relational comparison of function pointers
10911  if (IsRelational && LCanPointeeTy->isFunctionType()) {
10912  Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10913  << LHSType << RHSType << LHS.get()->getSourceRange()
10914  << RHS.get()->getSourceRange();
10915  }
10916  } else if (!IsRelational &&
10917  (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10918  // Valid unless comparison between non-null pointer and function pointer
10919  if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10920  && !LHSIsNull && !RHSIsNull)
10921  diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10922  /*isError*/false);
10923  } else {
10924  // Invalid
10925  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10926  }
10927  if (LCanPointeeTy != RCanPointeeTy) {
10928  // Treat NULL constant as a special case in OpenCL.
10929  if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10930  const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10931  if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10932  Diag(Loc,
10933  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10934  << LHSType << RHSType << 0 /* comparison */
10935  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10936  }
10937  }
10938  LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10939  LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10940  CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10941  : CK_BitCast;
10942  if (LHSIsNull && !RHSIsNull)
10943  LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10944  else
10945  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10946  }
10947  return computeResultTy();
10948  }
10949 
10950  if (getLangOpts().CPlusPlus) {
10951  // C++ [expr.eq]p4:
10952  // Two operands of type std::nullptr_t or one operand of type
10953  // std::nullptr_t and the other a null pointer constant compare equal.
10954  if (!IsOrdered && LHSIsNull && RHSIsNull) {
10955  if (LHSType->isNullPtrType()) {
10956  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10957  return computeResultTy();
10958  }
10959  if (RHSType->isNullPtrType()) {
10960  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10961  return computeResultTy();
10962  }
10963  }
10964 
10965  // Comparison of Objective-C pointers and block pointers against nullptr_t.
10966  // These aren't covered by the composite pointer type rules.
10967  if (!IsOrdered && RHSType->isNullPtrType() &&
10968  (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10969  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10970  return computeResultTy();
10971  }
10972  if (!IsOrdered && LHSType->isNullPtrType() &&
10973  (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10974  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10975  return computeResultTy();
10976  }
10977 
10978  if (IsRelational &&
10979  ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10980  (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10981  // HACK: Relational comparison of nullptr_t against a pointer type is
10982  // invalid per DR583, but we allow it within std::less<> and friends,
10983  // since otherwise common uses of it break.
10984  // FIXME: Consider removing this hack once LWG fixes std::less<> and
10985  // friends to have std::nullptr_t overload candidates.
10986  DeclContext *DC = CurContext;
10987  if (isa<FunctionDecl>(DC))
10988  DC = DC->getParent();
10989  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10990  if (CTSD->isInStdNamespace() &&
10991  llvm::StringSwitch<bool>(CTSD->getName())
10992  .Cases("less", "less_equal", "greater", "greater_equal", true)
10993  .Default(false)) {
10994  if (RHSType->isNullPtrType())
10995  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10996  else
10997  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10998  return computeResultTy();
10999  }
11000  }
11001  }
11002 
11003  // C++ [expr.eq]p2:
11004  // If at least one operand is a pointer to member, [...] bring them to
11005  // their composite pointer type.
11006  if (!IsOrdered &&
11007  (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11008  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11009  return QualType();
11010  else
11011  return computeResultTy();
11012  }
11013  }
11014 
11015  // Handle block pointer types.
11016  if (!IsOrdered && LHSType->isBlockPointerType() &&
11017  RHSType->isBlockPointerType()) {
11018  QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11019  QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11020 
11021  if (!LHSIsNull && !RHSIsNull &&
11022  !Context.typesAreCompatible(lpointee, rpointee)) {
11023  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11024  << LHSType << RHSType << LHS.get()->getSourceRange()
11025  << RHS.get()->getSourceRange();
11026  }
11027  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11028  return computeResultTy();
11029  }
11030 
11031  // Allow block pointers to be compared with null pointer constants.
11032  if (!IsOrdered
11033  && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11034  || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11035  if (!LHSIsNull && !RHSIsNull) {
11036  if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11037  ->getPointeeType()->isVoidType())
11038  || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11039  ->getPointeeType()->isVoidType())))
11040  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11041  << LHSType << RHSType << LHS.get()->getSourceRange()
11042  << RHS.get()->getSourceRange();
11043  }
11044  if (LHSIsNull && !RHSIsNull)
11045  LHS = ImpCastExprToType(LHS.get(), RHSType,
11046  RHSType->isPointerType() ? CK_BitCast
11047  : CK_AnyPointerToBlockPointerCast);
11048  else
11049  RHS = ImpCastExprToType(RHS.get(), LHSType,
11050  LHSType->isPointerType() ? CK_BitCast
11051  : CK_AnyPointerToBlockPointerCast);
11052  return computeResultTy();
11053  }
11054 
11055  if (LHSType->isObjCObjectPointerType() ||
11056  RHSType->isObjCObjectPointerType()) {
11057  const PointerType *LPT = LHSType->getAs<PointerType>();
11058  const PointerType *RPT = RHSType->getAs<PointerType>();
11059  if (LPT || RPT) {
11060  bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11061  bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11062 
11063  if (!LPtrToVoid && !RPtrToVoid &&
11064  !Context.typesAreCompatible(LHSType, RHSType)) {
11065  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11066  /*isError*/false);
11067  }
11068  // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11069  // the RHS, but we have test coverage for this behavior.
11070  // FIXME: Consider using convertPointersToCompositeType in C++.
11071  if (LHSIsNull && !RHSIsNull) {
11072  Expr *E = LHS.get();
11073  if (getLangOpts().ObjCAutoRefCount)
11074  CheckObjCConversion(SourceRange(), RHSType, E,
11075  CCK_ImplicitConversion);
11076  LHS = ImpCastExprToType(E, RHSType,
11077  RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11078  }
11079  else {
11080  Expr *E = RHS.get();
11081  if (getLangOpts().ObjCAutoRefCount)
11082  CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11083  /*Diagnose=*/true,
11084  /*DiagnoseCFAudited=*/false, Opc);
11085  RHS = ImpCastExprToType(E, LHSType,
11086  LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11087  }
11088  return computeResultTy();
11089  }
11090  if (LHSType->isObjCObjectPointerType() &&
11091  RHSType->isObjCObjectPointerType()) {
11092  if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11093  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11094  /*isError*/false);
11095  if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11096  diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11097 
11098  if (LHSIsNull && !RHSIsNull)
11099  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11100  else
11101  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11102  return computeResultTy();
11103  }
11104 
11105  if (!IsOrdered && LHSType->isBlockPointerType() &&
11106  RHSType->isBlockCompatibleObjCPointerType(Context)) {
11107  LHS = ImpCastExprToType(LHS.get(), RHSType,
11108  CK_BlockPointerToObjCPointerCast);
11109  return computeResultTy();
11110  } else if (!IsOrdered &&
11111  LHSType->isBlockCompatibleObjCPointerType(Context) &&
11112  RHSType->isBlockPointerType()) {
11113  RHS = ImpCastExprToType(RHS.get(), LHSType,
11114  CK_BlockPointerToObjCPointerCast);
11115  return computeResultTy();
11116  }
11117  }
11118  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11119  (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11120  unsigned DiagID = 0;
11121  bool isError = false;
11122  if (LangOpts.DebuggerSupport) {
11123  // Under a debugger, allow the comparison of pointers to integers,
11124  // since users tend to want to compare addresses.
11125  } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11126  (RHSIsNull && RHSType->isIntegerType())) {
11127  if (IsOrdered) {
11128  isError = getLangOpts().CPlusPlus;
11129  DiagID =
11130  isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11131  : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11132  }
11133  } else if (getLangOpts().CPlusPlus) {
11134  DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11135  isError = true;
11136  } else if (IsOrdered)
11137  DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11138  else
11139  DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11140 
11141  if (DiagID) {
11142  Diag(Loc, DiagID)
11143  << LHSType << RHSType << LHS.get()->getSourceRange()
11144  << RHS.get()->getSourceRange();
11145  if (isError)
11146  return QualType();
11147  }
11148 
11149  if (LHSType->isIntegerType())
11150  LHS = ImpCastExprToType(LHS.get(), RHSType,
11151  LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11152  else
11153  RHS = ImpCastExprToType(RHS.get(), LHSType,
11154  RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11155  return computeResultTy();
11156  }
11157 
11158  // Handle block pointers.
11159  if (!IsOrdered && RHSIsNull
11160  && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11161  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11162  return computeResultTy();
11163  }
11164  if (!IsOrdered && LHSIsNull
11165  && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11166  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11167  return computeResultTy();
11168  }
11169 
11170  if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11171  if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11172  return computeResultTy();
11173  }
11174 
11175  if (LHSType->isQueueT() && RHSType->isQueueT()) {
11176  return computeResultTy();
11177  }
11178 
11179  if (LHSIsNull && RHSType->isQueueT()) {
11180  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11181  return computeResultTy();
11182  }
11183 
11184  if (LHSType->isQueueT() && RHSIsNull) {
11185  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11186  return computeResultTy();
11187  }
11188  }
11189 
11190  return InvalidOperands(Loc, LHS, RHS);
11191 }
11192 
11193 // Return a signed ext_vector_type that is of identical size and number of
11194 // elements. For floating point vectors, return an integer type of identical
11195 // size and number of elements. In the non ext_vector_type case, search from
11196 // the largest type to the smallest type to avoid cases where long long == long,
11197 // where long gets picked over long long.
11199  const VectorType *VTy = V->castAs<VectorType>();
11200  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11201 
11202  if (isa<ExtVectorType>(VTy)) {
11203  if (TypeSize == Context.getTypeSize(Context.CharTy))
11204  return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11205  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11206  return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11207  else if (TypeSize == Context.getTypeSize(Context.IntTy))
11208  return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11209  else if (TypeSize == Context.getTypeSize(Context.LongTy))
11210  return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11211  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11212  "Unhandled vector element size in vector compare");
11213  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11214  }
11215 
11216  if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11217  return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11219  else if (TypeSize == Context.getTypeSize(Context.LongTy))
11220  return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11222  else if (TypeSize == Context.getTypeSize(Context.IntTy))
11223  return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11225  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11226  return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11228  assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11229  "Unhandled vector element size in vector compare");
11230  return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11232 }
11233 
11234 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11235 /// operates on extended vector types. Instead of producing an IntTy result,
11236 /// like a scalar comparison, a vector comparison produces a vector of integer
11237 /// types.
11239  SourceLocation Loc,
11240  BinaryOperatorKind Opc) {
11241  if (Opc == BO_Cmp) {
11242  Diag(Loc, diag::err_three_way_vector_comparison);
11243  return QualType();
11244  }
11245 
11246  // Check to make sure we're operating on vectors of the same type and width,
11247  // Allowing one side to be a scalar of element type.
11248  QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11249  /*AllowBothBool*/true,
11250  /*AllowBoolConversions*/getLangOpts().ZVector);
11251  if (vType.isNull())
11252  return vType;
11253 
11254  QualType LHSType = LHS.get()->getType();
11255 
11256  // If AltiVec, the comparison results in a numeric type, i.e.
11257  // bool for C++, int for C
11258  if (getLangOpts().AltiVec &&
11260  return Context.getLogicalOperationType();
11261 
11262  // For non-floating point types, check for self-comparisons of the form
11263  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11264  // often indicate logic errors in the program.
11265  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11266 
11267  // Check for comparisons of floating point operands using != and ==.
11268  if (BinaryOperator::isEqualityOp(Opc) &&
11269  LHSType->hasFloatingRepresentation()) {
11270  assert(RHS.get()->getType()->hasFloatingRepresentation());
11271  CheckFloatComparison(Loc, LHS.get(), RHS.get());
11272  }
11273 
11274  // Return a signed type for the vector.
11275  return GetSignedVectorType(vType);
11276 }
11277 
11278 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11279  const ExprResult &XorRHS,
11280  const SourceLocation Loc) {
11281  // Do not diagnose macros.
11282  if (Loc.isMacroID())
11283  return;
11284 
11285  bool Negative = false;
11286  bool ExplicitPlus = false;
11287  const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11288  const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11289 
11290  if (!LHSInt)
11291  return;
11292  if (!RHSInt) {
11293  // Check negative literals.
11294  if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11295  UnaryOperatorKind Opc = UO->getOpcode();
11296  if (Opc != UO_Minus && Opc != UO_Plus)
11297  return;
11298  RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11299  if (!RHSInt)
11300  return;
11301  Negative = (Opc == UO_Minus);
11302  ExplicitPlus = !Negative;
11303  } else {
11304  return;
11305  }
11306  }
11307 
11308  const llvm::APInt &LeftSideValue = LHSInt->getValue();
11309  llvm::APInt RightSideValue = RHSInt->getValue();
11310  if (LeftSideValue != 2 && LeftSideValue != 10)
11311  return;
11312 
11313  if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11314  return;
11315 
11317  LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11318  llvm::StringRef ExprStr =
11319  Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11320 
11321  CharSourceRange XorRange =
11323  llvm::StringRef XorStr =
11325  // Do not diagnose if xor keyword/macro is used.
11326  if (XorStr == "xor")
11327  return;
11328 
11329  std::string LHSStr = Lexer::getSourceText(
11330  CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11331  S.getSourceManager(), S.getLangOpts());
11332  std::string RHSStr = Lexer::getSourceText(
11333  CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11334  S.getSourceManager(), S.getLangOpts());
11335 
11336  if (Negative) {
11337  RightSideValue = -RightSideValue;
11338  RHSStr = "-" + RHSStr;
11339  } else if (ExplicitPlus) {
11340  RHSStr = "+" + RHSStr;
11341  }
11342 
11343  StringRef LHSStrRef = LHSStr;
11344  StringRef RHSStrRef = RHSStr;
11345  // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11346  // literals.
11347  if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11348  RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11349  LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11350  RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11351  (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11352  (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11353  LHSStrRef.find('\'') != StringRef::npos ||
11354  RHSStrRef.find('\'') != StringRef::npos)
11355  return;
11356 
11357  bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11358  const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11359  int64_t RightSideIntValue = RightSideValue.getSExtValue();
11360  if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11361  std::string SuggestedExpr = "1 << " + RHSStr;
11362  bool Overflow = false;
11363  llvm::APInt One = (LeftSideValue - 1);
11364  llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11365  if (Overflow) {
11366  if (RightSideIntValue < 64)
11367  S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11368  << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11369  << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11370  else if (RightSideIntValue == 64)
11371  S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11372  else
11373  return;
11374  } else {
11375  S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11376  << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11377  << PowValue.toString(10, true)
11379  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11380  }
11381 
11382  S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11383  } else if (LeftSideValue == 10) {
11384  std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11385  S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11386  << ExprStr << XorValue.toString(10, true) << SuggestedValue
11387  << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11388  S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11389  }
11390 }
11391 
11393  SourceLocation Loc) {
11394  // Ensure that either both operands are of the same vector type, or
11395  // one operand is of a vector type and the other is of its element type.
11396  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11397  /*AllowBothBool*/true,
11398  /*AllowBoolConversions*/false);
11399  if (vType.isNull())
11400  return InvalidOperands(Loc, LHS, RHS);
11401  if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11402  !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11403  return InvalidOperands(Loc, LHS, RHS);
11404  // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11405  // usage of the logical operators && and || with vectors in C. This
11406  // check could be notionally dropped.
11407  if (!getLangOpts().CPlusPlus &&
11408  !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11409  return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11410 
11411  return GetSignedVectorType(LHS.get()->getType());
11412 }
11413 
11415  SourceLocation Loc,
11416  BinaryOperatorKind Opc) {
11417  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11418 
11419  bool IsCompAssign =
11420  Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11421 
11422  if (LHS.get()->getType()->isVectorType() ||
11423  RHS.get()->getType()->isVectorType()) {
11424  if (LHS.get()->getType()->hasIntegerRepresentation() &&
11425  RHS.get()->getType()->hasIntegerRepresentation())
11426  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11427  /*AllowBothBool*/true,
11428  /*AllowBoolConversions*/getLangOpts().ZVector);
11429  return InvalidOperands(Loc, LHS, RHS);
11430  }
11431 
11432  if (Opc == BO_And)
11433  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11434 
11435  if (LHS.get()->getType()->hasFloatingRepresentation() ||
11436  RHS.get()->getType()->hasFloatingRepresentation())
11437  return InvalidOperands(Loc, LHS, RHS);
11438 
11439  ExprResult LHSResult = LHS, RHSResult = RHS;
11440  QualType compType = UsualArithmeticConversions(
11441  LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11442  if (LHSResult.isInvalid() || RHSResult.isInvalid())
11443  return QualType();
11444  LHS = LHSResult.get();
11445  RHS = RHSResult.get();
11446 
11447  if (Opc == BO_Xor)
11448  diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11449 
11450  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11451  return compType;
11452  return InvalidOperands(Loc, LHS, RHS);
11453 }
11454 
11455 // C99 6.5.[13,14]
11457  SourceLocation Loc,
11458  BinaryOperatorKind Opc) {
11459  // Check vector operands differently.
11460  if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11461  return CheckVectorLogicalOperands(LHS, RHS, Loc);
11462 
11463  bool EnumConstantInBoolContext = false;
11464  for (const ExprResult &HS : {LHS, RHS}) {
11465  if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11466  const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11467  if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11468  EnumConstantInBoolContext = true;
11469  }
11470  }
11471 
11472  if (EnumConstantInBoolContext)
11473  Diag(Loc, diag::warn_enum_constant_in_bool_context);
11474 
11475  // Diagnose cases where the user write a logical and/or but probably meant a
11476  // bitwise one. We do this when the LHS is a non-bool integer and the RHS
11477  // is a constant.
11478  if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11479  !LHS.get()->getType()->isBooleanType() &&
11480  RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11481  // Don't warn in macros or template instantiations.
11482  !Loc.isMacroID() && !inTemplateInstantiation()) {
11483  // If the RHS can be constant folded, and if it constant folds to something
11484  // that isn't 0 or 1 (which indicate a potential logical operation that
11485  // happened to fold to true/false) then warn.
11486  // Parens on the RHS are ignored.
11487  Expr::EvalResult EVResult;
11488  if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11489  llvm::APSInt Result = EVResult.Val.getInt();
11490  if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11491  !RHS.get()->getExprLoc().isMacroID()) ||
11492  (Result != 0 && Result != 1)) {
11493  Diag(Loc, diag::warn_logical_instead_of_bitwise)
11494  << RHS.get()->getSourceRange()
11495  << (Opc == BO_LAnd ? "&&" : "||");
11496  // Suggest replacing the logical operator with the bitwise version
11497  Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11498  << (Opc == BO_LAnd ? "&" : "|")
11500  Loc, getLocForEndOfToken(Loc)),
11501  Opc == BO_LAnd ? "&" : "|");
11502  if (Opc == BO_LAnd)
11503  // Suggest replacing "Foo() && kNonZero" with "Foo()"
11504  Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11506  SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11507  RHS.get()->getEndLoc()));
11508  }
11509  }
11510  }
11511 
11512  if (!Context.getLangOpts().CPlusPlus) {
11513  // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11514  // not operate on the built-in scalar and vector float types.
11515  if (Context.getLangOpts().OpenCL &&
11516  Context.getLangOpts().OpenCLVersion < 120) {
11517  if (LHS.get()->getType()->isFloatingType() ||
11518  RHS.get()->getType()->isFloatingType())
11519  return InvalidOperands(Loc, LHS, RHS);
11520  }
11521 
11522  LHS = UsualUnaryConversions(LHS.get());
11523  if (LHS.isInvalid())
11524  return QualType();
11525 
11526  RHS = UsualUnaryConversions(RHS.get());
11527  if (RHS.isInvalid())
11528  return QualType();
11529 
11530  if (!LHS.get()->getType()->isScalarType() ||
11531  !RHS.get()->getType()->isScalarType())
11532  return InvalidOperands(Loc, LHS, RHS);
11533 
11534  return Context.IntTy;
11535  }
11536 
11537  // The following is safe because we only use this method for
11538  // non-overloadable operands.
11539 
11540  // C++ [expr.log.and]p1
11541  // C++ [expr.log.or]p1
11542  // The operands are both contextually converted to type bool.
11543  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11544  if (LHSRes.isInvalid())
11545  return InvalidOperands(Loc, LHS, RHS);
11546  LHS = LHSRes;
11547 
11548  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11549  if (RHSRes.isInvalid())
11550  return InvalidOperands(Loc, LHS, RHS);
11551  RHS = RHSRes;
11552 
11553  // C++ [expr.log.and]p2
11554  // C++ [expr.log.or]p2
11555  // The result is a bool.
11556  return Context.BoolTy;
11557 }
11558 
11559 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11560  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11561  if (!ME) return false;
11562  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11563  ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11565  if (!Base) return false;
11566  return Base->getMethodDecl() != nullptr;
11567 }
11568 
11569 /// Is the given expression (which must be 'const') a reference to a
11570 /// variable which was originally non-const, but which has become
11571 /// 'const' due to being captured within a block?
11574  assert(E->isLValue() && E->getType().isConstQualified());
11575  E = E->IgnoreParens();
11576 
11577  // Must be a reference to a declaration from an enclosing scope.
11578  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11579  if (!DRE) return NCCK_None;
11580  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11581 
11582  // The declaration must be a variable which is not declared 'const'.
11583  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11584  if (!var) return NCCK_None;
11585  if (var->getType().isConstQualified()) return NCCK_None;
11586  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11587 
11588  // Decide whether the first capture was for a block or a lambda.
11589  DeclContext *DC = S.CurContext, *Prev = nullptr;
11590  // Decide whether the first capture was for a block or a lambda.
11591  while (DC) {
11592  // For init-capture, it is possible that the variable belongs to the
11593  // template pattern of the current context.
11594  if (auto *FD = dyn_cast<FunctionDecl>(DC))
11595  if (var->isInitCapture() &&
11596  FD->getTemplateInstantiationPattern() == var->getDeclContext())
11597  break;
11598  if (DC == var->getDeclContext())
11599  break;
11600  Prev = DC;
11601  DC = DC->getParent();
11602  }
11603  // Unless we have an init-capture, we've gone one step too far.
11604  if (!var->isInitCapture())
11605  DC = Prev;
11606  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11607 }
11608 
11609 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11610  Ty = Ty.getNonReferenceType();
11611  if (IsDereference && Ty->isPointerType())
11612  Ty = Ty->getPointeeType();
11613  return !Ty.isConstQualified();
11614 }
11615 
11616 // Update err_typecheck_assign_const and note_typecheck_assign_const
11617 // when this enum is changed.
11618 enum {
11624  ConstUnknown, // Keep as last element
11625 };
11626 
11627 /// Emit the "read-only variable not assignable" error and print notes to give
11628 /// more information about why the variable is not assignable, such as pointing
11629 /// to the declaration of a const variable, showing that a method is const, or
11630 /// that the function is returning a const reference.
11631 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11632  SourceLocation Loc) {
11633  SourceRange ExprRange = E->getSourceRange();
11634 
11635  // Only emit one error on the first const found. All other consts will emit
11636  // a note to the error.
11637  bool DiagnosticEmitted = false;
11638 
11639  // Track if the current expression is the result of a dereference, and if the
11640  // next checked expression is the result of a dereference.
11641  bool IsDereference = false;
11642  bool NextIsDereference = false;
11643 
11644  // Loop to process MemberExpr chains.
11645  while (true) {
11646  IsDereference = NextIsDereference;
11647 
11648  E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11649  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11650  NextIsDereference = ME->isArrow();
11651  const ValueDecl *VD = ME->getMemberDecl();
11652  if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11653  // Mutable fields can be modified even if the class is const.
11654  if (Field->isMutable()) {
11655  assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11656  break;
11657  }
11658 
11659  if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11660  if (!DiagnosticEmitted) {
11661  S.Diag(Loc, diag::err_typecheck_assign_const)
11662  << ExprRange << ConstMember << false /*static*/ << Field
11663  << Field->getType();
11664  DiagnosticEmitted = true;
11665  }
11666  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11667  << ConstMember << false /*static*/ << Field << Field->getType()
11668  << Field->getSourceRange();
11669  }
11670  E = ME->getBase();
11671  continue;
11672  } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11673  if (VDecl->getType().isConstQualified()) {
11674  if (!DiagnosticEmitted) {
11675  S.Diag(Loc, diag::err_typecheck_assign_const)
11676  << ExprRange << ConstMember << true /*static*/ << VDecl
11677  << VDecl->getType();
11678  DiagnosticEmitted = true;
11679  }
11680  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11681  << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11682  << VDecl->getSourceRange();
11683  }
11684  // Static fields do not inherit constness from parents.
11685  break;
11686  }
11687  break; // End MemberExpr
11688  } else if (const ArraySubscriptExpr *ASE =
11689  dyn_cast<ArraySubscriptExpr>(E)) {
11690  E = ASE->getBase()->IgnoreParenImpCasts();
11691  continue;
11692  } else if (const ExtVectorElementExpr *EVE =
11693  dyn_cast<ExtVectorElementExpr>(E)) {
11694  E = EVE->getBase()->IgnoreParenImpCasts();
11695  continue;
11696  }
11697  break;
11698  }
11699 
11700  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11701  // Function calls
11702  const FunctionDecl *FD = CE->getDirectCallee();
11703  if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11704  if (!DiagnosticEmitted) {
11705  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11706  << ConstFunction << FD;
11707  DiagnosticEmitted = true;
11708  }
11710  diag::note_typecheck_assign_const)
11711  << ConstFunction << FD << FD->getReturnType()
11712  << FD->getReturnTypeSourceRange();
11713  }
11714  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11715  // Point to variable declaration.
11716  if (const ValueDecl *VD = DRE->getDecl()) {
11717  if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11718  if (!DiagnosticEmitted) {
11719  S.Diag(Loc, diag::err_typecheck_assign_const)
11720  << ExprRange << ConstVariable << VD << VD->getType();
11721  DiagnosticEmitted = true;
11722  }
11723  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11724  << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11725  }
11726  }
11727  } else if (isa<CXXThisExpr>(E)) {
11728  if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11729  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11730  if (MD->isConst()) {
11731  if (!DiagnosticEmitted) {
11732  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11733  << ConstMethod << MD;
11734  DiagnosticEmitted = true;
11735  }
11736  S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11737  << ConstMethod << MD << MD->getSourceRange();
11738  }
11739  }
11740  }
11741  }
11742 
11743  if (DiagnosticEmitted)
11744  return;
11745 
11746  // Can't determine a more specific message, so display the generic error.
11747  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11748 }
11749 
11754 };
11755 
11756 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11757  const RecordType *Ty,
11758  SourceLocation Loc, SourceRange Range,
11759  OriginalExprKind OEK,
11760  bool &DiagnosticEmitted) {
11761  std::vector<const RecordType *> RecordTypeList;
11762  RecordTypeList.push_back(Ty);
11763  unsigned NextToCheckIndex = 0;
11764  // We walk the record hierarchy breadth-first to ensure that we print
11765  // diagnostics in field nesting order.
11766  while (RecordTypeList.size() > NextToCheckIndex) {
11767  bool IsNested = NextToCheckIndex > 0;
11768  for (const FieldDecl *Field :
11769  RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11770  // First, check every field for constness.
11771  QualType FieldTy = Field->getType();
11772  if (FieldTy.isConstQualified()) {
11773  if (!DiagnosticEmitted) {
11774  S.Diag(Loc, diag::err_typecheck_assign_const)
11775  << Range << NestedConstMember << OEK << VD
11776  << IsNested << Field;
11777  DiagnosticEmitted = true;
11778  }
11779  S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11780  << NestedConstMember << IsNested << Field
11781  << FieldTy << Field->getSourceRange();
11782  }
11783 
11784  // Then we append it to the list to check next in order.
11785  FieldTy = FieldTy.getCanonicalType();
11786  if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11787  if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11788  RecordTypeList.push_back(FieldRecTy);
11789  }
11790  }
11791  ++NextToCheckIndex;
11792  }
11793 }
11794 
11795 /// Emit an error for the case where a record we are trying to assign to has a
11796 /// const-qualified field somewhere in its hierarchy.
11797 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11798  SourceLocation Loc) {
11799  QualType Ty = E->getType();
11800  assert(Ty->isRecordType() && "lvalue was not record?");
11801  SourceRange Range = E->getSourceRange();
11802  const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11803  bool DiagEmitted = false;
11804 
11805  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11806  DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11807  Range, OEK_Member, DiagEmitted);
11808  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11809  DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11810  Range, OEK_Variable, DiagEmitted);
11811  else
11812  DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11813  Range, OEK_LValue, DiagEmitted);
11814  if (!DiagEmitted)
11815  DiagnoseConstAssignment(S, E, Loc);
11816 }
11817 
11818 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
11819 /// emit an error and return true. If so, return false.
11821  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11822 
11824 
11825  SourceLocation OrigLoc = Loc;
11827  &Loc);
11828  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11830  if (IsLV == Expr::MLV_Valid)
11831  return false;
11832 
11833  unsigned DiagID = 0;
11834  bool NeedType = false;
11835  switch (IsLV) { // C99 6.5.16p2
11837  // Use a specialized diagnostic when we're assigning to an object
11838  // from an enclosing function or block.
11840  if (NCCK == NCCK_Block)
11841  DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11842  else
11843  DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11844  break;
11845  }
11846 
11847  // In ARC, use some specialized diagnostics for occasions where we
11848  // infer 'const'. These are always pseudo-strong variables.
11849  if (S.getLangOpts().ObjCAutoRefCount) {
11850  DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11851  if (declRef && isa<VarDecl>(declRef->getDecl())) {
11852  VarDecl *var = cast<VarDecl>(declRef->getDecl());
11853 
11854  // Use the normal diagnostic if it's pseudo-__strong but the
11855  // user actually wrote 'const'.
11856  if (var->isARCPseudoStrong() &&
11857  (!var->getTypeSourceInfo() ||
11858  !var->getTypeSourceInfo()->getType().isConstQualified())) {
11859  // There are three pseudo-strong cases:
11860  // - self
11861  ObjCMethodDecl *method = S.getCurMethodDecl();
11862  if (method && var == method->getSelfDecl()) {
11863  DiagID = method->isClassMethod()
11864  ? diag::err_typecheck_arc_assign_self_class_method
11865  : diag::err_typecheck_arc_assign_self;
11866 
11867  // - Objective-C externally_retained attribute.
11868  } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11869  isa<ParmVarDecl>(var)) {
11870  DiagID = diag::err_typecheck_arc_assign_externally_retained;
11871 
11872  // - fast enumeration variables
11873  } else {
11874  DiagID = diag::err_typecheck_arr_assign_enumeration;
11875  }
11876 
11877  SourceRange Assign;
11878  if (Loc != OrigLoc)
11879  Assign = SourceRange(OrigLoc, OrigLoc);
11880  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11881  // We need to preserve the AST regardless, so migration tool
11882  // can do its job.
11883  return false;
11884  }
11885  }
11886  }
11887 
11888  // If none of the special cases above are triggered, then this is a
11889  // simple const assignment.
11890  if (DiagID == 0) {
11891  DiagnoseConstAssignment(S, E, Loc);
11892  return true;
11893  }
11894 
11895  break;
11897  DiagnoseConstAssignment(S, E, Loc);
11898  return true;
11900  DiagnoseRecursiveConstFields(S, E, Loc);
11901  return true;
11902  case Expr::MLV_ArrayType:
11904  DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11905  NeedType = true;
11906  break;
11908  DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11909  NeedType = true;
11910  break;
11911  case Expr::MLV_LValueCast:
11912  DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11913  break;
11914  case Expr::MLV_Valid:
11915  llvm_unreachable("did not take early return for MLV_Valid");
11919  DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11920  break;
11923  return S.RequireCompleteType(Loc, E->getType(),
11924  diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11926  DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11927  break;
11929  llvm_unreachable("readonly properties should be processed differently");
11931  DiagID = diag::err_readonly_message_assignment;
11932  break;
11934  DiagID = diag::err_no_subobject_property_setting;
11935  break;
11936  }
11937 
11938  SourceRange Assign;
11939  if (Loc != OrigLoc)
11940  Assign = SourceRange(OrigLoc, OrigLoc);
11941  if (NeedType)
11942  S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11943  else
11944  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11945  return true;
11946 }
11947 
11948 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11949  SourceLocation Loc,
11950  Sema &Sema) {
11951  if (Sema.inTemplateInstantiation())
11952  return;
11953  if (Sema.isUnevaluatedContext())
11954  return;
11955  if (Loc.isInvalid() || Loc.isMacroID())
11956  return;
11957  if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11958  return;
11959 
11960  // C / C++ fields
11961  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11962  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11963  if (ML && MR) {
11964  if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11965  return;
11966  const ValueDecl *LHSDecl =
11967  cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11968  const ValueDecl *RHSDecl =
11969  cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11970  if (LHSDecl != RHSDecl)
11971  return;
11972  if (LHSDecl->getType().isVolatileQualified())
11973  return;
11974  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11975  if (RefTy->getPointeeType().isVolatileQualified())
11976  return;
11977 
11978  Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11979  }
11980 
11981  // Objective-C instance variables
11982  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11983  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11984  if (OL && OR && OL->getDecl() == OR->getDecl()) {
11985  DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11986  DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11987  if (RL && RR && RL->getDecl() == RR->getDecl())
11988  Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11989  }
11990 }
11991 
11992 // C99 6.5.16.1
11994  SourceLocation Loc,
11995  QualType CompoundType) {
11996  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11997 
11998  // Verify that LHS is a modifiable lvalue, and emit error if not.
11999  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12000  return QualType();
12001 
12002  QualType LHSType = LHSExpr->getType();
12003  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12004  CompoundType;
12005  // OpenCL v1.2 s6.1.1.1 p2:
12006  // The half data type can only be used to declare a pointer to a buffer that
12007  // contains half values
12008  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12009  LHSType->isHalfType()) {
12010  Diag(Loc, diag::err_opencl_half_load_store) << 1
12011  << LHSType.getUnqualifiedType();
12012  return QualType();
12013  }
12014 
12015  AssignConvertType ConvTy;
12016  if (CompoundType.isNull()) {
12017  Expr *RHSCheck = RHS.get();
12018 
12019  CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12020 
12021  QualType LHSTy(LHSType);
12022  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12023  if (RHS.isInvalid())
12024  return QualType();
12025  // Special case of NSObject attributes on c-style pointer types.
12026  if (ConvTy == IncompatiblePointer &&
12027  ((Context.isObjCNSObjectType(LHSType) &&
12028  RHSType->isObjCObjectPointerType()) ||
12029  (Context.isObjCNSObjectType(RHSType) &&
12030  LHSType->isObjCObjectPointerType())))
12031  ConvTy = Compatible;
12032 
12033  if (ConvTy == Compatible &&
12034  LHSType->isObjCObjectType())
12035  Diag(Loc, diag::err_objc_object_assignment)
12036  << LHSType;
12037 
12038  // If the RHS is a unary plus or minus, check to see if they = and + are
12039  // right next to each other. If so, the user may have typo'd "x =+ 4"
12040  // instead of "x += 4".
12041  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12042  RHSCheck = ICE->getSubExpr();
12043  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12044  if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12045  Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12046  // Only if the two operators are exactly adjacent.
12047  Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12048  // And there is a space or other character before the subexpr of the
12049  // unary +/-. We don't want to warn on "x=-1".
12050  Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12051  UO->getSubExpr()->getBeginLoc().isFileID()) {
12052  Diag(Loc, diag::warn_not_compound_assign)
12053  << (UO->getOpcode() == UO_Plus ? "+" : "-")
12054  << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12055  }
12056  }
12057 
12058  if (ConvTy == Compatible) {
12059  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12060  // Warn about retain cycles where a block captures the LHS, but
12061  // not if the LHS is a simple variable into which the block is
12062  // being stored...unless that variable can be captured by reference!
12063  const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12064  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12065  if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12066  checkRetainCycles(LHSExpr, RHS.get());
12067  }
12068 
12069  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12070  LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12071  // It is safe to assign a weak reference into a strong variable.
12072  // Although this code can still have problems:
12073  // id x = self.weakProp;
12074  // id y = self.weakProp;
12075  // we do not warn to warn spuriously when 'x' and 'y' are on separate
12076  // paths through the function. This should be revisited if
12077  // -Wrepeated-use-of-weak is made flow-sensitive.
12078  // For ObjCWeak only, we do not warn if the assign is to a non-weak
12079  // variable, which will be valid for the current autorelease scope.
12080  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12081  RHS.get()->getBeginLoc()))
12082  getCurFunction()->markSafeWeakUse(RHS.get());
12083 
12084  } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12085  checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12086  }
12087  }
12088  } else {
12089  // Compound assignment "x += y"
12090  ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12091  }
12092 
12093  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12094  RHS.get(), AA_Assigning))
12095  return QualType();
12096 
12097  CheckForNullPointerDereference(*this, LHSExpr);
12098 
12099  if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12100  if (CompoundType.isNull()) {
12101  // C++2a [expr.ass]p5:
12102  // A simple-assignment whose left operand is of a volatile-qualified
12103  // type is deprecated unless the assignment is either a discarded-value
12104  // expression or an unevaluated operand
12105  ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12106  } else {
12107  // C++2a [expr.ass]p6:
12108  // [Compound-assignment] expressions are deprecated if E1 has
12109  // volatile-qualified type
12110  Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12111  }
12112  }
12113 
12114  // C99 6.5.16p3: The type of an assignment expression is the type of the
12115  // left operand unless the left operand has qualified type, in which case
12116  // it is the unqualified version of the type of the left operand.
12117  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12118  // is converted to the type of the assignment expression (above).
12119  // C++ 5.17p1: the type of the assignment expression is that of its left
12120  // operand.
12121  return (getLangOpts().CPlusPlus
12122  ? LHSType : LHSType.getUnqualifiedType());
12123 }
12124 
12125 // Only ignore explicit casts to void.
12126 static bool IgnoreCommaOperand(const Expr *E) {
12127  E = E->IgnoreParens();
12128 
12129  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12130  if (CE->getCastKind() == CK_ToVoid) {
12131  return true;
12132  }
12133 
12134  // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12135  if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12136  CE->getSubExpr()->getType()->isDependentType()) {
12137  return true;
12138  }
12139  }
12140 
12141  return false;
12142 }
12143 
12144 // Look for instances where it is likely the comma operator is confused with
12145 // another operator. There is a whitelist of acceptable expressions for the
12146 // left hand side of the comma operator, otherwise emit a warning.
12148  // No warnings in macros
12149  if (Loc.isMacroID())
12150  return;
12151 
12152  // Don't warn in template instantiations.
12153  if (inTemplateInstantiation())
12154  return;
12155 
12156  // Scope isn't fine-grained enough to whitelist the specific cases, so
12157  // instead, skip more than needed, then call back into here with the
12158  // CommaVisitor in SemaStmt.cpp.
12159  // The whitelisted locations are the initialization and increment portions
12160  // of a for loop. The additional checks are on the condition of
12161  // if statements, do/while loops, and for loops.
12162  // Differences in scope flags for C89 mode requires the extra logic.
12163  const unsigned ForIncrementFlags =
12164  getLangOpts().C99 || getLangOpts().CPlusPlus
12167  const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12168  const unsigned ScopeFlags = getCurScope()->getFlags();
12169  if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12170  (ScopeFlags & ForInitFlags) == ForInitFlags)
12171  return;
12172 
12173  // If there are multiple comma operators used together, get the RHS of the
12174  // of the comma operator as the LHS.
12175  while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12176  if (BO->getOpcode() != BO_Comma)
12177  break;
12178  LHS = BO->getRHS();
12179  }
12180 
12181  // Only allow some expressions on LHS to not warn.
12182  if (IgnoreCommaOperand(LHS))
12183  return;
12184 
12185  Diag(Loc, diag::warn_comma_operator);
12186  Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12187  << LHS->getSourceRange()
12189  LangOpts.CPlusPlus ? "static_cast<void>("
12190  : "(void)(")
12191  << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12192  ")");
12193 }
12194 
12195 // C99 6.5.17
12197  SourceLocation Loc) {
12198  LHS = S.CheckPlaceholderExpr(LHS.get());
12199  RHS = S.CheckPlaceholderExpr(RHS.get());
12200  if (LHS.isInvalid() || RHS.isInvalid())
12201  return QualType();
12202 
12203  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12204  // operands, but not unary promotions.
12205  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12206 
12207  // So we treat the LHS as a ignored value, and in C++ we allow the
12208  // containing site to determine what should be done with the RHS.
12209  LHS = S.IgnoredValueConversions(LHS.get());
12210  if (LHS.isInvalid())
12211  return QualType();
12212 
12213  S.DiagnoseUnusedExprResult(LHS.get());
12214 
12215  if (!S.getLangOpts().CPlusPlus) {
12217  if (RHS.isInvalid())
12218  return QualType();
12219  if (!RHS.get()->getType()->isVoidType())
12220  S.RequireCompleteType(Loc, RHS.get()->getType(),
12221  diag::err_incomplete_type);
12222  }
12223 
12224  if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12225  S.DiagnoseCommaOperator(LHS.get(), Loc);
12226 
12227  return RHS.get()->getType();
12228 }
12229 
12230 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12231 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12233  ExprValueKind &VK,
12234  ExprObjectKind &OK,
12235  SourceLocation OpLoc,
12236  bool IsInc, bool IsPrefix) {
12237  if (Op->isTypeDependent())
12238  return S.Context.DependentTy;
12239 
12240  QualType ResType = Op->getType();
12241  // Atomic types can be used for increment / decrement where the non-atomic
12242  // versions can, so ignore the _Atomic() specifier for the purpose of
12243  // checking.
12244  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12245  ResType = ResAtomicType->getValueType();
12246 
12247  assert(!ResType.isNull() && "no type for increment/decrement expression");
12248 
12249  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12250  // Decrement of bool is not allowed.
12251  if (!IsInc) {
12252  S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12253  return QualType();
12254  }
12255  // Increment of bool sets it to true, but is deprecated.
12256  S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12257  : diag::warn_increment_bool)
12258  << Op->getSourceRange();
12259  } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12260  // Error on enum increments and decrements in C++ mode
12261  S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12262  return QualType();
12263  } else if (ResType->isRealType()) {
12264  // OK!
12265  } else if (ResType->isPointerType()) {
12266  // C99 6.5.2.4p2, 6.5.6p2
12267  if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12268  return QualType();
12269  } else if (ResType->isObjCObjectPointerType()) {
12270  // On modern runtimes, ObjC pointer arithmetic is forbidden.
12271  // Otherwise, we just need a complete type.
12272  if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12273  checkArithmeticOnObjCPointer(S, OpLoc, Op))
12274  return QualType();
12275  } else if (ResType->isAnyComplexType()) {
12276  // C99 does not support ++/-- on complex types, we allow as an extension.
12277  S.Diag(OpLoc, diag::ext_integer_increment_complex)
12278  << ResType << Op->getSourceRange();
12279  } else if (ResType->isPlaceholderType()) {
12280  ExprResult PR = S.CheckPlaceholderExpr(Op);
12281  if (PR.isInvalid()) return QualType();
12282  return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12283  IsInc, IsPrefix);
12284  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12285  // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12286  } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12287  (ResType->castAs<VectorType>()->getVectorKind() !=
12289  // The z vector extensions allow ++ and -- for non-bool vectors.
12290  } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12291  ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12292  // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12293  } else {
12294  S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12295  << ResType << int(IsInc) << Op->getSourceRange();
12296  return QualType();
12297  }
12298  // At this point, we know we have a real, complex or pointer type.
12299  // Now make sure the operand is a modifiable lvalue.
12300  if (CheckForModifiableLvalue(Op, OpLoc, S))
12301  return QualType();
12302  if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12303  // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12304  // An operand with volatile-qualified type is deprecated
12305  S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12306  << IsInc << ResType;
12307  }
12308  // In C++, a prefix increment is the same type as the operand. Otherwise
12309  // (in C or with postfix), the increment is the unqualified type of the
12310  // operand.
12311  if (IsPrefix && S.getLangOpts().CPlusPlus) {
12312  VK = VK_LValue;
12313  OK = Op->getObjectKind();
12314  return ResType;
12315  } else {
12316  VK = VK_RValue;
12317  return ResType.getUnqualifiedType();
12318  }
12319 }
12320 
12321 
12322 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12323 /// This routine allows us to typecheck complex/recursive expressions
12324 /// where the declaration is needed for type checking. We only need to
12325 /// handle cases when the expression references a function designator
12326 /// or is an lvalue. Here are some examples:
12327 /// - &(x) => x
12328 /// - &*****f => f for f a function designator.
12329 /// - &s.xx => s
12330 /// - &s.zz[1].yy -> s, if zz is an array
12331 /// - *(x + 1) -> x, if x is an array
12332 /// - &"123"[2] -> 0
12333 /// - & __real__ x -> x
12335  switch (E->getStmtClass()) {
12336  case Stmt::DeclRefExprClass:
12337  return cast<DeclRefExpr>(E)->getDecl();
12338  case Stmt::MemberExprClass:
12339  // If this is an arrow operator, the address is an offset from
12340  // the base's value, so the object the base refers to is
12341  // irrelevant.
12342  if (cast<MemberExpr>(E)->isArrow())
12343  return nullptr;
12344  // Otherwise, the expression refers to a part of the base
12345  return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12346  case Stmt::ArraySubscriptExprClass: {
12347  // FIXME: This code shouldn't be necessary! We should catch the implicit
12348  // promotion of register arrays earlier.
12349  Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12350  if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12351  if (ICE->getSubExpr()->getType()->isArrayType())
12352  return getPrimaryDecl(ICE->getSubExpr());
12353  }
12354  return nullptr;
12355  }
12356  case Stmt::UnaryOperatorClass: {
12357  UnaryOperator *UO = cast<UnaryOperator>(E);
12358 
12359  switch(UO->getOpcode()) {
12360  case UO_Real:
12361  case UO_Imag:
12362  case UO_Extension:
12363  return getPrimaryDecl(UO->getSubExpr());
12364  default:
12365  return nullptr;
12366  }
12367  }
12368  case Stmt::ParenExprClass:
12369  return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12370  case Stmt::ImplicitCastExprClass:
12371  // If the result of an implicit cast is an l-value, we care about
12372  // the sub-expression; otherwise, the result here doesn't matter.
12373  return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12374  default:
12375  return nullptr;
12376  }
12377 }
12378 
12379 namespace {
12380  enum {
12381  AO_Bit_Field = 0,
12382  AO_Vector_Element = 1,
12383  AO_Property_Expansion = 2,
12384  AO_Register_Variable = 3,
12385  AO_No_Error = 4
12386  };
12387 }
12388 /// Diagnose invalid operand for address of operations.
12389 ///
12390 /// \param Type The type of operand which cannot have its address taken.
12392  Expr *E, unsigned Type) {
12393  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12394 }
12395 
12396 /// CheckAddressOfOperand - The operand of & must be either a function
12397 /// designator or an lvalue designating an object. If it is an lvalue, the
12398 /// object cannot be declared with storage class register or be a bit field.
12399 /// Note: The usual conversions are *not* applied to the operand of the &
12400 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12401 /// In C++, the operand might be an overloaded function name, in which case
12402 /// we allow the '&' but retain the overloaded-function type.
12404  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12405  if (PTy->getKind() == BuiltinType::Overload) {
12406  Expr *E = OrigOp.get()->IgnoreParens();
12407  if (!isa<OverloadExpr>(E)) {
12408  assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12409  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12410  << OrigOp.get()->getSourceRange();
12411  return QualType();
12412  }
12413 
12414  OverloadExpr *Ovl = cast<OverloadExpr>(E);
12415  if (isa<UnresolvedMemberExpr>(Ovl))
12416  if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12417  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12418  << OrigOp.get()->getSourceRange();
12419  return QualType();
12420  }
12421 
12422  return Context.OverloadTy;
12423  }
12424 
12425  if (PTy->getKind() == BuiltinType::UnknownAny)
12426  return Context.UnknownAnyTy;
12427 
12428  if (PTy->getKind() == BuiltinType::BoundMember) {
12429  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12430  << OrigOp.get()->getSourceRange();
12431  return QualType();
12432  }
12433 
12434  OrigOp = CheckPlaceholderExpr(OrigOp.get());
12435  if (OrigOp.isInvalid()) return QualType();
12436  }
12437 
12438  if (OrigOp.get()->isTypeDependent())
12439  return Context.DependentTy;
12440 
12441  assert(!OrigOp.get()->getType()->isPlaceholderType());
12442 
12443  // Make sure to ignore parentheses in subsequent checks
12444  Expr *op = OrigOp.get()->IgnoreParens();
12445 
12446  // In OpenCL captures for blocks called as lambda functions
12447  // are located in the private address space. Blocks used in
12448  // enqueue_kernel can be located in a different address space
12449  // depending on a vendor implementation. Thus preventing
12450  // taking an address of the capture to avoid invalid AS casts.
12451  if (LangOpts.OpenCL) {
12452  auto* VarRef = dyn_cast<DeclRefExpr>(op);
12453  if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12454  Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12455  return QualType();
12456  }
12457  }
12458 
12459  if (getLangOpts().C99) {
12460  // Implement C99-only parts of addressof rules.
12461  if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12462  if (uOp->getOpcode() == UO_Deref)
12463  // Per C99 6.5.3.2, the address of a deref always returns a valid result
12464  // (assuming the deref expression is valid).
12465  return uOp->getSubExpr()->getType();
12466  }
12467  // Technically, there should be a check for array subscript
12468  // expressions here, but the result of one is always an lvalue anyway.
12469  }
12470  ValueDecl *dcl = getPrimaryDecl(op);
12471 
12472  if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12473  if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12474  op->getBeginLoc()))
12475  return QualType();
12476 
12477  Expr::LValueClassification lval = op->ClassifyLValue(Context);
12478  unsigned AddressOfError = AO_No_Error;
12479 
12480  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12481  bool sfinae = (bool)isSFINAEContext();
12482  Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12483  : diag::ext_typecheck_addrof_temporary)
12484  << op->getType() << op->getSourceRange();
12485  if (sfinae)
12486  return QualType();
12487  // Materialize the temporary as an lvalue so that we can take its address.
12488  OrigOp = op =
12489  CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12490  } else if (isa<ObjCSelectorExpr>(op)) {
12491  return Context.getPointerType(op->getType());
12492  } else if (lval == Expr::LV_MemberFunction) {
12493  // If it's an instance method, make a member pointer.
12494  // The expression must have exactly the form &A::foo.
12495 
12496  // If the underlying expression isn't a decl ref, give up.
12497  if (!isa<DeclRefExpr>(op)) {
12498  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12499  << OrigOp.get()->getSourceRange();
12500  return QualType();
12501  }
12502  DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12503  CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12504 
12505  // The id-expression was parenthesized.
12506  if (OrigOp.get() != DRE) {
12507  Diag(OpLoc, diag::err_parens_pointer_member_function)
12508  << OrigOp.get()->getSourceRange();
12509 
12510  // The method was named without a qualifier.
12511  } else if (!DRE->getQualifier()) {
12512  if (MD->getParent()->getName().empty())
12513  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12514  << op->getSourceRange();
12515  else {
12516  SmallString<32> Str;
12517  StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12518  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12519  << op->getSourceRange()
12521  }
12522  }
12523 
12524  // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12525  if (isa<CXXDestructorDecl>(MD))
12526  Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12527 
12528  QualType MPTy = Context.getMemberPointerType(
12529  op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12530  // Under the MS ABI, lock down the inheritance model now.
12531  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12532  (void)isCompleteType(OpLoc, MPTy);
12533  return MPTy;
12534  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12535  // C99 6.5.3.2p1
12536  // The operand must be either an l-value or a function designator
12537  if (!op->getType()->isFunctionType()) {
12538  // Use a special diagnostic for loads from property references.
12539  if (isa<PseudoObjectExpr>(op)) {
12540  AddressOfError = AO_Property_Expansion;
12541  } else {
12542  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12543  << op->getType() << op->getSourceRange();
12544  return QualType();
12545  }
12546  }
12547  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12548  // The operand cannot be a bit-field
12549  AddressOfError = AO_Bit_Field;
12550  } else if (op->getObjectKind() == OK_VectorComponent) {
12551  // The operand cannot be an element of a vector
12552  AddressOfError = AO_Vector_Element;
12553  } else if (dcl) { // C99 6.5.3.2p1
12554  // We have an lvalue with a decl. Make sure the decl is not declared
12555  // with the register storage-class specifier.
12556  if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12557  // in C++ it is not error to take address of a register
12558  // variable (c++03 7.1.1P3)
12559  if (vd->getStorageClass() == SC_Register &&
12560  !getLangOpts().CPlusPlus) {
12561  AddressOfError = AO_Register_Variable;
12562  }
12563  } else if (isa<MSPropertyDecl>(dcl)) {
12564  AddressOfError = AO_Property_Expansion;
12565  } else if (isa<FunctionTemplateDecl>(dcl)) {
12566  return Context.OverloadTy;
12567  } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12568  // Okay: we can take the address of a field.
12569  // Could be a pointer to member, though, if there is an explicit
12570  // scope qualifier for the class.
12571  if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12572  DeclContext *Ctx = dcl->getDeclContext();
12573  if (Ctx && Ctx->isRecord()) {
12574  if (dcl->getType()->isReferenceType()) {
12575  Diag(OpLoc,
12576  diag::err_cannot_form_pointer_to_member_of_reference_type)
12577  << dcl->getDeclName() << dcl->getType();
12578  return QualType();
12579  }
12580 
12581  while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12582  Ctx = Ctx->getParent();
12583 
12584  QualType MPTy = Context.getMemberPointerType(
12585  op->getType(),
12586  Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12587  // Under the MS ABI, lock down the inheritance model now.
12588  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12589  (void)isCompleteType(OpLoc, MPTy);
12590  return MPTy;
12591  }
12592  }
12593  } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12594  !isa<BindingDecl>(dcl))
12595  llvm_unreachable("Unknown/unexpected decl type");
12596  }
12597 
12598  if (AddressOfError != AO_No_Error) {
12599  diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12600  return QualType();
12601  }
12602 
12603  if (lval == Expr::LV_IncompleteVoidType) {
12604  // Taking the address of a void variable is technically illegal, but we
12605  // allow it in cases which are otherwise valid.
12606  // Example: "extern void x; void* y = &x;".
12607  Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12608  }
12609 
12610  // If the operand has type "type", the result has type "pointer to type".
12611  if (op->getType()->isObjCObjectType())
12612  return Context.getObjCObjectPointerType(op->getType());
12613 
12614  CheckAddressOfPackedMember(op);
12615 
12616  return Context.getPointerType(op->getType());
12617 }
12618 
12619 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12620  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12621  if (!DRE)
12622  return;
12623  const Decl *D = DRE->getDecl();
12624  if (!D)
12625  return;
12626  const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12627  if (!Param)
12628  return;
12629  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12630  if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12631  return;
12632  if (FunctionScopeInfo *FD = S.getCurFunction())
12633  if (!FD->ModifiedNonNullParams.count(Param))
12634  FD->ModifiedNonNullParams.insert(Param);
12635 }
12636 
12637 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12639  SourceLocation OpLoc) {
12640  if (Op->isTypeDependent())
12641  return S.Context.DependentTy;
12642 
12643  ExprResult ConvResult = S.UsualUnaryConversions(Op);
12644  if (ConvResult.isInvalid())
12645  return QualType();
12646  Op = ConvResult.get();
12647  QualType OpTy = Op->getType();
12648  QualType Result;
12649 
12650  if (isa<CXXReinterpretCastExpr>(Op)) {
12651  QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12652  S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12653  Op->getSourceRange());
12654  }
12655 
12656  if (const PointerType *PT = OpTy->getAs<PointerType>())
12657  {
12658  Result = PT->getPointeeType();
12659  }
12660  else if (const ObjCObjectPointerType *OPT =
12661  OpTy->getAs<ObjCObjectPointerType>())
12662  Result = OPT->getPointeeType();
12663  else {
12664  ExprResult PR = S.CheckPlaceholderExpr(Op);
12665  if (PR.isInvalid()) return QualType();
12666  if (PR.get() != Op)
12667  return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12668  }
12669 
12670  if (Result.isNull()) {
12671  S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12672  << OpTy << Op->getSourceRange();
12673  return QualType();
12674  }
12675 
12676  // Note that per both C89 and C99, indirection is always legal, even if Result
12677  // is an incomplete type or void. It would be possible to warn about
12678  // dereferencing a void pointer, but it's completely well-defined, and such a
12679  // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12680  // for pointers to 'void' but is fine for any other pointer type:
12681  //
12682  // C++ [expr.unary.op]p1:
12683  // [...] the expression to which [the unary * operator] is applied shall
12684  // be a pointer to an object type, or a pointer to a function type
12685  if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12686  S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12687  << OpTy << Op->getSourceRange();
12688 
12689  // Dereferences are usually l-values...
12690  VK = VK_LValue;
12691 
12692  // ...except that certain expressions are never l-values in C.
12693  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12694  VK = VK_RValue;
12695 
12696  return Result;
12697 }
12698 
12699 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12700  BinaryOperatorKind Opc;
12701  switch (Kind) {
12702  default: llvm_unreachable("Unknown binop!");
12703  case tok::periodstar: Opc = BO_PtrMemD; break;
12704  case tok::arrowstar: Opc = BO_PtrMemI; break;
12705  case tok::star: Opc = BO_Mul; break;
12706  case tok::slash: Opc = BO_Div; break;
12707  case tok::percent: Opc = BO_Rem; break;
12708  case tok::plus: Opc = BO_Add; break;
12709  case tok::minus: Opc = BO_Sub; break;
12710  case tok::lessless: Opc = BO_Shl; break;
12711  case tok::greatergreater: Opc = BO_Shr; break;
12712  case tok::lessequal: Opc = BO_LE; break;
12713  case tok::less: Opc = BO_LT; break;
12714  case tok::greaterequal: Opc = BO_GE; break;
12715  case tok::greater: Opc = BO_GT; break;
12716  case tok::exclaimequal: Opc = BO_NE; break;
12717  case tok::equalequal: Opc = BO_EQ; break;
12718  case tok::spaceship: Opc = BO_Cmp; break;
12719  case tok::amp: Opc = BO_And; break;
12720  case tok::caret: Opc = BO_Xor; break;
12721  case tok::pipe: Opc = BO_Or; break;
12722  case tok::ampamp: Opc = BO_LAnd; break;
12723  case tok::pipepipe: Opc = BO_LOr; break;
12724  case tok::equal: Opc = BO_Assign; break;
12725  case tok::starequal: Opc = BO_MulAssign; break;
12726  case tok::slashequal: Opc = BO_DivAssign; break;
12727  case tok::percentequal: Opc = BO_RemAssign; break;
12728  case tok::plusequal: Opc = BO_AddAssign; break;
12729  case tok::minusequal: Opc = BO_SubAssign; break;
12730  case tok::lesslessequal: Opc = BO_ShlAssign; break;
12731  case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
12732  case tok::ampequal: Opc = BO_AndAssign; break;
12733  case tok::caretequal: Opc = BO_XorAssign; break;
12734  case tok::pipeequal: Opc = BO_OrAssign; break;
12735  case tok::comma: Opc = BO_Comma; break;
12736  }
12737  return Opc;
12738 }
12739 
12741  tok::TokenKind Kind) {
12742  UnaryOperatorKind Opc;
12743  switch (Kind) {
12744  default: llvm_unreachable("Unknown unary op!");
12745  case tok::plusplus: Opc = UO_PreInc; break;
12746  case tok::minusminus: Opc = UO_PreDec; break;
12747  case tok::amp: Opc = UO_AddrOf; break;
12748  case tok::star: Opc = UO_Deref; break;
12749  case tok::plus: Opc = UO_Plus; break;
12750  case tok::minus: Opc = UO_Minus; break;
12751  case tok::tilde: Opc = UO_Not; break;
12752  case tok::exclaim: Opc = UO_LNot; break;
12753  case tok::kw___real: Opc = UO_Real; break;
12754  case tok::kw___imag: Opc = UO_Imag; break;
12755  case tok::kw___extension__: Opc = UO_Extension; break;
12756  }
12757  return Opc;
12758 }
12759 
12760 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12761 /// This warning suppressed in the event of macro expansions.
12762 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12763  SourceLocation OpLoc, bool IsBuiltin) {
12764  if (S.inTemplateInstantiation())
12765  return;
12766  if (S.isUnevaluatedContext())
12767  return;
12768  if (OpLoc.isInvalid() || OpLoc.isMacroID())
12769  return;
12770  LHSExpr = LHSExpr->IgnoreParenImpCasts();
12771  RHSExpr = RHSExpr->IgnoreParenImpCasts();
12772  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12773  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12774  if (!LHSDeclRef || !RHSDeclRef ||
12775  LHSDeclRef->getLocation().isMacroID() ||
12776  RHSDeclRef->getLocation().isMacroID())
12777  return;
12778  const ValueDecl *LHSDecl =
12779  cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12780  const ValueDecl *RHSDecl =
12781  cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12782  if (LHSDecl != RHSDecl)
12783  return;
12784  if (LHSDecl->getType().isVolatileQualified())
12785  return;
12786  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12787  if (RefTy->getPointeeType().isVolatileQualified())
12788  return;
12789 
12790  S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12791  : diag::warn_self_assignment_overloaded)
12792  << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12793  << RHSExpr->getSourceRange();
12794 }
12795 
12796 /// Check if a bitwise-& is performed on an Objective-C pointer. This
12797 /// is usually indicative of introspection within the Objective-C pointer.
12799  SourceLocation OpLoc) {
12800  if (!S.getLangOpts().ObjC)
12801  return;
12802 
12803  const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12804  const Expr *LHS = L.get();
12805  const Expr *RHS = R.get();
12806 
12808  ObjCPointerExpr = LHS;
12809  OtherExpr = RHS;
12810  }
12811  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12812  ObjCPointerExpr = RHS;
12813  OtherExpr = LHS;
12814  }
12815 
12816  // This warning is deliberately made very specific to reduce false
12817  // positives with logic that uses '&' for hashing. This logic mainly
12818  // looks for code trying to introspect into tagged pointers, which
12819  // code should generally never do.
12820  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12821  unsigned Diag = diag::warn_objc_pointer_masking;
12822  // Determine if we are introspecting the result of performSelectorXXX.
12823  const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12824  // Special case messages to -performSelector and friends, which
12825  // can return non-pointer values boxed in a pointer value.
12826  // Some clients may wish to silence warnings in this subcase.
12827  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12828  Selector S = ME->getSelector();
12829  StringRef SelArg0 = S.getNameForSlot(0);
12830  if (SelArg0.startswith("performSelector"))
12831  Diag = diag::warn_objc_pointer_masking_performSelector;
12832  }
12833 
12834  S.Diag(OpLoc, Diag)
12835  << ObjCPointerExpr->getSourceRange();
12836  }
12837 }
12838 
12840  if (!E)
12841  return nullptr;
12842  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12843  return DRE->getDecl();
12844  if (auto *ME = dyn_cast<MemberExpr>(E))
12845  return ME->getMemberDecl();
12846  if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12847  return IRE->getDecl();
12848  return nullptr;
12849 }
12850 
12851 // This helper function promotes a binary operator's operands (which are of a
12852 // half vector type) to a vector of floats and then truncates the result to
12853 // a vector of either half or short.
12855  BinaryOperatorKind Opc, QualType ResultTy,
12857  bool IsCompAssign, SourceLocation OpLoc,
12858  FPOptions FPFeatures) {
12859  auto &Context = S.getASTContext();
12860  assert((isVector(ResultTy, Context.HalfTy) ||
12861  isVector(ResultTy, Context.ShortTy)) &&
12862  "Result must be a vector of half or short");
12863  assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12864  isVector(RHS.get()->getType(), Context.HalfTy) &&
12865  "both operands expected to be a half vector");
12866 
12867  RHS = convertVector(RHS.get(), Context.FloatTy, S);
12868  QualType BinOpResTy = RHS.get()->getType();
12869 
12870  // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12871  // change BinOpResTy to a vector of ints.
12872  if (isVector(ResultTy, Context.ShortTy))
12873  BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12874 
12875  if (IsCompAssign)
12876  return new (Context) CompoundAssignOperator(
12877  LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12878  OpLoc, FPFeatures);
12879 
12880  LHS = convertVector(LHS.get(), Context.FloatTy, S);
12881  auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12882  VK, OK, OpLoc, FPFeatures);
12883  return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12884 }
12885 
12886 static std::pair<ExprResult, ExprResult>
12888  Expr *RHSExpr) {
12889  ExprResult LHS = LHSExpr, RHS = RHSExpr;
12890  if (!S.getLangOpts().CPlusPlus) {
12891  // C cannot handle TypoExpr nodes on either side of a binop because it
12892  // doesn't handle dependent types properly, so make sure any TypoExprs have
12893  // been dealt with before checking the operands.
12894  LHS = S.CorrectDelayedTyposInExpr(LHS);
12895  RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12896  if (Opc != BO_Assign)
12897  return ExprResult(E);
12898  // Avoid correcting the RHS to the same Expr as the LHS.
12899  Decl *D = getDeclFromExpr(E);
12900  return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12901  });
12902  }
12903  return std::make_pair(LHS, RHS);
12904 }
12905 
12906 /// Returns true if conversion between vectors of halfs and vectors of floats
12907 /// is needed.
12908 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12909  QualType SrcType) {
12910  return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12912  isVector(SrcType, Ctx.HalfTy);
12913 }
12914 
12915 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12916 /// operator @p Opc at location @c TokLoc. This routine only supports
12917 /// built-in operations; ActOnBinOp handles overloaded operators.
12919  BinaryOperatorKind Opc,
12920  Expr *LHSExpr, Expr *RHSExpr) {
12921  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12922  // The syntax only allows initializer lists on the RHS of assignment,
12923  // so we don't need to worry about accepting invalid code for
12924  // non-assignment operators.
12925  // C++11 5.17p9:
12926  // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12927  // of x = {} is x = T().
12929  RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12930  InitializedEntity Entity =
12932  InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12933  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12934  if (Init.isInvalid())
12935  return Init;
12936  RHSExpr = Init.get();
12937  }
12938 
12939  ExprResult LHS = LHSExpr, RHS = RHSExpr;
12940  QualType ResultTy; // Result type of the binary operator.
12941  // The following two variables are used for compound assignment operators
12942  QualType CompLHSTy; // Type of LHS after promotions for computation
12943  QualType CompResultTy; // Type of computation result
12944  ExprValueKind VK = VK_RValue;
12946  bool ConvertHalfVec = false;
12947 
12948  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12949  if (!LHS.isUsable() || !RHS.isUsable())
12950  return ExprError();
12951 
12952  if (getLangOpts().OpenCL) {
12953  QualType LHSTy = LHSExpr->getType();
12954  QualType RHSTy = RHSExpr->getType();
12955  // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12956  // the ATOMIC_VAR_INIT macro.
12957  if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12958  SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12959  if (BO_Assign == Opc)
12960  Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12961  else
12962  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12963  return ExprError();
12964  }
12965 
12966  // OpenCL special types - image, sampler, pipe, and blocks are to be used
12967  // only with a builtin functions and therefore should be disallowed here.
12968  if (LHSTy->isImageType() || RHSTy->isImageType() ||
12969  LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12970  LHSTy->isPipeType() || RHSTy->isPipeType() ||
12971  LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12972  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12973  return ExprError();
12974  }
12975  }
12976 
12977  // Diagnose operations on the unsupported types for OpenMP device compilation.
12978  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12979  if (Opc != BO_Assign && Opc != BO_Comma) {
12980  checkOpenMPDeviceExpr(LHSExpr);
12981  checkOpenMPDeviceExpr(RHSExpr);
12982  }
12983  }
12984 
12985  switch (Opc) {
12986  case BO_Assign:
12987  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12988  if (getLangOpts().CPlusPlus &&
12989  LHS.get()->getObjectKind() != OK_ObjCProperty) {
12990  VK = LHS.get()->getValueKind();
12991  OK = LHS.get()->getObjectKind();
12992  }
12993  if (!ResultTy.isNull()) {
12994  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12995  DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12996 
12997  // Avoid copying a block to the heap if the block is assigned to a local
12998  // auto variable that is declared in the same scope as the block. This
12999  // optimization is unsafe if the local variable is declared in an outer
13000  // scope. For example:
13001  //
13002  // BlockTy b;
13003  // {
13004  // b = ^{...};
13005  // }
13006  // // It is unsafe to invoke the block here if it wasn't copied to the
13007  // // heap.
13008  // b();
13009 
13010  if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13011  if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13012  if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13013  if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13014  BE->getBlockDecl()->setCanAvoidCopyToHeap();
13015 
13016  if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13017  checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13018  NTCUC_Assignment, NTCUK_Copy);
13019  }
13020  RecordModifiableNonNullParam(*this, LHS.get());
13021  break;
13022  case BO_PtrMemD:
13023  case BO_PtrMemI:
13024  ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13025  Opc == BO_PtrMemI);
13026  break;
13027  case BO_Mul:
13028  case BO_Div:
13029  ConvertHalfVec = true;
13030  ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13031  Opc == BO_Div);
13032  break;
13033  case BO_Rem:
13034  ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13035  break;
13036  case BO_Add:
13037  ConvertHalfVec = true;
13038  ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13039  break;
13040  case BO_Sub:
13041  ConvertHalfVec = true;
13042  ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13043  break;
13044  case BO_Shl:
13045  case BO_Shr:
13046  ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13047  break;
13048  case BO_LE:
13049  case BO_LT:
13050  case BO_GE:
13051  case BO_GT:
13052  ConvertHalfVec = true;
13053  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13054  break;
13055  case BO_EQ:
13056  case BO_NE:
13057  ConvertHalfVec = true;
13058  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13059  break;
13060  case BO_Cmp:
13061  ConvertHalfVec = true;
13062  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13063  assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13064  break;
13065  case BO_And:
13066  checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13067  LLVM_FALLTHROUGH;
13068  case BO_Xor:
13069  case BO_Or:
13070  ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13071  break;
13072  case BO_LAnd:
13073  case BO_LOr:
13074  ConvertHalfVec = true;
13075  ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13076  break;
13077  case BO_MulAssign:
13078  case BO_DivAssign:
13079  ConvertHalfVec = true;
13080  CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13081  Opc == BO_DivAssign);
13082  CompLHSTy = CompResultTy;
13083  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13084  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13085  break;
13086  case BO_RemAssign:
13087  CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13088  CompLHSTy = CompResultTy;
13089  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13090  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13091  break;
13092  case BO_AddAssign:
13093  ConvertHalfVec = true;
13094  CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13095  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13096  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13097  break;
13098  case BO_SubAssign:
13099  ConvertHalfVec = true;
13100  CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13101  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13102  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13103  break;
13104  case BO_ShlAssign:
13105  case BO_ShrAssign:
13106  CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13107  CompLHSTy = CompResultTy;
13108  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13109  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13110  break;
13111  case BO_AndAssign:
13112  case BO_OrAssign: // fallthrough
13113  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13114  LLVM_FALLTHROUGH;
13115  case BO_XorAssign:
13116  CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13117  CompLHSTy = CompResultTy;
13118  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13119  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13120  break;
13121  case BO_Comma:
13122  ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13123  if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13124  VK = RHS.get()->getValueKind();
13125  OK = RHS.get()->getObjectKind();
13126  }
13127  break;
13128  }
13129  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13130  return ExprError();
13131 
13132  if (ResultTy->isRealFloatingType() &&
13133  (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest ||
13134  getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13135  // Mark the current function as usng floating point constrained intrinsics
13136  if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13137  F->setUsesFPIntrin(true);
13138  }
13139 
13140  // Some of the binary operations require promoting operands of half vector to
13141  // float vectors and truncating the result back to half vector. For now, we do
13142  // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13143  // arm64).
13144  assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13145  isVector(LHS.get()->getType(), Context.HalfTy) &&
13146  "both sides are half vectors or neither sides are");
13147  ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
13148  LHS.get()->getType());
13149 
13150  // Check for array bounds violations for both sides of the BinaryOperator
13151  CheckArrayAccess(LHS.get());
13152  CheckArrayAccess(RHS.get());
13153 
13154  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13155  NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13156  &Context.Idents.get("object_setClass"),
13157  SourceLocation(), LookupOrdinaryName);
13158  if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13159  SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13160  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13161  << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13162  "object_setClass(")
13163  << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13164  ",")
13165  << FixItHint::CreateInsertion(RHSLocEnd, ")");
13166  }
13167  else
13168  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13169  }
13170  else if (const ObjCIvarRefExpr *OIRE =
13171  dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13172  DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13173 
13174  // Opc is not a compound assignment if CompResultTy is null.
13175  if (CompResultTy.isNull()) {
13176  if (ConvertHalfVec)
13177  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13178  OpLoc, FPFeatures);
13179  return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13180  OK, OpLoc, FPFeatures);
13181  }
13182 
13183  // Handle compound assignments.
13184  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13185  OK_ObjCProperty) {
13186  VK = VK_LValue;
13187  OK = LHS.get()->getObjectKind();
13188  }
13189 
13190  if (ConvertHalfVec)
13191  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13192  OpLoc, FPFeatures);
13193 
13194  return new (Context) CompoundAssignOperator(
13195  LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13196  OpLoc, FPFeatures);
13197 }
13198 
13199 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13200 /// operators are mixed in a way that suggests that the programmer forgot that
13201 /// comparison operators have higher precedence. The most typical example of
13202 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13204  SourceLocation OpLoc, Expr *LHSExpr,
13205  Expr *RHSExpr) {
13206  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13207  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13208 
13209  // Check that one of the sides is a comparison operator and the other isn't.
13210  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13211  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13212  if (isLeftComp == isRightComp)
13213  return;
13214 
13215  // Bitwise operations are sometimes used as eager logical ops.
13216  // Don't diagnose this.
13217  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13218  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13219  if (isLeftBitwise || isRightBitwise)
13220  return;
13221 
13222  SourceRange DiagRange = isLeftComp
13223  ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13224  : SourceRange(OpLoc, RHSExpr->getEndLoc());
13225  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13226  SourceRange ParensRange =
13227  isLeftComp
13228  ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13229  : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13230 
13231  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13232  << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13233  SuggestParentheses(Self, OpLoc,
13234  Self.PDiag(diag::note_precedence_silence) << OpStr,
13235  (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13236  SuggestParentheses(Self, OpLoc,
13237  Self.PDiag(diag::note_precedence_bitwise_first)
13239  ParensRange);
13240 }
13241 
13242 /// It accepts a '&&' expr that is inside a '||' one.
13243 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13244 /// in parentheses.
13245 static void
13247  BinaryOperator *Bop) {
13248  assert(Bop->getOpcode() == BO_LAnd);
13249  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13250  << Bop->getSourceRange() << OpLoc;
13251  SuggestParentheses(Self, Bop->getOperatorLoc(),
13252  Self.PDiag(diag::note_precedence_silence)
13253  << Bop->getOpcodeStr(),
13254  Bop->getSourceRange());
13255 }
13256 
13257 /// Returns true if the given expression can be evaluated as a constant
13258 /// 'true'.
13259 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13260  bool Res;
13261  return !E->isValueDependent() &&
13262  E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13263 }
13264 
13265 /// Returns true if the given expression can be evaluated as a constant
13266 /// 'false'.
13267 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13268  bool Res;
13269  return !E->isValueDependent() &&
13270  E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13271 }
13272 
13273 /// Look for '&&' in the left hand of a '||' expr.
13275  Expr *LHSExpr, Expr *RHSExpr) {
13276  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13277  if (Bop->getOpcode() == BO_LAnd) {
13278  // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13279  if (EvaluatesAsFalse(S, RHSExpr))
13280  return;
13281  // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13282  if (!EvaluatesAsTrue(S, Bop->getLHS()))
13283  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13284  } else if (Bop->getOpcode() == BO_LOr) {
13285  if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13286  // If it's "a || b && 1 || c" we didn't warn earlier for
13287  // "a || b && 1", but warn now.
13288  if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13289  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13290  }
13291  }
13292  }
13293 }
13294 
13295 /// Look for '&&' in the right hand of a '||' expr.
13297  Expr *LHSExpr, Expr *RHSExpr) {
13298  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13299  if (Bop->getOpcode() == BO_LAnd) {
13300  // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13301  if (EvaluatesAsFalse(S, LHSExpr))
13302  return;
13303  // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13304  if (!EvaluatesAsTrue(S, Bop->getRHS()))
13305  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13306  }
13307  }
13308 }
13309 
13310 /// Look for bitwise op in the left or right hand of a bitwise op with
13311 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13312 /// the '&' expression in parentheses.
13314  SourceLocation OpLoc, Expr *SubExpr) {
13315  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13316  if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13317  S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13318  << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13319  << Bop->getSourceRange() << OpLoc;
13320  SuggestParentheses(S, Bop->getOperatorLoc(),
13321  S.PDiag(diag::note_precedence_silence)
13322  << Bop->getOpcodeStr(),
13323  Bop->getSourceRange());
13324  }
13325  }
13326 }
13327 
13329  Expr *SubExpr, StringRef Shift) {
13330  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13331  if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13332  StringRef Op = Bop->getOpcodeStr();
13333  S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13334  << Bop->getSourceRange() << OpLoc << Shift << Op;
13335  SuggestParentheses(S, Bop->getOperatorLoc(),
13336  S.PDiag(diag::note_precedence_silence) << Op,
13337  Bop->getSourceRange());
13338  }
13339  }
13340 }
13341 
13343  Expr *LHSExpr, Expr *RHSExpr) {
13344  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13345  if (!OCE)
13346  return;
13347 
13348  FunctionDecl *FD = OCE->getDirectCallee();
13349  if (!FD || !FD->isOverloadedOperator())
13350  return;
13351 
13353  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13354  return;
13355 
13356  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13357  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13358  << (Kind == OO_LessLess);
13360  S.PDiag(diag::note_precedence_silence)
13361  << (Kind == OO_LessLess ? "<<" : ">>"),
13362  OCE->getSourceRange());
13364  S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13365  SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13366 }
13367 
13368 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13369 /// precedence.
13371  SourceLocation OpLoc, Expr *LHSExpr,
13372  Expr *RHSExpr){
13373  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13374  if (BinaryOperator::isBitwiseOp(Opc))
13375  DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13376 
13377  // Diagnose "arg1 & arg2 | arg3"
13378  if ((Opc == BO_Or || Opc == BO_Xor) &&
13379  !OpLoc.isMacroID()/* Don't warn in macros. */) {
13380  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13381  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13382  }
13383 
13384  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13385  // We don't warn for 'assert(a || b && "bad")' since this is safe.
13386  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13387  DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13388  DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13389  }
13390 
13391  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13392  || Opc == BO_Shr) {
13393  StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13394  DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13395  DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13396  }
13397 
13398  // Warn on overloaded shift operators and comparisons, such as:
13399  // cout << 5 == 4;
13401  DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13402 }
13403 
13404 // Binary Operators. 'Tok' is the token for the operator.
13406  tok::TokenKind Kind,
13407  Expr *LHSExpr, Expr *RHSExpr) {
13408  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13409  assert(LHSExpr && "ActOnBinOp(): missing left expression");
13410  assert(RHSExpr && "ActOnBinOp(): missing right expression");
13411 
13412  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13413  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13414 
13415  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13416 }
13417 
13418 /// Build an overloaded binary operator expression in the given scope.
13420  BinaryOperatorKind Opc,
13421  Expr *LHS, Expr *RHS) {
13422  switch (Opc) {
13423  case BO_Assign:
13424  case BO_DivAssign:
13425  case BO_RemAssign:
13426  case BO_SubAssign:
13427  case BO_AndAssign:
13428  case BO_OrAssign:
13429  case BO_XorAssign:
13430  DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13431  CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13432  break;
13433  default:
13434  break;
13435  }
13436 
13437  // Find all of the overloaded operators visible from this
13438  // point. We perform both an operator-name lookup from the local
13439  // scope and an argument-dependent lookup based on the types of
13440  // the arguments.
13441  UnresolvedSet<16> Functions;
13442  OverloadedOperatorKind OverOp
13444  if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13445  S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13446  RHS->getType(), Functions);
13447 
13448  // In C++20 onwards, we may have a second operator to look up.
13449  if (S.getLangOpts().CPlusPlus2a) {
13451  S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13452  RHS->getType(), Functions);
13453  }
13454 
13455  // Build the (potentially-overloaded, potentially-dependent)
13456  // binary operation.
13457  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13458 }
13459 
13461  BinaryOperatorKind Opc,
13462  Expr *LHSExpr, Expr *RHSExpr) {
13463  ExprResult LHS, RHS;
13464  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13465  if (!LHS.isUsable() || !RHS.isUsable())
13466  return ExprError();
13467  LHSExpr = LHS.get();
13468  RHSExpr = RHS.get();
13469 
13470  // We want to end up calling one of checkPseudoObjectAssignment
13471  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13472  // both expressions are overloadable or either is type-dependent),
13473  // or CreateBuiltinBinOp (in any other case). We also want to get
13474  // any placeholder types out of the way.
13475 
13476  // Handle pseudo-objects in the LHS.
13477  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13478  // Assignments with a pseudo-object l-value need special analysis.
13479  if (pty->getKind() == BuiltinType::PseudoObject &&
13481  return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13482 
13483  // Don't resolve overloads if the other type is overloadable.
13484  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13485  // We can't actually test that if we still have a placeholder,
13486  // though. Fortunately, none of the exceptions we see in that
13487  // code below are valid when the LHS is an overload set. Note
13488  // that an overload set can be dependently-typed, but it never
13489  // instantiates to having an overloadable type.
13490  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13491  if (resolvedRHS.isInvalid()) return ExprError();
13492  RHSExpr = resolvedRHS.get();
13493 
13494  if (RHSExpr->isTypeDependent() ||
13495  RHSExpr->getType()->isOverloadableType())
13496  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13497  }
13498 
13499  // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13500  // template, diagnose the missing 'template' keyword instead of diagnosing
13501  // an invalid use of a bound member function.
13502  //
13503  // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13504  // to C++1z [over.over]/1.4, but we already checked for that case above.
13505  if (Opc == BO_LT && inTemplateInstantiation() &&
13506  (pty->getKind() == BuiltinType::BoundMember ||
13507  pty->getKind() == BuiltinType::Overload)) {
13508  auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13509  if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13510  std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13511  return isa<FunctionTemplateDecl>(ND);
13512  })) {
13513  Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13514  : OE->getNameLoc(),
13515  diag::err_template_kw_missing)
13516  << OE->getName().getAsString() << "";
13517  return ExprError();
13518  }
13519  }
13520 
13521  ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13522  if (LHS.isInvalid()) return ExprError();
13523  LHSExpr = LHS.get();
13524  }
13525 
13526  // Handle pseudo-objects in the RHS.
13527  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13528  // An overload in the RHS can potentially be resolved by the type
13529  // being assigned to.
13530  if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13531  if (getLangOpts().CPlusPlus &&
13532  (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13533  LHSExpr->getType()->isOverloadableType()))
13534  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13535 
13536  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13537  }
13538 
13539  // Don't resolve overloads if the other type is overloadable.
13540  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13541  LHSExpr->getType()->isOverloadableType())
13542  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13543 
13544  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13545  if (!resolvedRHS.isUsable()) return ExprError();
13546  RHSExpr = resolvedRHS.get();
13547  }
13548 
13549  if (getLangOpts().CPlusPlus) {
13550  // If either expression is type-dependent, always build an
13551  // overloaded op.
13552  if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13553  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13554 
13555  // Otherwise, build an overloaded op if either expression has an
13556  // overloadable type.
13557  if (LHSExpr->getType()->isOverloadableType() ||
13558  RHSExpr->getType()->isOverloadableType())
13559  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13560  }
13561 
13562  // Build a built-in binary operation.
13563  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13564 }
13565 
13567  if (T.isNull() || T->isDependentType())
13568  return false;
13569 
13570  if (!T->isPromotableIntegerType())
13571  return true;
13572 
13573  return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13574 }
13575 
13577  UnaryOperatorKind Opc,
13578  Expr *InputExpr) {
13579  ExprResult Input = InputExpr;
13580  ExprValueKind VK = VK_RValue;
13582  QualType resultType;
13583  bool CanOverflow = false;
13584 
13585  bool ConvertHalfVec = false;
13586  if (getLangOpts().OpenCL) {
13587  QualType Ty = InputExpr->getType();
13588  // The only legal unary operation for atomics is '&'.
13589  if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13590  // OpenCL special types - image, sampler, pipe, and blocks are to be used
13591  // only with a builtin functions and therefore should be disallowed here.
13592  (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13593  || Ty->isBlockPointerType())) {
13594  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13595  << InputExpr->getType()
13596  << Input.get()->getSourceRange());
13597  }
13598  }
13599  // Diagnose operations on the unsupported types for OpenMP device compilation.
13600  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13603  checkOpenMPDeviceExpr(InputExpr);
13604  }
13605 
13606  switch (Opc) {
13607  case UO_PreInc:
13608  case UO_PreDec:
13609  case UO_PostInc:
13610  case UO_PostDec:
13611  resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13612  OpLoc,
13613  Opc == UO_PreInc ||
13614  Opc == UO_PostInc,
13615  Opc == UO_PreInc ||
13616  Opc == UO_PreDec);
13617  CanOverflow = isOverflowingIntegerType(Context, resultType);
13618  break;
13619  case UO_AddrOf:
13620  resultType = CheckAddressOfOperand(Input, OpLoc);
13621  CheckAddressOfNoDeref(InputExpr);
13622  RecordModifiableNonNullParam(*this, InputExpr);
13623  break;
13624  case UO_Deref: {
13625  Input = DefaultFunctionArrayLvalueConversion(Input.get());
13626  if (Input.isInvalid()) return ExprError();
13627  resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13628  break;
13629  }
13630  case UO_Plus:
13631  case UO_Minus:
13632  CanOverflow = Opc == UO_Minus &&
13633  isOverflowingIntegerType(Context, Input.get()->getType());
13634  Input = UsualUnaryConversions(Input.get());
13635  if (Input.isInvalid()) return ExprError();
13636  // Unary plus and minus require promoting an operand of half vector to a
13637  // float vector and truncating the result back to a half vector. For now, we
13638  // do this only when HalfArgsAndReturns is set (that is, when the target is
13639  // arm or arm64).
13640  ConvertHalfVec =
13641  needsConversionOfHalfVec(true, Context, Input.get()->getType());
13642 
13643  // If the operand is a half vector, promote it to a float vector.
13644  if (ConvertHalfVec)
13645  Input = convertVector(Input.get(), Context.FloatTy, *this);
13646  resultType = Input.get()->getType();
13647  if (resultType->isDependentType())
13648  break;
13649  if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13650  break;
13651  else if (resultType->isVectorType() &&
13652  // The z vector extensions don't allow + or - with bool vectors.
13653  (!Context.getLangOpts().ZVector ||
13654  resultType->castAs<VectorType>()->getVectorKind() !=
13656  break;
13657  else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13658  Opc == UO_Plus &&
13659  resultType->isPointerType())
13660  break;
13661 
13662  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13663  << resultType << Input.get()->getSourceRange());
13664 
13665  case UO_Not: // bitwise complement
13666  Input = UsualUnaryConversions(Input.get());
13667  if (Input.isInvalid())
13668  return ExprError();
13669  resultType = Input.get()->getType();
13670  if (resultType->isDependentType())
13671  break;
13672  // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13673  if (resultType->isComplexType() || resultType->isComplexIntegerType())
13674  // C99 does not support '~' for complex conjugation.
13675  Diag(OpLoc, diag::ext_integer_complement_complex)
13676  << resultType << Input.get()->getSourceRange();
13677  else if (resultType->hasIntegerRepresentation())
13678  break;
13679  else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13680  // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13681  // on vector float types.
13682  QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13683  if (!T->isIntegerType())
13684  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13685  << resultType << Input.get()->getSourceRange());
13686  } else {
13687  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13688  << resultType << Input.get()->getSourceRange());
13689  }
13690  break;
13691 
13692  case UO_LNot: // logical negation
13693  // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13694  Input = DefaultFunctionArrayLvalueConversion(Input.get());
13695  if (Input.isInvalid()) return ExprError();
13696  resultType = Input.get()->getType();
13697 
13698  // Though we still have to promote half FP to float...
13699  if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13700  Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13701  resultType = Context.FloatTy;
13702  }
13703 
13704  if (resultType->isDependentType())
13705  break;
13706  if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13707  // C99 6.5.3.3p1: ok, fallthrough;
13708  if (Context.getLangOpts().CPlusPlus) {
13709  // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13710  // operand contextually converted to bool.
13711  Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13712  ScalarTypeToBooleanCastKind(resultType));
13713  } else if (Context.getLangOpts().OpenCL &&
13714  Context.getLangOpts().OpenCLVersion < 120) {
13715  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13716  // operate on scalar float types.
13717  if (!resultType->isIntegerType() && !resultType->isPointerType())
13718  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13719  << resultType << Input.get()->getSourceRange());
13720  }
13721  } else if (resultType->isExtVectorType()) {
13722  if (Context.getLangOpts().OpenCL &&
13723  Context.getLangOpts().OpenCLVersion < 120 &&
13724  !Context.getLangOpts().OpenCLCPlusPlus) {
13725  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13726  // operate on vector float types.
13727  QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13728  if (!T->isIntegerType())
13729  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13730  << resultType << Input.get()->getSourceRange());
13731  }
13732  // Vector logical not returns the signed variant of the operand type.
13733  resultType = GetSignedVectorType(resultType);
13734  break;
13735  } else {
13736  // FIXME: GCC's vector extension permits the usage of '!' with a vector
13737  // type in C++. We should allow that here too.
13738  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13739  << resultType << Input.get()->getSourceRange());
13740  }
13741 
13742  // LNot always has type int. C99 6.5.3.3p5.
13743  // In C++, it's bool. C++ 5.3.1p8
13744  resultType = Context.getLogicalOperationType();
13745  break;
13746  case UO_Real:
13747  case UO_Imag:
13748  resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13749  // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13750  // complex l-values to ordinary l-values and all other values to r-values.
13751  if (Input.isInvalid()) return ExprError();
13752  if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13753  if (Input.get()->getValueKind() != VK_RValue &&
13754  Input.get()->getObjectKind() == OK_Ordinary)
13755  VK = Input.get()->getValueKind();
13756  } else if (!getLangOpts().CPlusPlus) {
13757  // In C, a volatile scalar is read by __imag. In C++, it is not.
13758  Input = DefaultLvalueConversion(Input.get());
13759  }
13760  break;
13761  case UO_Extension:
13762  resultType = Input.get()->getType();
13763  VK = Input.get()->getValueKind();
13764  OK = Input.get()->getObjectKind();
13765  break;
13766  case UO_Coawait:
13767  // It's unnecessary to represent the pass-through operator co_await in the
13768  // AST; just return the input expression instead.
13769  assert(!Input.get()->getType()->isDependentType() &&
13770  "the co_await expression must be non-dependant before "
13771  "building operator co_await");
13772  return Input;
13773  }
13774  if (resultType.isNull() || Input.isInvalid())
13775  return ExprError();
13776 
13777  // Check for array bounds violations in the operand of the UnaryOperator,
13778  // except for the '*' and '&' operators that have to be handled specially
13779  // by CheckArrayAccess (as there are special cases like &array[arraysize]
13780  // that are explicitly defined as valid by the standard).
13781  if (Opc != UO_AddrOf && Opc != UO_Deref)
13782  CheckArrayAccess(Input.get());
13783 
13784  auto *UO = new (Context)
13785  UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13786 
13787  if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13788  !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13789  ExprEvalContexts.back().PossibleDerefs.insert(UO);
13790 
13791  // Convert the result back to a half vector.
13792  if (ConvertHalfVec)
13793  return convertVector(UO, Context.HalfTy, *this);
13794  return UO;
13795 }
13796 
13797 /// Determine whether the given expression is a qualified member
13798 /// access expression, of a form that could be turned into a pointer to member
13799 /// with the address-of operator.
13801  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13802  if (!DRE->getQualifier())
13803  return false;
13804 
13805  ValueDecl *VD = DRE->getDecl();
13806  if (!VD->isCXXClassMember())
13807  return false;
13808 
13809  if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13810  return true;
13811  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13812  return Method->isInstance();
13813 
13814  return false;
13815  }
13816 
13817  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13818  if (!ULE->getQualifier())
13819  return false;
13820 
13821  for (NamedDecl *D : ULE->decls()) {
13822  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13823  if (Method->isInstance())
13824  return true;
13825  } else {
13826  // Overload set does not contain methods.
13827  break;
13828  }
13829  }
13830 
13831  return false;
13832  }
13833 
13834  return false;
13835 }
13836 
13838  UnaryOperatorKind Opc, Expr *Input) {
13839  // First things first: handle placeholders so that the
13840  // overloaded-operator check considers the right type.
13841  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13842  // Increment and decrement of pseudo-object references.
13843  if (pty->getKind() == BuiltinType::PseudoObject &&
13845  return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13846 
13847  // extension is always a builtin operator.
13848  if (Opc == UO_Extension)
13849  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13850 
13851  // & gets special logic for several kinds of placeholder.
13852  // The builtin code knows what to do.
13853  if (Opc == UO_AddrOf &&
13854  (pty->getKind() == BuiltinType::Overload ||
13855  pty->getKind() == BuiltinType::UnknownAny ||
13856  pty->getKind() == BuiltinType::BoundMember))
13857  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13858 
13859  // Anything else needs to be handled now.
13860  ExprResult Result = CheckPlaceholderExpr(Input);
13861  if (Result.isInvalid()) return ExprError();
13862  Input = Result.get();
13863  }
13864 
13865  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13867  !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13868  // Find all of the overloaded operators visible from this
13869  // point. We perform both an operator-name lookup from the local
13870  // scope and an argument-dependent lookup based on the types of
13871  // the arguments.
13872  UnresolvedSet<16> Functions;
13874  if (S && OverOp != OO_None)
13875  LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13876  Functions);
13877 
13878  return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13879  }
13880 
13881  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13882 }
13883 
13884 // Unary Operators. 'Tok' is the token for the operator.
13886  tok::TokenKind Op, Expr *Input) {
13887  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13888 }
13889 
13890 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13892  LabelDecl *TheDecl) {
13893  TheDecl->markUsed(Context);
13894  // Create the AST node. The address of a label always has type 'void*'.
13895  return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13896  Context.getPointerType(Context.VoidTy));
13897 }
13898 
13900  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13901 }
13902 
13904  // Note that function is also called by TreeTransform when leaving a
13905  // StmtExpr scope without rebuilding anything.
13906 
13907  DiscardCleanupsInEvaluationContext();
13908  PopExpressionEvaluationContext();
13909 }
13910 
13911 ExprResult
13913  SourceLocation RPLoc) { // "({..})"
13914  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13915  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13916 
13917  if (hasAnyUnrecoverableErrorsInThisFunction())
13918  DiscardCleanupsInEvaluationContext();
13919  assert(!Cleanup.exprNeedsCleanups() &&
13920  "cleanups within StmtExpr not correctly bound!");
13921  PopExpressionEvaluationContext();
13922 
13923  // FIXME: there are a variety of strange constraints to enforce here, for
13924  // example, it is not possible to goto into a stmt expression apparently.
13925  // More semantic analysis is needed.
13926 
13927  // If there are sub-stmts in the compound stmt, take the type of the last one
13928  // as the type of the stmtexpr.
13929  QualType Ty = Context.VoidTy;
13930  bool StmtExprMayBindToTemp = false;
13931  if (!Compound->body_empty()) {
13932  // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13933  if (const auto *LastStmt =
13934  dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13935  if (const Expr *Value = LastStmt->getExprStmt()) {
13936  StmtExprMayBindToTemp = true;
13937  Ty = Value->getType();
13938  }
13939  }
13940  }
13941 
13942  // FIXME: Check that expression type is complete/non-abstract; statement
13943  // expressions are not lvalues.
13944  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13945  if (StmtExprMayBindToTemp)
13946  return MaybeBindToTemporary(ResStmtExpr);
13947  return ResStmtExpr;
13948 }
13949 
13951  if (ER.isInvalid())
13952  return ExprError();
13953 
13954  // Do function/array conversion on the last expression, but not
13955  // lvalue-to-rvalue. However, initialize an unqualified type.
13956  ER = DefaultFunctionArrayConversion(ER.get());
13957  if (ER.isInvalid())
13958  return ExprError();
13959  Expr *E = ER.get();
13960 
13961  if (E->isTypeDependent())
13962  return E;
13963 
13964  // In ARC, if the final expression ends in a consume, splice
13965  // the consume out and bind it later. In the alternate case
13966  // (when dealing with a retainable type), the result
13967  // initialization will create a produce. In both cases the
13968  // result will be +1, and we'll need to balance that out with
13969  // a bind.
13970  auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13971  if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13972  return Cast->getSubExpr();
13973 
13974  // FIXME: Provide a better location for the initialization.
13975  return PerformCopyInitialization(
13977  E->getBeginLoc(), E->getType().getUnqualifiedType()),
13978  SourceLocation(), E);
13979 }
13980 
13982  TypeSourceInfo *TInfo,
13983  ArrayRef<OffsetOfComponent> Components,
13984  SourceLocation RParenLoc) {
13985  QualType ArgTy = TInfo->getType();
13986  bool Dependent = ArgTy->isDependentType();
13987  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13988 
13989  // We must have at least one component that refers to the type, and the first
13990  // one is known to be a field designator. Verify that the ArgTy represents
13991  // a struct/union/class.
13992  if (!Dependent && !ArgTy->isRecordType())
13993  return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13994  << ArgTy << TypeRange);
13995 
13996  // Type must be complete per C99 7.17p3 because a declaring a variable
13997  // with an incomplete type would be ill-formed.
13998  if (!Dependent
13999  && RequireCompleteType(BuiltinLoc, ArgTy,
14000  diag::err_offsetof_incomplete_type, TypeRange))
14001  return ExprError();
14002 
14003  bool DidWarnAboutNonPOD = false;
14004  QualType CurrentType = ArgTy;
14006  SmallVector<Expr*, 4> Exprs;
14007  for (const OffsetOfComponent &OC : Components) {
14008  if (OC.isBrackets) {
14009  // Offset of an array sub-field. TODO: Should we allow vector elements?
14010  if (!CurrentType->isDependentType()) {
14011  const ArrayType *AT = Context.getAsArrayType(CurrentType);
14012  if(!AT)
14013  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14014  << CurrentType);
14015  CurrentType = AT->getElementType();
14016  } else
14017  CurrentType = Context.DependentTy;
14018 
14019  ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14020  if (IdxRval.isInvalid())
14021  return ExprError();
14022  Expr *Idx = IdxRval.get();
14023 
14024  // The expression must be an integral expression.
14025  // FIXME: An integral constant expression?
14026  if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14027  !Idx->getType()->isIntegerType())
14028  return ExprError(
14029  Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14030  << Idx->getSourceRange());
14031 
14032  // Record this array index.
14033  Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14034  Exprs.push_back(Idx);
14035  continue;
14036  }
14037 
14038  // Offset of a field.
14039  if (CurrentType->isDependentType()) {
14040  // We have the offset of a field, but we can't look into the dependent
14041  // type. Just record the identifier of the field.
14042  Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14043  CurrentType = Context.DependentTy;
14044  continue;
14045  }
14046 
14047  // We need to have a complete type to look into.
14048  if (RequireCompleteType(OC.LocStart, CurrentType,
14049  diag::err_offsetof_incomplete_type))
14050  return ExprError();
14051 
14052  // Look for the designated field.
14053  const RecordType *RC = CurrentType->getAs<RecordType>();
14054  if (!RC)
14055  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14056  << CurrentType);
14057  RecordDecl *RD = RC->getDecl();
14058 
14059  // C++ [lib.support.types]p5:
14060  // The macro offsetof accepts a restricted set of type arguments in this
14061  // International Standard. type shall be a POD structure or a POD union
14062  // (clause 9).
14063  // C++11 [support.types]p4:
14064  // If type is not a standard-layout class (Clause 9), the results are
14065  // undefined.
14066  if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14067  bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14068  unsigned DiagID =
14069  LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14070  : diag::ext_offsetof_non_pod_type;
14071 
14072  if (!IsSafe && !DidWarnAboutNonPOD &&
14073  DiagRuntimeBehavior(BuiltinLoc, nullptr,
14074  PDiag(DiagID)
14075  << SourceRange(Components[0].LocStart, OC.LocEnd)
14076  << CurrentType))
14077  DidWarnAboutNonPOD = true;
14078  }
14079 
14080  // Look for the field.
14081  LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14082  LookupQualifiedName(R, RD);
14083  FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14084  IndirectFieldDecl *IndirectMemberDecl = nullptr;
14085  if (!MemberDecl) {
14086  if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14087  MemberDecl = IndirectMemberDecl->getAnonField();
14088  }
14089 
14090  if (!MemberDecl)
14091  return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14092  << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14093  OC.LocEnd));
14094 
14095  // C99 7.17p3:
14096  // (If the specified member is a bit-field, the behavior is undefined.)
14097  //
14098  // We diagnose this as an error.
14099  if (MemberDecl->isBitField()) {
14100  Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14101  << MemberDecl->getDeclName()
14102  << SourceRange(BuiltinLoc, RParenLoc);
14103  Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14104  return ExprError();
14105  }
14106 
14107  RecordDecl *Parent = MemberDecl->getParent();
14108  if (IndirectMemberDecl)
14109  Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14110 
14111  // If the member was found in a base class, introduce OffsetOfNodes for
14112  // the base class indirections.
14113  CXXBasePaths Paths;
14114  if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14115  Paths)) {
14116  if (Paths.getDetectedVirtual()) {
14117  Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14118  << MemberDecl->getDeclName()
14119  << SourceRange(BuiltinLoc, RParenLoc);
14120  return ExprError();
14121  }
14122 
14123  CXXBasePath &Path = Paths.front();
14124  for (const CXXBasePathElement &B : Path)
14125  Comps.push_back(OffsetOfNode(B.Base));
14126  }
14127 
14128  if (IndirectMemberDecl) {
14129  for (auto *FI : IndirectMemberDecl->chain()) {
14130  assert(isa<FieldDecl>(FI));
14131  Comps.push_back(OffsetOfNode(OC.LocStart,
14132  cast<FieldDecl>(FI), OC.LocEnd));
14133  }
14134  } else
14135  Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14136 
14137  CurrentType = MemberDecl->getType().getNonReferenceType();
14138  }
14139 
14140  return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14141  Comps, Exprs, RParenLoc);
14142 }
14143 
14145  SourceLocation BuiltinLoc,
14147  ParsedType ParsedArgTy,
14148  ArrayRef<OffsetOfComponent> Components,
14149  SourceLocation RParenLoc) {
14150 
14151  TypeSourceInfo *ArgTInfo;
14152  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14153  if (ArgTy.isNull())
14154  return ExprError();
14155 
14156  if (!ArgTInfo)
14157  ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14158 
14159  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14160 }
14161 
14162 
14164  Expr *CondExpr,
14165  Expr *LHSExpr, Expr *RHSExpr,
14166  SourceLocation RPLoc) {
14167  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14168 
14169  ExprValueKind VK = VK_RValue;
14171  QualType resType;
14172  bool ValueDependent = false;
14173  bool CondIsTrue = false;
14174  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14175  resType = Context.DependentTy;
14176  ValueDependent = true;
14177  } else {
14178  // The conditional expression is required to be a constant expression.
14179  llvm::APSInt condEval(32);
14180  ExprResult CondICE
14181  = VerifyIntegerConstantExpression(CondExpr, &condEval,
14182  diag::err_typecheck_choose_expr_requires_constant, false);
14183  if (CondICE.isInvalid())
14184  return ExprError();
14185  CondExpr = CondICE.get();
14186  CondIsTrue = condEval.getZExtValue();
14187 
14188  // If the condition is > zero, then the AST type is the same as the LHSExpr.
14189  Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14190 
14191  resType = ActiveExpr->getType();
14192  ValueDependent = ActiveExpr->isValueDependent();
14193  VK = ActiveExpr->getValueKind();
14194  OK = ActiveExpr->getObjectKind();
14195  }
14196 
14197  return new (Context)
14198  ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14199  CondIsTrue, resType->isDependentType(), ValueDependent);
14200 }
14201 
14202 //===----------------------------------------------------------------------===//
14203 // Clang Extensions.
14204 //===----------------------------------------------------------------------===//
14205 
14206 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14207 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14208  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14209 
14210  if (LangOpts.CPlusPlus) {
14211  MangleNumberingContext *MCtx;
14212  Decl *ManglingContextDecl;
14213  std::tie(MCtx, ManglingContextDecl) =
14214  getCurrentMangleNumberContext(Block->getDeclContext());
14215  if (MCtx) {
14216  unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14217  Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14218  }
14219  }
14220 
14221  PushBlockScope(CurScope, Block);
14222  CurContext->addDecl(Block);
14223  if (CurScope)
14224  PushDeclContext(CurScope, Block);
14225  else
14226  CurContext = Block;
14227 
14228  getCurBlock()->HasImplicitReturnType = true;
14229 
14230  // Enter a new evaluation context to insulate the block from any
14231  // cleanups from the enclosing full-expression.
14232  PushExpressionEvaluationContext(
14233  ExpressionEvaluationContext::PotentiallyEvaluated);
14234 }
14235 
14237  Scope *CurScope) {
14238  assert(ParamInfo.getIdentifier() == nullptr &&
14239  "block-id should have no identifier!");
14240  assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14241  BlockScopeInfo *CurBlock = getCurBlock();
14242 
14243  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14244  QualType T = Sig->getType();
14245 
14246  // FIXME: We should allow unexpanded parameter packs here, but that would,
14247  // in turn, make the block expression contain unexpanded parameter packs.
14248  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14249  // Drop the parameters.
14251  EPI.HasTrailingReturn = false;
14252  EPI.TypeQuals.addConst();
14253  T = Context.getFunctionType(Context.DependentTy, None, EPI);
14254  Sig = Context.getTrivialTypeSourceInfo(T);
14255  }
14256 
14257  // GetTypeForDeclarator always produces a function type for a block
14258  // literal signature. Furthermore, it is always a FunctionProtoType
14259  // unless the function was written with a typedef.
14260  assert(T->isFunctionType() &&
14261  "GetTypeForDeclarator made a non-function block signature");
14262 
14263  // Look for an explicit signature in that function type.
14264  FunctionProtoTypeLoc ExplicitSignature;
14265 
14266  if ((ExplicitSignature = Sig->getTypeLoc()
14268 
14269  // Check whether that explicit signature was synthesized by
14270  // GetTypeForDeclarator. If so, don't save that as part of the
14271  // written signature.
14272  if (ExplicitSignature.getLocalRangeBegin() ==
14273  ExplicitSignature.getLocalRangeEnd()) {
14274  // This would be much cheaper if we stored TypeLocs instead of
14275  // TypeSourceInfos.
14276  TypeLoc Result = ExplicitSignature.getReturnLoc();
14277  unsigned Size = Result.getFullDataSize();
14278  Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14279  Sig->getTypeLoc().initializeFullCopy(Result, Size);
14280 
14281  ExplicitSignature = FunctionProtoTypeLoc();
14282  }
14283  }
14284 
14285  CurBlock->TheDecl->setSignatureAsWritten(Sig);
14286  CurBlock->FunctionType = T;
14287 
14288  const FunctionType *Fn = T->getAs<FunctionType>();
14289  QualType RetTy = Fn->getReturnType();
14290  bool isVariadic =
14291  (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14292 
14293  CurBlock->TheDecl->setIsVariadic(isVariadic);
14294 
14295  // Context.DependentTy is used as a placeholder for a missing block
14296  // return type. TODO: what should we do with declarators like:
14297  // ^ * { ... }
14298  // If the answer is "apply template argument deduction"....
14299  if (RetTy != Context.DependentTy) {
14300  CurBlock->ReturnType = RetTy;
14301  CurBlock->TheDecl->setBlockMissingReturnType(false);
14302  CurBlock->HasImplicitReturnType = false;
14303  }
14304 
14305  // Push block parameters from the declarator if we had them.
14307  if (ExplicitSignature) {
14308  for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14309  ParmVarDecl *Param = ExplicitSignature.getParam(I);
14310  if (Param->getIdentifier() == nullptr &&
14311  !Param->isImplicit() &&
14312  !Param->isInvalidDecl() &&
14313  !getLangOpts().CPlusPlus)
14314  Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14315  Params.push_back(Param);
14316  }
14317 
14318  // Fake up parameter variables if we have a typedef, like
14319  // ^ fntype { ... }
14320  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14321  for (const auto &I : Fn->param_types()) {
14322  ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14323  CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14324  Params.push_back(Param);
14325  }
14326  }
14327 
14328  // Set the parameters on the block decl.
14329  if (!Params.empty()) {
14330  CurBlock->TheDecl->setParams(Params);
14331  CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14332  /*CheckParameterNames=*/false);
14333  }
14334 
14335  // Finally we can process decl attributes.
14336  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14337 
14338  // Put the parameter variables in scope.
14339  for (auto AI : CurBlock->TheDecl->parameters()) {
14340  AI->setOwningFunction(CurBlock->TheDecl);
14341 
14342  // If this has an identifier, add it to the scope stack.
14343  if (AI->getIdentifier()) {
14344  CheckShadow(CurBlock->TheScope, AI);
14345 
14346  PushOnScopeChains(AI, CurBlock->TheScope);
14347  }
14348  }
14349 }
14350 
14351 /// ActOnBlockError - If there is an error parsing a block, this callback
14352 /// is invoked to pop the information about the block from the action impl.
14353 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14354  // Leave the expression-evaluation context.
14355  DiscardCleanupsInEvaluationContext();
14356  PopExpressionEvaluationContext();
14357 
14358  // Pop off CurBlock, handle nested blocks.
14359  PopDeclContext();
14360  PopFunctionScopeInfo();
14361 }
14362 
14363 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14364 /// literal was successfully completed. ^(int x){...}
14366  Stmt *Body, Scope *CurScope) {
14367  // If blocks are disabled, emit an error.
14368  if (!LangOpts.Blocks)
14369  Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14370 
14371  // Leave the expression-evaluation context.
14372  if (hasAnyUnrecoverableErrorsInThisFunction())
14373  DiscardCleanupsInEvaluationContext();
14374  assert(!Cleanup.exprNeedsCleanups() &&
14375  "cleanups within block not correctly bound!");
14376  PopExpressionEvaluationContext();
14377 
14378  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14379  BlockDecl *BD = BSI->TheDecl;
14380 
14381  if (BSI->HasImplicitReturnType)
14382  deduceClosureReturnType(*BSI);
14383 
14384  QualType RetTy = Context.VoidTy;
14385  if (!BSI->ReturnType.isNull())
14386  RetTy = BSI->ReturnType;
14387 
14388  bool NoReturn = BD->hasAttr<NoReturnAttr>();
14389  QualType BlockTy;
14390 
14391  // If the user wrote a function type in some form, try to use that.
14392  if (!BSI->FunctionType.isNull()) {
14393  const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14394 
14395  FunctionType::ExtInfo Ext = FTy->getExtInfo();
14396  if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14397 
14398  // Turn protoless block types into nullary block types.
14399  if (isa<FunctionNoProtoType>(FTy)) {
14401  EPI.ExtInfo = Ext;
14402  BlockTy = Context.getFunctionType(RetTy, None, EPI);
14403 
14404  // Otherwise, if we don't need to change anything about the function type,
14405  // preserve its sugar structure.
14406  } else if (FTy->getReturnType() == RetTy &&
14407  (!NoReturn || FTy->getNoReturnAttr())) {
14408  BlockTy = BSI->FunctionType;
14409 
14410  // Otherwise, make the minimal modifications to the function type.
14411  } else {
14412  const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14414  EPI.TypeQuals = Qualifiers();
14415  EPI.ExtInfo = Ext;
14416  BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14417  }
14418 
14419  // If we don't have a function type, just build one from nothing.
14420  } else {
14422  EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14423  BlockTy = Context.getFunctionType(RetTy, None, EPI);
14424  }
14425 
14426  DiagnoseUnusedParameters(BD->parameters());
14427  BlockTy = Context.getBlockPointerType(BlockTy);
14428 
14429  // If needed, diagnose invalid gotos and switches in the block.
14430  if (getCurFunction()->NeedsScopeChecking() &&
14431  !PP.isCodeCompletionEnabled())
14432  DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14433 
14434  BD->setBody(cast<CompoundStmt>(Body));
14435 
14436  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14437  DiagnoseUnguardedAvailabilityViolations(BD);
14438 
14439  // Try to apply the named return value optimization. We have to check again
14440  // if we can do this, though, because blocks keep return statements around
14441  // to deduce an implicit return type.
14442  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14443  !BD->isDependentContext())
14444  computeNRVO(Body, BSI);
14445 
14448  checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14449  NTCUK_Destruct|NTCUK_Copy);
14450 
14451  PopDeclContext();
14452 
14453  // Pop the block scope now but keep it alive to the end of this function.
14454  AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14455  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14456 
14457  // Set the captured variables on the block.
14459  for (Capture &Cap : BSI->Captures) {
14460  if (Cap.isInvalid() || Cap.isThisCapture())
14461  continue;
14462 
14463  VarDecl *Var = Cap.getVariable();
14464  Expr *CopyExpr = nullptr;
14465  if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14466  if (const RecordType *Record =
14467  Cap.getCaptureType()->getAs<RecordType>()) {
14468  // The capture logic needs the destructor, so make sure we mark it.
14469  // Usually this is unnecessary because most local variables have
14470  // their destructors marked at declaration time, but parameters are
14471  // an exception because it's technically only the call site that
14472  // actually requires the destructor.
14473  if (isa<ParmVarDecl>(Var))
14474  FinalizeVarWithDestructor(Var, Record);
14475 
14476  // Enter a separate potentially-evaluated context while building block
14477  // initializers to isolate their cleanups from those of the block
14478  // itself.
14479  // FIXME: Is this appropriate even when the block itself occurs in an
14480  // unevaluated operand?
14482  *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14483 
14484  SourceLocation Loc = Cap.getLocation();
14485 
14486  ExprResult Result = BuildDeclarationNameExpr(
14487  CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14488 
14489  // According to the blocks spec, the capture of a variable from
14490  // the stack requires a const copy constructor. This is not true
14491  // of the copy/move done to move a __block variable to the heap.
14492  if (!Result.isInvalid() &&
14493  !Result.get()->getType().isConstQualified()) {
14494  Result = ImpCastExprToType(Result.get(),
14495  Result.get()->getType().withConst(),
14496  CK_NoOp, VK_LValue);
14497  }
14498 
14499  if (!Result.isInvalid()) {
14500  Result = PerformCopyInitialization(
14502  Cap.getCaptureType(), false),
14503  Loc, Result.get());
14504  }
14505 
14506  // Build a full-expression copy expression if initialization
14507  // succeeded and used a non-trivial constructor. Recover from
14508  // errors by pretending that the copy isn't necessary.
14509  if (!Result.isInvalid() &&
14510  !cast<CXXConstructExpr>(Result.get())->getConstructor()
14511  ->isTrivial()) {
14512  Result = MaybeCreateExprWithCleanups(Result);
14513  CopyExpr = Result.get();
14514  }
14515  }
14516  }
14517 
14518  BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14519  CopyExpr);
14520  Captures.push_back(NewCap);
14521  }
14522  BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14523 
14524  BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14525 
14526  // If the block isn't obviously global, i.e. it captures anything at
14527  // all, then we need to do a few things in the surrounding context:
14528  if (Result->getBlockDecl()->hasCaptures()) {
14529  // First, this expression has a new cleanup object.
14530  ExprCleanupObjects.push_back(Result->getBlockDecl());
14531  Cleanup.setExprNeedsCleanups(true);
14532 
14533  // It also gets a branch-protected scope if any of the captured
14534  // variables needs destruction.
14535  for (const auto &CI : Result->getBlockDecl()->captures()) {
14536  const VarDecl *var = CI.getVariable();
14537  if (var->getType().isDestructedType() != QualType::DK_none) {
14538  setFunctionHasBranchProtectedScope();
14539  break;
14540  }
14541  }
14542  }
14543 
14544  if (getCurFunction())
14545  getCurFunction()->addBlock(BD);
14546 
14547  return Result;
14548 }
14549 
14551  SourceLocation RPLoc) {
14552  TypeSourceInfo *TInfo;
14553  GetTypeFromParser(Ty, &TInfo);
14554  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14555 }
14556 
14558  Expr *E, TypeSourceInfo *TInfo,
14559  SourceLocation RPLoc) {
14560  Expr *OrigExpr = E;
14561  bool IsMS = false;
14562 
14563  // CUDA device code does not support varargs.
14564  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14565  if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14566  CUDAFunctionTarget T = IdentifyCUDATarget(F);
14567  if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14568  return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14569  }
14570  }
14571 
14572  // NVPTX does not support va_arg expression.
14573  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14574  Context.getTargetInfo().getTriple().isNVPTX())
14575  targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14576 
14577  // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14578  // as Microsoft ABI on an actual Microsoft platform, where
14579  // __builtin_ms_va_list and __builtin_va_list are the same.)
14580  if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14582  QualType MSVaListType = Context.getBuiltinMSVaListType();
14583  if (Context.hasSameType(MSVaListType, E->getType())) {
14584  if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14585  return ExprError();
14586  IsMS = true;
14587  }
14588  }
14589 
14590  // Get the va_list type
14591  QualType VaListType = Context.getBuiltinVaListType();
14592  if (!IsMS) {
14593  if (VaListType->isArrayType()) {
14594  // Deal with implicit array decay; for example, on x86-64,
14595  // va_list is an array, but it's supposed to decay to
14596  // a pointer for va_arg.
14597  VaListType = Context.getArrayDecayedType(VaListType);
14598  // Make sure the input expression also decays appropriately.
14599  ExprResult Result = UsualUnaryConversions(E);
14600  if (Result.isInvalid())
14601  return ExprError();
14602  E = Result.get();
14603  } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14604  // If va_list is a record type and we are compiling in C++ mode,
14605  // check the argument using reference binding.
14607  Context, Context.getLValueReferenceType(VaListType), false);
14608  ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14609  if (Init.isInvalid())
14610  return ExprError();
14611  E = Init.getAs<Expr>();
14612  } else {
14613  // Otherwise, the va_list argument must be an l-value because
14614  // it is modified by va_arg.
14615  if (!E->isTypeDependent() &&
14616  CheckForModifiableLvalue(E, BuiltinLoc, *this))
14617  return ExprError();
14618  }
14619  }
14620 
14621  if (!IsMS && !E->isTypeDependent() &&
14622  !Context.hasSameType(VaListType, E->getType()))
14623  return ExprError(
14624  Diag(E->getBeginLoc(),
14625  diag::err_first_argument_to_va_arg_not_of_type_va_list)
14626  << OrigExpr->getType() << E->getSourceRange());
14627 
14628  if (!TInfo->getType()->isDependentType()) {
14629  if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14630  diag::err_second_parameter_to_va_arg_incomplete,
14631  TInfo->getTypeLoc()))
14632  return ExprError();
14633 
14634  if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14635  TInfo->getType(),
14636  diag::err_second_parameter_to_va_arg_abstract,
14637  TInfo->getTypeLoc()))
14638  return ExprError();
14639 
14640  if (!TInfo->getType().isPODType(Context)) {
14641  Diag(TInfo->getTypeLoc().getBeginLoc(),
14642  TInfo->getType()->isObjCLifetimeType()
14643  ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14644  : diag::warn_second_parameter_to_va_arg_not_pod)
14645  << TInfo->getType()
14646  << TInfo->getTypeLoc().getSourceRange();
14647  }
14648 
14649  // Check for va_arg where arguments of the given type will be promoted
14650  // (i.e. this va_arg is guaranteed to have undefined behavior).
14651  QualType PromoteType;
14652  if (TInfo->getType()->isPromotableIntegerType()) {
14653  PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14654  if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14655  PromoteType = QualType();
14656  }
14657  if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14658  PromoteType = Context.DoubleTy;
14659  if (!PromoteType.isNull())
14660  DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14661  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14662  << TInfo->getType()
14663  << PromoteType
14664  << TInfo->getTypeLoc().getSourceRange());
14665  }
14666 
14667  QualType T = TInfo->getType().getNonLValueExprType(Context);
14668  return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14669 }
14670 
14672  // The type of __null will be int or long, depending on the size of
14673  // pointers on the target.
14674  QualType Ty;
14675  unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14676  if (pw == Context.getTargetInfo().getIntWidth())
14677  Ty = Context.IntTy;
14678  else if (pw == Context.getTargetInfo().getLongWidth())
14679  Ty = Context.LongTy;
14680  else if (pw == Context.getTargetInfo().getLongLongWidth())
14681  Ty = Context.LongLongTy;
14682  else {
14683  llvm_unreachable("I don't know size of pointer!");
14684  }
14685 
14686  return new (Context) GNUNullExpr(Ty, TokenLoc);
14687 }
14688 
14690  SourceLocation BuiltinLoc,
14691  SourceLocation RPLoc) {
14692  return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14693 }
14694 
14696  SourceLocation BuiltinLoc,
14697  SourceLocation RPLoc,
14698  DeclContext *ParentContext) {
14699  return new (Context)
14700  SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14701 }
14702 
14704  bool Diagnose) {
14705  if (!getLangOpts().ObjC)
14706  return false;
14707 
14708  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14709  if (!PT)
14710  return false;
14711 
14712  if (!PT->isObjCIdType()) {
14713  // Check if the destination is the 'NSString' interface.
14714  const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14715  if (!ID || !ID->getIdentifier()->isStr("NSString"))
14716  return false;
14717  }
14718 
14719  // Ignore any parens, implicit casts (should only be
14720  // array-to-pointer decays), and not-so-opaque values. The last is
14721  // important for making this trigger for property assignments.
14722  Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14723  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14724  if (OV->getSourceExpr())
14725  SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14726 
14727  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14728  if (!SL || !SL->isAscii())
14729  return false;
14730  if (Diagnose) {
14731  Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14732  << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14733  Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14734  }
14735  return true;
14736 }
14737 
14739  const Expr *SrcExpr) {
14740  if (!DstType->isFunctionPointerType() ||
14741  !SrcExpr->getType()->isFunctionType())
14742  return false;
14743 
14744  auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14745  if (!DRE)
14746  return false;
14747 
14748  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14749  if (!FD)
14750  return false;
14751 
14752  return !S.checkAddressOfFunctionIsAvailable(FD,
14753  /*Complain=*/true,
14754  SrcExpr->getBeginLoc());
14755 }
14756 
14758  SourceLocation Loc,
14759  QualType DstType, QualType SrcType,
14760  Expr *SrcExpr, AssignmentAction Action,
14761  bool *Complained) {
14762  if (Complained)
14763  *Complained = false;
14764 
14765  // Decode the result (notice that AST's are still created for extensions).
14766  bool CheckInferredResultType = false;
14767  bool isInvalid = false;
14768  unsigned DiagKind = 0;
14769  FixItHint Hint;
14770  ConversionFixItGenerator ConvHints;
14771  bool MayHaveConvFixit = false;
14772  bool MayHaveFunctionDiff = false;
14773  const ObjCInterfaceDecl *IFace = nullptr;
14774  const ObjCProtocolDecl *PDecl = nullptr;
14775 
14776  switch (ConvTy) {
14777  case Compatible:
14778  DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14779  return false;
14780 
14781  case PointerToInt:
14782  DiagKind = diag::ext_typecheck_convert_pointer_int;
14783  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14784  MayHaveConvFixit = true;
14785  break;
14786  case IntToPointer:
14787  DiagKind = diag::ext_typecheck_convert_int_pointer;
14788  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14789  MayHaveConvFixit = true;
14790  break;
14791  case IncompatiblePointer:
14792  if (Action == AA_Passing_CFAudited)
14793  DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14794  else if (SrcType->isFunctionPointerType() &&
14795  DstType->isFunctionPointerType())
14796  DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14797  else
14798  DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14799 
14800  CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14801  SrcType->isObjCObjectPointerType();
14802  if (Hint.isNull() && !CheckInferredResultType) {
14803  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14804  }
14805  else if (CheckInferredResultType) {
14806  SrcType = SrcType.getUnqualifiedType();
14807  DstType = DstType.getUnqualifiedType();
14808  }
14809  MayHaveConvFixit = true;
14810  break;
14811  case IncompatiblePointerSign:
14812  DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14813  break;
14814  case FunctionVoidPointer:
14815  DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14816  break;
14817  case IncompatiblePointerDiscardsQualifiers: {
14818  // Perform array-to-pointer decay if necessary.
14819  if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14820 
14821  Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14822  Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14823  if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14824  DiagKind = diag::err_typecheck_incompatible_address_space;
14825  break;
14826 
14827  } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14828  DiagKind = diag::err_typecheck_incompatible_ownership;
14829  break;
14830  }
14831 
14832  llvm_unreachable("unknown error case for discarding qualifiers!");
14833  // fallthrough
14834  }
14835  case CompatiblePointerDiscardsQualifiers:
14836  // If the qualifiers lost were because we were applying the
14837  // (deprecated) C++ conversion from a string literal to a char*
14838  // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
14839  // Ideally, this check would be performed in
14840  // checkPointerTypesForAssignment. However, that would require a
14841  // bit of refactoring (so that the second argument is an
14842  // expression, rather than a type), which should be done as part
14843  // of a larger effort to fix checkPointerTypesForAssignment for
14844  // C++ semantics.
14845  if (getLangOpts().CPlusPlus &&
14846  IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14847  return false;
14848  DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14849  break;
14850  case IncompatibleNestedPointerQualifiers:
14851  DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14852  break;
14853  case IncompatibleNestedPointerAddressSpaceMismatch:
14854  DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14855  break;
14856  case IntToBlockPointer:
14857  DiagKind = diag::err_int_to_block_pointer;
14858  break;
14859  case IncompatibleBlockPointer:
14860  DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14861  break;
14862  case IncompatibleObjCQualifiedId: {
14863  if (SrcType->isObjCQualifiedIdType()) {
14864  const ObjCObjectPointerType *srcOPT =
14865  SrcType->castAs<ObjCObjectPointerType>();
14866  for (auto *srcProto : srcOPT->quals()) {
14867  PDecl = srcProto;
14868  break;
14869  }
14870  if (const ObjCInterfaceType *IFaceT =
14872  IFace = IFaceT->getDecl();
14873  }
14874  else if (DstType->isObjCQualifiedIdType()) {
14875  const ObjCObjectPointerType *dstOPT =
14876  DstType->castAs<ObjCObjectPointerType>();
14877  for (auto *dstProto : dstOPT->quals()) {
14878  PDecl = dstProto;
14879  break;
14880  }
14881  if (const ObjCInterfaceType *IFaceT =
14883  IFace = IFaceT->getDecl();
14884  }
14885  DiagKind = diag::warn_incompatible_qualified_id;
14886  break;
14887  }
14888  case IncompatibleVectors:
14889  DiagKind = diag::warn_incompatible_vectors;
14890  break;
14891  case IncompatibleObjCWeakRef:
14892  DiagKind = diag::err_arc_weak_unavailable_assign;
14893  break;
14894  case Incompatible:
14895  if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14896  if (Complained)
14897  *Complained = true;
14898  return true;
14899  }
14900 
14901  DiagKind = diag::err_typecheck_convert_incompatible;
14902  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14903  MayHaveConvFixit = true;
14904  isInvalid = true;
14905  MayHaveFunctionDiff = true;
14906  break;
14907  }
14908 
14909  QualType FirstType, SecondType;
14910  switch (Action) {
14911  case AA_Assigning:
14912  case AA_Initializing:
14913  // The destination type comes first.
14914  FirstType = DstType;
14915  SecondType = SrcType;
14916  break;
14917 
14918  case AA_Returning:
14919  case AA_Passing:
14920  case AA_Passing_CFAudited:
14921  case AA_Converting:
14922  case AA_Sending:
14923  case AA_Casting:
14924  // The source type comes first.
14925  FirstType = SrcType;
14926  SecondType = DstType;
14927  break;
14928  }
14929 
14930  PartialDiagnostic FDiag = PDiag(DiagKind);
14931  if (Action == AA_Passing_CFAudited)
14932  FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14933  else
14934  FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14935 
14936  // If we can fix the conversion, suggest the FixIts.
14937  assert(ConvHints.isNull() || Hint.isNull());
14938  if (!ConvHints.isNull()) {
14939  for (FixItHint &H : ConvHints.Hints)
14940  FDiag << H;
14941  } else {
14942  FDiag << Hint;
14943  }
14944  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14945 
14946  if (MayHaveFunctionDiff)
14947  HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14948 
14949  Diag(Loc, FDiag);
14950  if (DiagKind == diag::warn_incompatible_qualified_id &&
14951  PDecl && IFace && !IFace->hasDefinition())
14952  Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14953  << IFace << PDecl;
14954 
14955  if (SecondType == Context.OverloadTy)
14956  NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14957  FirstType, /*TakingAddress=*/true);
14958 
14959  if (CheckInferredResultType)
14960  EmitRelatedResultTypeNote(SrcExpr);
14961 
14962  if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14963  EmitRelatedResultTypeNoteForReturn(DstType);
14964 
14965  if (Complained)
14966  *Complained = true;
14967  return isInvalid;
14968 }
14969 
14971  llvm::APSInt *Result) {
14972  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14973  public:
14974  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14975  S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14976  }
14977  } Diagnoser;
14978 
14979  return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14980 }
14981 
14983  llvm::APSInt *Result,
14984  unsigned DiagID,
14985  bool AllowFold) {
14986  class IDDiagnoser : public VerifyICEDiagnoser {
14987  unsigned DiagID;
14988 
14989  public:
14990  IDDiagnoser(unsigned DiagID)
14991  : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14992 
14993  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14994  S.Diag(Loc, DiagID) << SR;
14995  }
14996  } Diagnoser(DiagID);
14997 
14998  return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14999 }
15000 
15002  SourceRange SR) {
15003  S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15004 }
15005 
15006 ExprResult
15008  VerifyICEDiagnoser &Diagnoser,
15009  bool AllowFold) {
15010  SourceLocation DiagLoc = E->getBeginLoc();
15011 
15012  if (getLangOpts().CPlusPlus11) {
15013  // C++11 [expr.const]p5:
15014  // If an expression of literal class type is used in a context where an
15015  // integral constant expression is required, then that class type shall
15016  // have a single non-explicit conversion function to an integral or
15017  // unscoped enumeration type
15018  ExprResult Converted;
15019  class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15020  public:
15021  CXX11ConvertDiagnoser(bool Silent)
15022  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15023  Silent, true) {}
15024 
15025  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15026  QualType T) override {
15027  return S.Diag(Loc, diag::err_ice_not_integral) << T;
15028  }
15029 
15030  SemaDiagnosticBuilder diagnoseIncomplete(
15031  Sema &S, SourceLocation Loc, QualType T) override {
15032  return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15033  }
15034 
15035  SemaDiagnosticBuilder diagnoseExplicitConv(
15036  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15037  return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15038  }
15039 
15040  SemaDiagnosticBuilder noteExplicitConv(
15041  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15042  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15043  << ConvTy->isEnumeralType() << ConvTy;
15044  }
15045 
15046  SemaDiagnosticBuilder diagnoseAmbiguous(
15047  Sema &S, SourceLocation Loc, QualType T) override {
15048  return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15049  }
15050 
15051  SemaDiagnosticBuilder noteAmbiguous(
15052  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15053  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15054  << ConvTy->isEnumeralType() << ConvTy;
15055  }
15056 
15057  SemaDiagnosticBuilder diagnoseConversion(
15058  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15059  llvm_unreachable("conversion functions are permitted");
15060  }
15061  } ConvertDiagnoser(Diagnoser.Suppress);
15062 
15063  Converted = PerformContextualImplicitConversion(DiagLoc, E,
15064  ConvertDiagnoser);
15065  if (Converted.isInvalid())
15066  return Converted;
15067  E = Converted.get();
15069  return ExprError();
15070  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15071  // An ICE must be of integral or unscoped enumeration type.
15072  if (!Diagnoser.Suppress)
15073  Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15074  return ExprError();
15075  }
15076 
15077  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15078  // in the non-ICE case.
15079  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15080  if (Result)
15081  *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15082  if (!isa<ConstantExpr>(E))
15083  E = ConstantExpr::Create(Context, E);
15084  return E;
15085  }
15086 
15087  Expr::EvalResult EvalResult;
15089  EvalResult.Diag = &Notes;
15090 
15091  // Try to evaluate the expression, and produce diagnostics explaining why it's
15092  // not a constant expression as a side-effect.
15093  bool Folded =
15094  E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15095  EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15096 
15097  if (!isa<ConstantExpr>(E))
15098  E = ConstantExpr::Create(Context, E, EvalResult.Val);
15099 
15100  // In C++11, we can rely on diagnostics being produced for any expression
15101  // which is not a constant expression. If no diagnostics were produced, then
15102  // this is a constant expression.
15103  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15104  if (Result)
15105  *Result = EvalResult.Val.getInt();
15106  return E;
15107  }
15108 
15109  // If our only note is the usual "invalid subexpression" note, just point
15110  // the caret at its location rather than producing an essentially
15111  // redundant note.
15112  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15113  diag::note_invalid_subexpr_in_const_expr) {
15114  DiagLoc = Notes[0].first;
15115  Notes.clear();
15116  }
15117 
15118  if (!Folded || !AllowFold) {
15119  if (!Diagnoser.Suppress) {
15120  Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15121  for (const PartialDiagnosticAt &Note : Notes)
15122  Diag(Note.first, Note.second);
15123  }
15124 
15125  return ExprError();
15126  }
15127 
15128  Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15129  for (const PartialDiagnosticAt &Note : Notes)
15130  Diag(Note.first, Note.second);
15131 
15132  if (Result)
15133  *Result = EvalResult.Val.getInt();
15134  return E;
15135 }
15136 
15137 namespace {
15138  // Handle the case where we conclude a expression which we speculatively
15139  // considered to be unevaluated is actually evaluated.
15140  class TransformToPE : public TreeTransform<TransformToPE> {
15141  typedef TreeTransform<TransformToPE> BaseTransform;
15142 
15143  public:
15144  TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15145 
15146  // Make sure we redo semantic analysis
15147  bool AlwaysRebuild() { return true; }
15148  bool ReplacingOriginal() { return true; }
15149 
15150  // We need to special-case DeclRefExprs referring to FieldDecls which
15151  // are not part of a member pointer formation; normal TreeTransforming
15152  // doesn't catch this case because of the way we represent them in the AST.
15153  // FIXME: This is a bit ugly; is it really the best way to handle this
15154  // case?
15155  //
15156  // Error on DeclRefExprs referring to FieldDecls.
15157  ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15158  if (isa<FieldDecl>(E->getDecl()) &&
15159  !SemaRef.isUnevaluatedContext())
15160  return SemaRef.Diag(E->getLocation(),
15161  diag::err_invalid_non_static_member_use)
15162  << E->getDecl() << E->getSourceRange();
15163 
15164  return BaseTransform::TransformDeclRefExpr(E);
15165  }
15166 
15167  // Exception: filter out member pointer formation
15168  ExprResult TransformUnaryOperator(UnaryOperator *E) {
15169  if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15170  return E;
15171 
15172  return BaseTransform::TransformUnaryOperator(E);
15173  }
15174 
15175  // The body of a lambda-expression is in a separate expression evaluation
15176  // context so never needs to be transformed.
15177  // FIXME: Ideally we wouldn't transform the closure type either, and would
15178  // just recreate the capture expressions and lambda expression.
15179  StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15180  return SkipLambdaBody(E, Body);
15181  }
15182  };
15183 }
15184 
15186  assert(isUnevaluatedContext() &&
15187  "Should only transform unevaluated expressions");
15188  ExprEvalContexts.back().Context =
15189  ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15190  if (isUnevaluatedContext())
15191  return E;
15192  return TransformToPE(*this).TransformExpr(E);
15193 }
15194 
15195 void
15197  ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15199  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15200  LambdaContextDecl, ExprContext);
15201  Cleanup.reset();
15202  if (!MaybeODRUseExprs.empty())
15203  std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15204 }
15205 
15206 void
15210  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15211  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15212 }
15213 
15214 namespace {
15215 
15216 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15217  PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15218  if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15219  if (E->getOpcode() == UO_Deref)
15220  return CheckPossibleDeref(S, E->getSubExpr());
15221  } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15222  return CheckPossibleDeref(S, E->getBase());
15223  } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15224  return CheckPossibleDeref(S, E->getBase());
15225  } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15226  QualType Inner;
15227  QualType Ty = E->getType();
15228  if (const auto *Ptr = Ty->getAs<PointerType>())
15229  Inner = Ptr->getPointeeType();
15230  else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15231  Inner = Arr->getElementType();
15232  else
15233  return nullptr;
15234 
15235  if (Inner->hasAttr(attr::NoDeref))
15236  return E;
15237  }
15238  return nullptr;
15239 }
15240 
15241 } // namespace
15242 
15244  for (const Expr *E : Rec.PossibleDerefs) {
15245  const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15246  if (DeclRef) {
15247  const ValueDecl *Decl = DeclRef->getDecl();
15248  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15249  << Decl->getName() << E->getSourceRange();
15250  Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15251  } else {
15252  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15253  << E->getSourceRange();
15254  }
15255  }
15256  Rec.PossibleDerefs.clear();
15257 }
15258 
15259 /// Check whether E, which is either a discarded-value expression or an
15260 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15261 /// and if so, remove it from the list of volatile-qualified assignments that
15262 /// we are going to warn are deprecated.
15264  if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15265  return;
15266 
15267  // Note: ignoring parens here is not justified by the standard rules, but
15268  // ignoring parentheses seems like a more reasonable approach, and this only
15269  // drives a deprecation warning so doesn't affect conformance.
15270  if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15271  if (BO->getOpcode() == BO_Assign) {
15272  auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15273  LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15274  LHSs.end());
15275  }
15276  }
15277 }
15278 
15280  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15281  unsigned NumTypos = Rec.NumTypos;
15282 
15283  if (!Rec.Lambdas.empty()) {
15285  if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15286  (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15287  unsigned D;
15288  if (Rec.isUnevaluated()) {
15289  // C++11 [expr.prim.lambda]p2:
15290  // A lambda-expression shall not appear in an unevaluated operand
15291  // (Clause 5).
15292  D = diag::err_lambda_unevaluated_operand;
15293  } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15294  // C++1y [expr.const]p2:
15295  // A conditional-expression e is a core constant expression unless the
15296  // evaluation of e, following the rules of the abstract machine, would
15297  // evaluate [...] a lambda-expression.
15298  D = diag::err_lambda_in_constant_expression;
15299  } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15300  // C++17 [expr.prim.lamda]p2:
15301  // A lambda-expression shall not appear [...] in a template-argument.
15302  D = diag::err_lambda_in_invalid_context;
15303  } else
15304  llvm_unreachable("Couldn't infer lambda error message.");
15305 
15306  for (const auto *L : Rec.Lambdas)
15307  Diag(L->getBeginLoc(), D);
15308  }
15309  }
15310 
15311  WarnOnPendingNoDerefs(Rec);
15312 
15313  // Warn on any volatile-qualified simple-assignments that are not discarded-
15314  // value expressions nor unevaluated operands (those cases get removed from
15315  // this list by CheckUnusedVolatileAssignment).
15316  for (auto *BO : Rec.VolatileAssignmentLHSs)
15317  Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15318  << BO->getType();
15319 
15320  // When are coming out of an unevaluated context, clear out any
15321  // temporaries that we may have created as part of the evaluation of
15322  // the expression in that context: they aren't relevant because they
15323  // will never be constructed.
15324  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15325  ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15326  ExprCleanupObjects.end());
15327  Cleanup = Rec.ParentCleanup;
15328  CleanupVarDeclMarking();
15329  std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15330  // Otherwise, merge the contexts together.
15331  } else {
15332  Cleanup.mergeFrom(Rec.ParentCleanup);
15333  MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15334  Rec.SavedMaybeODRUseExprs.end());
15335  }
15336 
15337  // Pop the current expression evaluation context off the stack.
15338  ExprEvalContexts.pop_back();
15339 
15340  // The global expression evaluation context record is never popped.
15341  ExprEvalContexts.back().NumTypos += NumTypos;
15342 }
15343 
15345  ExprCleanupObjects.erase(
15346  ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15347  ExprCleanupObjects.end());
15348  Cleanup.reset();
15349  MaybeODRUseExprs.clear();
15350 }
15351 
15353  ExprResult Result = CheckPlaceholderExpr(E);
15354  if (Result.isInvalid())
15355  return ExprError();
15356  E = Result.get();
15357  if (!E->getType()->isVariablyModifiedType())
15358  return E;
15359  return TransformToPotentiallyEvaluated(E);
15360 }
15361 
15362 /// Are we in a context that is potentially constant evaluated per C++20
15363 /// [expr.const]p12?
15365  /// C++2a [expr.const]p12:
15366  // An expression or conversion is potentially constant evaluated if it is
15367  switch (SemaRef.ExprEvalContexts.back().Context) {
15369  // -- a manifestly constant-evaluated expression,
15373  // -- a potentially-evaluated expression,
15375  // -- an immediate subexpression of a braced-init-list,
15376 
15377  // -- [FIXME] an expression of the form & cast-expression that occurs
15378  // within a templated entity
15379  // -- a subexpression of one of the above that is not a subexpression of
15380  // a nested unevaluated operand.
15381  return true;
15382 
15385  // Expressions in this context are never evaluated.
15386  return false;
15387  }
15388  llvm_unreachable("Invalid context");
15389 }
15390 
15391 /// Return true if this function has a calling convention that requires mangling
15392 /// in the size of the parameter pack.
15394  // These manglings don't do anything on non-Windows or non-x86 platforms, so
15395  // we don't need parameter type sizes.
15396  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15397  if (!TT.isOSWindows() || !TT.isX86())
15398  return false;
15399 
15400  // If this is C++ and this isn't an extern "C" function, parameters do not
15401  // need to be complete. In this case, C++ mangling will apply, which doesn't
15402  // use the size of the parameters.
15403  if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15404  return false;
15405 
15406  // Stdcall, fastcall, and vectorcall need this special treatment.
15407  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15408  switch (CC) {
15409  case CC_X86StdCall:
15410  case CC_X86FastCall:
15411  case CC_X86VectorCall:
15412  return true;
15413  default:
15414  break;
15415  }
15416  return false;
15417 }
15418 
15419 /// Require that all of the parameter types of function be complete. Normally,
15420 /// parameter types are only required to be complete when a function is called
15421 /// or defined, but to mangle functions with certain calling conventions, the
15422 /// mangler needs to know the size of the parameter list. In this situation,
15423 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15424 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15425 /// result in a linker error. Clang doesn't implement this behavior, and instead
15426 /// attempts to error at compile time.
15428  SourceLocation Loc) {
15429  class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15430  FunctionDecl *FD;
15431  ParmVarDecl *Param;
15432 
15433  public:
15434  ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15435  : FD(FD), Param(Param) {}
15436 
15437  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15438  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15439  StringRef CCName;
15440  switch (CC) {
15441  case CC_X86StdCall:
15442  CCName = "stdcall";
15443  break;
15444  case CC_X86FastCall:
15445  CCName = "fastcall";
15446  break;
15447  case CC_X86VectorCall:
15448  CCName = "vectorcall";
15449  break;
15450  default:
15451  llvm_unreachable("CC does not need mangling");
15452  }
15453 
15454  S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15455  << Param->getDeclName() << FD->getDeclName() << CCName;
15456  }
15457  };
15458 
15459  for (ParmVarDecl *Param : FD->parameters()) {
15460  ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15461  S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15462  }
15463 }
15464 
15465 namespace {
15466 enum class OdrUseContext {
15467  /// Declarations in this context are not odr-used.
15468  None,
15469  /// Declarations in this context are formally odr-used, but this is a
15470  /// dependent context.
15471  Dependent,
15472  /// Declarations in this context are odr-used but not actually used (yet).
15473  FormallyOdrUsed,
15474  /// Declarations in this context are used.
15475  Used
15476 };
15477 }
15478 
15479 /// Are we within a context in which references to resolved functions or to
15480 /// variables result in odr-use?
15482  OdrUseContext Result;
15483 
15484  switch (SemaRef.ExprEvalContexts.back().Context) {
15488  return OdrUseContext::None;
15489 
15492  Result = OdrUseContext::Used;
15493  break;
15494 
15496  Result = OdrUseContext::FormallyOdrUsed;
15497  break;
15498 
15500  // A default argument formally results in odr-use, but doesn't actually
15501  // result in a use in any real sense until it itself is used.
15502  Result = OdrUseContext::FormallyOdrUsed;
15503  break;
15504  }
15505 
15506  if (SemaRef.CurContext->isDependentContext())
15507  return OdrUseContext::Dependent;
15508 
15509  return Result;
15510 }
15511 
15513  return Func->isConstexpr() &&
15514  (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
15515 }
15516 
15517 /// Mark a function referenced, and check whether it is odr-used
15518 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15520  bool MightBeOdrUse) {
15521  assert(Func && "No function?");
15522 
15523  Func->setReferenced();
15524 
15525  // Recursive functions aren't really used until they're used from some other
15526  // context.
15527  bool IsRecursiveCall = CurContext == Func;
15528 
15529  // C++11 [basic.def.odr]p3:
15530  // A function whose name appears as a potentially-evaluated expression is
15531  // odr-used if it is the unique lookup result or the selected member of a
15532  // set of overloaded functions [...].
15533  //
15534  // We (incorrectly) mark overload resolution as an unevaluated context, so we
15535  // can just check that here.
15536  OdrUseContext OdrUse =
15537  MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15538  if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15539  OdrUse = OdrUseContext::FormallyOdrUsed;
15540 
15541  // Trivial default constructors and destructors are never actually used.
15542  // FIXME: What about other special members?
15543  if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15544  OdrUse == OdrUseContext::Used) {
15545  if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15546  if (Constructor->isDefaultConstructor())
15547  OdrUse = OdrUseContext::FormallyOdrUsed;
15548  if (isa<CXXDestructorDecl>(Func))
15549  OdrUse = OdrUseContext::FormallyOdrUsed;
15550  }
15551 
15552  // C++20 [expr.const]p12:
15553  // A function [...] is needed for constant evaluation if it is [...] a
15554  // constexpr function that is named by an expression that is potentially
15555  // constant evaluated
15556  bool NeededForConstantEvaluation =
15559 
15560  // Determine whether we require a function definition to exist, per
15561  // C++11 [temp.inst]p3:
15562  // Unless a function template specialization has been explicitly
15563  // instantiated or explicitly specialized, the function template
15564  // specialization is implicitly instantiated when the specialization is
15565  // referenced in a context that requires a function definition to exist.
15566  // C++20 [temp.inst]p7:
15567  // The existence of a definition of a [...] function is considered to
15568  // affect the semantics of the program if the [...] function is needed for
15569  // constant evaluation by an expression
15570  // C++20 [basic.def.odr]p10:
15571  // Every program shall contain exactly one definition of every non-inline
15572  // function or variable that is odr-used in that program outside of a
15573  // discarded statement
15574  // C++20 [special]p1:
15575  // The implementation will implicitly define [defaulted special members]
15576  // if they are odr-used or needed for constant evaluation.
15577  //
15578  // Note that we skip the implicit instantiation of templates that are only
15579  // used in unused default arguments or by recursive calls to themselves.
15580  // This is formally non-conforming, but seems reasonable in practice.
15581  bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15582  NeededForConstantEvaluation);
15583 
15584  // C++14 [temp.expl.spec]p6:
15585  // If a template [...] is explicitly specialized then that specialization
15586  // shall be declared before the first use of that specialization that would
15587  // cause an implicit instantiation to take place, in every translation unit
15588  // in which such a use occurs
15589  if (NeedDefinition &&
15591  Func->getMemberSpecializationInfo()))
15592  checkSpecializationVisibility(Loc, Func);
15593 
15594  if (getLangOpts().CUDA)
15595  CheckCUDACall(Loc, Func);
15596 
15597  // If we need a definition, try to create one.
15598  if (NeedDefinition && !Func->getBody()) {
15599  runWithSufficientStackSpace(Loc, [&] {
15600  if (CXXConstructorDecl *Constructor =
15601  dyn_cast<CXXConstructorDecl>(Func)) {
15602  Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15603  if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15604  if (Constructor->isDefaultConstructor()) {
15605  if (Constructor->isTrivial() &&
15606  !Constructor->hasAttr<DLLExportAttr>())
15607  return;
15608  DefineImplicitDefaultConstructor(Loc, Constructor);
15609  } else if (Constructor->isCopyConstructor()) {
15610  DefineImplicitCopyConstructor(Loc, Constructor);
15611  } else if (Constructor->isMoveConstructor()) {
15612  DefineImplicitMoveConstructor(Loc, Constructor);
15613  }
15614  } else if (Constructor->getInheritedConstructor()) {
15615  DefineInheritingConstructor(Loc, Constructor);
15616  }
15617  } else if (CXXDestructorDecl *Destructor =
15618  dyn_cast<CXXDestructorDecl>(Func)) {
15619  Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15620  if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15621  if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15622  return;
15623  DefineImplicitDestructor(Loc, Destructor);
15624  }
15625  if (Destructor->isVirtual() && getLangOpts().AppleKext)
15626  MarkVTableUsed(Loc, Destructor->getParent());
15627  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15628  if (MethodDecl->isOverloadedOperator() &&
15629  MethodDecl->getOverloadedOperator() == OO_Equal) {
15630  MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15631  if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15632  if (MethodDecl->isCopyAssignmentOperator())
15633  DefineImplicitCopyAssignment(Loc, MethodDecl);
15634  else if (MethodDecl->isMoveAssignmentOperator())
15635  DefineImplicitMoveAssignment(Loc, MethodDecl);
15636  }
15637  } else if (isa<CXXConversionDecl>(MethodDecl) &&
15638  MethodDecl->getParent()->isLambda()) {
15639  CXXConversionDecl *Conversion =
15640  cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15641  if (Conversion->isLambdaToBlockPointerConversion())
15642  DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15643  else
15644  DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15645  } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15646  MarkVTableUsed(Loc, MethodDecl->getParent());
15647  }
15648 
15649  if (Func->isDefaulted() && !Func->isDeleted()) {
15650  DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
15651  if (DCK != DefaultedComparisonKind::None)
15652  DefineDefaultedComparison(Loc, Func, DCK);
15653  }
15654 
15655  // Implicit instantiation of function templates and member functions of
15656  // class templates.
15657  if (Func->isImplicitlyInstantiable()) {
15660  SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15661  bool FirstInstantiation = PointOfInstantiation.isInvalid();
15662  if (FirstInstantiation) {
15663  PointOfInstantiation = Loc;
15664  Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15665  } else if (TSK != TSK_ImplicitInstantiation) {
15666  // Use the point of use as the point of instantiation, instead of the
15667  // point of explicit instantiation (which we track as the actual point
15668  // of instantiation). This gives better backtraces in diagnostics.
15669  PointOfInstantiation = Loc;
15670  }
15671 
15672  if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15673  Func->isConstexpr()) {
15674  if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15675  cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15676  CodeSynthesisContexts.size())
15677  PendingLocalImplicitInstantiations.push_back(
15678  std::make_pair(Func, PointOfInstantiation));
15679  else if (Func->isConstexpr())
15680  // Do not defer instantiations of constexpr functions, to avoid the
15681  // expression evaluator needing to call back into Sema if it sees a
15682  // call to such a function.
15683  InstantiateFunctionDefinition(PointOfInstantiation, Func);
15684  else {
15685  Func->setInstantiationIsPending(true);
15686  PendingInstantiations.push_back(
15687  std::make_pair(Func, PointOfInstantiation));
15688  // Notify the consumer that a function was implicitly instantiated.
15689  Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15690  }
15691  }
15692  } else {
15693  // Walk redefinitions, as some of them may be instantiable.
15694  for (auto i : Func->redecls()) {
15695  if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15696  MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15697  }
15698  }
15699  });
15700  }
15701 
15702  // C++14 [except.spec]p17:
15703  // An exception-specification is considered to be needed when:
15704  // - the function is odr-used or, if it appears in an unevaluated operand,
15705  // would be odr-used if the expression were potentially-evaluated;
15706  //
15707  // Note, we do this even if MightBeOdrUse is false. That indicates that the
15708  // function is a pure virtual function we're calling, and in that case the
15709  // function was selected by overload resolution and we need to resolve its
15710  // exception specification for a different reason.
15711  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15712  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15713  ResolveExceptionSpec(Loc, FPT);
15714 
15715  // If this is the first "real" use, act on that.
15716  if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15717  // Keep track of used but undefined functions.
15718  if (!Func->isDefined()) {
15719  if (mightHaveNonExternalLinkage(Func))
15720  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15721  else if (Func->getMostRecentDecl()->isInlined() &&
15722  !LangOpts.GNUInline &&
15723  !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15724  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15725  else if (isExternalWithNoLinkageType(Func))
15726  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15727  }
15728 
15729  // Some x86 Windows calling conventions mangle the size of the parameter
15730  // pack into the name. Computing the size of the parameters requires the
15731  // parameter types to be complete. Check that now.
15732  if (funcHasParameterSizeMangling(*this, Func))
15733  CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15734 
15735  Func->markUsed(Context);
15736  }
15737 
15738  if (LangOpts.OpenMP) {
15739  markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15740  if (LangOpts.OpenMPIsDevice)
15741  checkOpenMPDeviceFunction(Loc, Func);
15742  else
15743  checkOpenMPHostFunction(Loc, Func);
15744  }
15745 }
15746 
15747 /// Directly mark a variable odr-used. Given a choice, prefer to use
15748 /// MarkVariableReferenced since it does additional checks and then
15749 /// calls MarkVarDeclODRUsed.
15750 /// If the variable must be captured:
15751 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15752 /// - else capture it in the DeclContext that maps to the
15753 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15754 static void
15756  const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15757  // Keep track of used but undefined variables.
15758  // FIXME: We shouldn't suppress this warning for static data members.
15759  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15760  (!Var->isExternallyVisible() || Var->isInline() ||
15761  SemaRef.isExternalWithNoLinkageType(Var)) &&
15762  !(Var->isStaticDataMember() && Var->hasInit())) {
15763  SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15764  if (old.isInvalid())
15765  old = Loc;
15766  }
15767  QualType CaptureType, DeclRefType;
15768  if (SemaRef.LangOpts.OpenMP)
15769  SemaRef.tryCaptureOpenMPLambdas(Var);
15771  /*EllipsisLoc*/ SourceLocation(),
15772  /*BuildAndDiagnose*/ true,
15773  CaptureType, DeclRefType,
15774  FunctionScopeIndexToStopAt);
15775 
15776  Var->markUsed(SemaRef.Context);
15777 }
15778 
15780  SourceLocation Loc,
15781  unsigned CapturingScopeIndex) {
15782  MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15783 }
15784 
15785 static void
15787  ValueDecl *var, DeclContext *DC) {
15788  DeclContext *VarDC = var->getDeclContext();
15789 
15790  // If the parameter still belongs to the translation unit, then
15791  // we're actually just using one parameter in the declaration of
15792  // the next.
15793  if (isa<ParmVarDecl>(var) &&
15794  isa<TranslationUnitDecl>(VarDC))
15795  return;
15796 
15797  // For C code, don't diagnose about capture if we're not actually in code
15798  // right now; it's impossible to write a non-constant expression outside of
15799  // function context, so we'll get other (more useful) diagnostics later.
15800  //
15801  // For C++, things get a bit more nasty... it would be nice to suppress this
15802  // diagnostic for certain cases like using a local variable in an array bound
15803  // for a member of a local class, but the correct predicate is not obvious.
15804  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15805  return;
15806 
15807  unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15808  unsigned ContextKind = 3; // unknown
15809  if (isa<CXXMethodDecl>(VarDC) &&
15810  cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15811  ContextKind = 2;
15812  } else if (isa<FunctionDecl>(VarDC)) {
15813  ContextKind = 0;
15814  } else if (isa<BlockDecl>(VarDC)) {
15815  ContextKind = 1;
15816  }
15817 
15818  S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15819  << var << ValueKind << ContextKind << VarDC;
15820  S.Diag(var->getLocation(), diag::note_entity_declared_at)
15821  << var;
15822 
15823  // FIXME: Add additional diagnostic info about class etc. which prevents
15824  // capture.
15825 }
15826 
15827 
15829  bool &SubCapturesAreNested,
15830  QualType &CaptureType,
15831  QualType &DeclRefType) {
15832  // Check whether we've already captured it.
15833  if (CSI->CaptureMap.count(Var)) {
15834  // If we found a capture, any subcaptures are nested.
15835  SubCapturesAreNested = true;
15836 
15837  // Retrieve the capture type for this variable.
15838  CaptureType = CSI->getCapture(Var).getCaptureType();
15839 
15840  // Compute the type of an expression that refers to this variable.
15841  DeclRefType = CaptureType.getNonReferenceType();
15842 
15843  // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15844  // are mutable in the sense that user can change their value - they are
15845  // private instances of the captured declarations.
15846  const Capture &Cap = CSI->getCapture(Var);
15847  if (Cap.isCopyCapture() &&
15848  !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15849  !(isa<CapturedRegionScopeInfo>(CSI) &&
15850  cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15851  DeclRefType.addConst();
15852  return true;
15853  }
15854  return false;
15855 }
15856 
15857 // Only block literals, captured statements, and lambda expressions can
15858 // capture; other scopes don't work.
15860  SourceLocation Loc,
15861  const bool Diagnose, Sema &S) {
15862  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15864  else if (Var->hasLocalStorage()) {
15865  if (Diagnose)
15866  diagnoseUncapturableValueReference(S, Loc, Var, DC);
15867  }
15868  return nullptr;
15869 }
15870 
15871 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15872 // certain types of variables (unnamed, variably modified types etc.)
15873 // so check for eligibility.
15875  SourceLocation Loc,
15876  const bool Diagnose, Sema &S) {
15877 
15878  bool IsBlock = isa<BlockScopeInfo>(CSI);
15879  bool IsLambda = isa<LambdaScopeInfo>(CSI);
15880 
15881  // Lambdas are not allowed to capture unnamed variables
15882  // (e.g. anonymous unions).
15883  // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15884  // assuming that's the intent.
15885  if (IsLambda && !Var->getDeclName()) {
15886  if (Diagnose) {
15887  S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15888  S.Diag(Var->getLocation(), diag::note_declared_at);
15889  }
15890  return false;
15891  }
15892 
15893  // Prohibit variably-modified types in blocks; they're difficult to deal with.
15894  if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15895  if (Diagnose) {
15896  S.Diag(Loc, diag::err_ref_vm_type);
15897  S.Diag(Var->getLocation(), diag::note_previous_decl)
15898  << Var->getDeclName();
15899  }
15900  return false;
15901  }
15902  // Prohibit structs with flexible array members too.
15903  // We cannot capture what is in the tail end of the struct.
15904  if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15905  if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15906  if (Diagnose) {
15907  if (IsBlock)
15908  S.Diag(Loc, diag::err_ref_flexarray_type);
15909  else
15910  S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15911  << Var->getDeclName();
15912  S.Diag(Var->getLocation(), diag::note_previous_decl)
15913  << Var->getDeclName();
15914  }
15915  return false;
15916  }
15917  }
15918  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15919  // Lambdas and captured statements are not allowed to capture __block
15920  // variables; they don't support the expected semantics.
15921  if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15922  if (Diagnose) {
15923  S.Diag(Loc, diag::err_capture_block_variable)
15924  << Var->getDeclName() << !IsLambda;
15925  S.Diag(Var->getLocation(), diag::note_previous_decl)
15926  << Var->getDeclName();
15927  }
15928  return false;
15929  }
15930  // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15931  if (S.getLangOpts().OpenCL && IsBlock &&
15932  Var->getType()->isBlockPointerType()) {
15933  if (Diagnose)
15934  S.Diag(Loc, diag::err_opencl_block_ref_block);
15935  return false;
15936  }
15937 
15938  return true;
15939 }
15940 
15941 // Returns true if the capture by block was successful.
15942 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15943  SourceLocation Loc,
15944  const bool BuildAndDiagnose,
15945  QualType &CaptureType,
15946  QualType &DeclRefType,
15947  const bool Nested,
15948  Sema &S, bool Invalid) {
15949  bool ByRef = false;
15950 
15951  // Blocks are not allowed to capture arrays, excepting OpenCL.
15952  // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15953  // (decayed to pointers).
15954  if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15955  if (BuildAndDiagnose) {
15956  S.Diag(Loc, diag::err_ref_array_type);
15957  S.Diag(Var->getLocation(), diag::note_previous_decl)
15958  << Var->getDeclName();
15959  Invalid = true;
15960  } else {
15961  return false;
15962  }
15963  }
15964 
15965  // Forbid the block-capture of autoreleasing variables.
15966  if (!Invalid &&
15968  if (BuildAndDiagnose) {
15969  S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15970  << /*block*/ 0;
15971  S.Diag(Var->getLocation(), diag::note_previous_decl)
15972  << Var->getDeclName();
15973  Invalid = true;
15974  } else {
15975  return false;
15976  }
15977  }
15978 
15979  // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15980  if (const auto *PT = CaptureType->getAs<PointerType>()) {
15981  QualType PointeeTy = PT->getPointeeType();
15982 
15983  if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15985  !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15986  if (BuildAndDiagnose) {
15987  SourceLocation VarLoc = Var->getLocation();
15988  S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15989  S.Diag(VarLoc, diag::note_declare_parameter_strong);
15990  }
15991  }
15992  }
15993 
15994  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15995  if (HasBlocksAttr || CaptureType->isReferenceType() ||
15996  (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15997  // Block capture by reference does not change the capture or
15998  // declaration reference types.
15999  ByRef = true;
16000  } else {
16001  // Block capture by copy introduces 'const'.
16002  CaptureType = CaptureType.getNonReferenceType().withConst();
16003  DeclRefType = CaptureType;
16004  }
16005 
16006  // Actually capture the variable.
16007  if (BuildAndDiagnose)
16008  BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16009  CaptureType, Invalid);
16010 
16011  return !Invalid;
16012 }
16013 
16014 
16015 /// Capture the given variable in the captured region.
16017  VarDecl *Var,
16018  SourceLocation Loc,
16019  const bool BuildAndDiagnose,
16020  QualType &CaptureType,
16021  QualType &DeclRefType,
16022  const bool RefersToCapturedVariable,
16023  Sema &S, bool Invalid) {
16024  // By default, capture variables by reference.
16025  bool ByRef = true;
16026  // Using an LValue reference type is consistent with Lambdas (see below).
16027  if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16028  if (S.isOpenMPCapturedDecl(Var)) {
16029  bool HasConst = DeclRefType.isConstQualified();
16030  DeclRefType = DeclRefType.getUnqualifiedType();
16031  // Don't lose diagnostics about assignments to const.
16032  if (HasConst)
16033  DeclRefType.addConst();
16034  }
16035  ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16036  RSI->OpenMPCaptureLevel);
16037  }
16038 
16039  if (ByRef)
16040  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16041  else
16042  CaptureType = DeclRefType;
16043 
16044  // Actually capture the variable.
16045  if (BuildAndDiagnose)
16046  RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16047  Loc, SourceLocation(), CaptureType, Invalid);
16048 
16049  return !Invalid;
16050 }
16051 
16052 /// Capture the given variable in the lambda.
16054  VarDecl *Var,
16055  SourceLocation Loc,
16056  const bool BuildAndDiagnose,
16057  QualType &CaptureType,
16058  QualType &DeclRefType,
16059  const bool RefersToCapturedVariable,
16060  const Sema::TryCaptureKind Kind,
16061  SourceLocation EllipsisLoc,
16062  const bool IsTopScope,
16063  Sema &S, bool Invalid) {
16064  // Determine whether we are capturing by reference or by value.
16065  bool ByRef = false;
16066  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16067  ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16068  } else {
16070  }
16071 
16072  // Compute the type of the field that will capture this variable.
16073  if (ByRef) {
16074  // C++11 [expr.prim.lambda]p15:
16075  // An entity is captured by reference if it is implicitly or
16076  // explicitly captured but not captured by copy. It is
16077  // unspecified whether additional unnamed non-static data
16078  // members are declared in the closure type for entities
16079  // captured by reference.
16080  //
16081  // FIXME: It is not clear whether we want to build an lvalue reference
16082  // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16083  // to do the former, while EDG does the latter. Core issue 1249 will
16084  // clarify, but for now we follow GCC because it's a more permissive and
16085  // easily defensible position.
16086  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16087  } else {
16088  // C++11 [expr.prim.lambda]p14:
16089  // For each entity captured by copy, an unnamed non-static
16090  // data member is declared in the closure type. The
16091  // declaration order of these members is unspecified. The type
16092  // of such a data member is the type of the corresponding
16093  // captured entity if the entity is not a reference to an
16094  // object, or the referenced type otherwise. [Note: If the
16095  // captured entity is a reference to a function, the
16096  // corresponding data member is also a reference to a
16097  // function. - end note ]
16098  if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16099  if (!RefType->getPointeeType()->isFunctionType())
16100  CaptureType = RefType->getPointeeType();
16101  }
16102 
16103  // Forbid the lambda copy-capture of autoreleasing variables.
16104  if (!Invalid &&
16106  if (BuildAndDiagnose) {
16107  S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16108  S.Diag(Var->getLocation(), diag::note_previous_decl)
16109  << Var->getDeclName();
16110  Invalid = true;
16111  } else {
16112  return false;
16113  }
16114  }
16115 
16116  // Make sure that by-copy captures are of a complete and non-abstract type.
16117  if (!Invalid && BuildAndDiagnose) {
16118  if (!CaptureType->isDependentType() &&
16119  S.RequireCompleteType(Loc, CaptureType,
16120  diag::err_capture_of_incomplete_type,
16121  Var->getDeclName()))
16122  Invalid = true;
16123  else if (S.RequireNonAbstractType(Loc, CaptureType,
16124  diag::err_capture_of_abstract_type))
16125  Invalid = true;
16126  }
16127  }
16128 
16129  // Compute the type of a reference to this captured variable.
16130  if (ByRef)
16131  DeclRefType = CaptureType.getNonReferenceType();
16132  else {
16133  // C++ [expr.prim.lambda]p5:
16134  // The closure type for a lambda-expression has a public inline
16135  // function call operator [...]. This function call operator is
16136  // declared const (9.3.1) if and only if the lambda-expression's
16137  // parameter-declaration-clause is not followed by mutable.
16138  DeclRefType = CaptureType.getNonReferenceType();
16139  if (!LSI->Mutable && !CaptureType->isReferenceType())
16140  DeclRefType.addConst();
16141  }
16142 
16143  // Add the capture.
16144  if (BuildAndDiagnose)
16145  LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16146  Loc, EllipsisLoc, CaptureType, Invalid);
16147 
16148  return !Invalid;
16149 }
16150 
16152  VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16153  SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16154  QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16155  // An init-capture is notionally from the context surrounding its
16156  // declaration, but its parent DC is the lambda class.
16157  DeclContext *VarDC = Var->getDeclContext();
16158  if (Var->isInitCapture())
16159  VarDC = VarDC->getParent();
16160 
16161  DeclContext *DC = CurContext;
16162  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16163  ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16164  // We need to sync up the Declaration Context with the
16165  // FunctionScopeIndexToStopAt
16166  if (FunctionScopeIndexToStopAt) {
16167  unsigned FSIndex = FunctionScopes.size() - 1;
16168  while (FSIndex != MaxFunctionScopesIndex) {
16170  --FSIndex;
16171  }
16172  }
16173 
16174 
16175  // If the variable is declared in the current context, there is no need to
16176  // capture it.
16177  if (VarDC == DC) return true;
16178 
16179  // Capture global variables if it is required to use private copy of this
16180  // variable.
16181  bool IsGlobal = !Var->hasLocalStorage();
16182  if (IsGlobal &&
16183  !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16184  MaxFunctionScopesIndex)))
16185  return true;
16186  Var = Var->getCanonicalDecl();
16187 
16188  // Walk up the stack to determine whether we can capture the variable,
16189  // performing the "simple" checks that don't depend on type. We stop when
16190  // we've either hit the declared scope of the variable or find an existing
16191  // capture of that variable. We start from the innermost capturing-entity
16192  // (the DC) and ensure that all intervening capturing-entities
16193  // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16194  // declcontext can either capture the variable or have already captured
16195  // the variable.
16196  CaptureType = Var->getType();
16197  DeclRefType = CaptureType.getNonReferenceType();
16198  bool Nested = false;
16199  bool Explicit = (Kind != TryCapture_Implicit);
16200  unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16201  do {
16202  // Only block literals, captured statements, and lambda expressions can
16203  // capture; other scopes don't work.
16204  DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16205  ExprLoc,
16206  BuildAndDiagnose,
16207  *this);
16208  // We need to check for the parent *first* because, if we *have*
16209  // private-captured a global variable, we need to recursively capture it in
16210  // intermediate blocks, lambdas, etc.
16211  if (!ParentDC) {
16212  if (IsGlobal) {
16213  FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16214  break;
16215  }
16216  return true;
16217  }
16218 
16219  FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
16220  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16221 
16222 
16223  // Check whether we've already captured it.
16224  if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16225  DeclRefType)) {
16226  CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16227  break;
16228  }
16229  // If we are instantiating a generic lambda call operator body,
16230  // we do not want to capture new variables. What was captured
16231  // during either a lambdas transformation or initial parsing
16232  // should be used.
16234  if (BuildAndDiagnose) {
16235  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16237  Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16238  Diag(Var->getLocation(), diag::note_previous_decl)
16239  << Var->getDeclName();
16240  Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16241  } else
16242  diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16243  }
16244  return true;
16245  }
16246 
16247  // Try to capture variable-length arrays types.
16248  if (Var->getType()->isVariablyModifiedType()) {
16249  // We're going to walk down into the type and look for VLA
16250  // expressions.
16251  QualType QTy = Var->getType();
16252  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16253  QTy = PVD->getOriginalType();
16254  captureVariablyModifiedType(Context, QTy, CSI);
16255  }
16256 
16257  if (getLangOpts().OpenMP) {
16258  if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16259  // OpenMP private variables should not be captured in outer scope, so
16260  // just break here. Similarly, global variables that are captured in a
16261  // target region should not be captured outside the scope of the region.
16262  if (RSI->CapRegionKind == CR_OpenMP) {
16263  bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16264  // If the variable is private (i.e. not captured) and has variably
16265  // modified type, we still need to capture the type for correct
16266  // codegen in all regions, associated with the construct. Currently,
16267  // it is captured in the innermost captured region only.
16268  if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
16269  QualType QTy = Var->getType();
16270  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16271  QTy = PVD->getOriginalType();
16272  for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16273  I < E; ++I) {
16274  auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16275  FunctionScopes[FunctionScopesIndex - I]);
16276  assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
16277  "Wrong number of captured regions associated with the "
16278  "OpenMP construct.");
16279  captureVariablyModifiedType(Context, QTy, OuterRSI);
16280  }
16281  }
16282  bool IsTargetCap = !IsOpenMPPrivateDecl &&
16283  isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16284  // When we detect target captures we are looking from inside the
16285  // target region, therefore we need to propagate the capture from the
16286  // enclosing region. Therefore, the capture is not initially nested.
16287  if (IsTargetCap)
16288  adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16289 
16290  if (IsTargetCap || IsOpenMPPrivateDecl) {
16291  Nested = !IsTargetCap;
16292  DeclRefType = DeclRefType.getUnqualifiedType();
16293  CaptureType = Context.getLValueReferenceType(DeclRefType);
16294  break;
16295  }
16296  }
16297  }
16298  }
16299  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16300  // No capture-default, and this is not an explicit capture
16301  // so cannot capture this variable.
16302  if (BuildAndDiagnose) {
16303  Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16304  Diag(Var->getLocation(), diag::note_previous_decl)
16305  << Var->getDeclName();
16306  if (cast<LambdaScopeInfo>(CSI)->Lambda)
16307  Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16308  diag::note_lambda_decl);
16309  // FIXME: If we error out because an outer lambda can not implicitly
16310  // capture a variable that an inner lambda explicitly captures, we
16311  // should have the inner lambda do the explicit capture - because
16312  // it makes for cleaner diagnostics later. This would purely be done
16313  // so that the diagnostic does not misleadingly claim that a variable
16314  // can not be captured by a lambda implicitly even though it is captured
16315  // explicitly. Suggestion:
16316  // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16317  // at the function head
16318  // - cache the StartingDeclContext - this must be a lambda
16319  // - captureInLambda in the innermost lambda the variable.
16320  }
16321  return true;
16322  }
16323 
16324  FunctionScopesIndex--;
16325  DC = ParentDC;
16326  Explicit = false;
16327  } while (!VarDC->Equals(DC));
16328 
16329  // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16330  // computing the type of the capture at each step, checking type-specific
16331  // requirements, and adding captures if requested.
16332  // If the variable had already been captured previously, we start capturing
16333  // at the lambda nested within that one.
16334  bool Invalid = false;
16335  for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16336  ++I) {
16337  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16338 
16339  // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16340  // certain types of variables (unnamed, variably modified types etc.)
16341  // so check for eligibility.
16342  if (!Invalid)
16343  Invalid =
16344  !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16345 
16346  // After encountering an error, if we're actually supposed to capture, keep
16347  // capturing in nested contexts to suppress any follow-on diagnostics.
16348  if (Invalid && !BuildAndDiagnose)
16349  return true;
16350 
16351  if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16352  Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16353  DeclRefType, Nested, *this, Invalid);
16354  Nested = true;
16355  } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16356  Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16357  CaptureType, DeclRefType, Nested,
16358  *this, Invalid);
16359  Nested = true;
16360  } else {
16361  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16362  Invalid =
16363  !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16364  DeclRefType, Nested, Kind, EllipsisLoc,
16365  /*IsTopScope*/ I == N - 1, *this, Invalid);
16366  Nested = true;
16367  }
16368 
16369  if (Invalid && !BuildAndDiagnose)
16370  return true;
16371  }
16372  return Invalid;
16373 }
16374 
16376  TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16377  QualType CaptureType;
16378  QualType DeclRefType;
16379  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16380  /*BuildAndDiagnose=*/true, CaptureType,
16381  DeclRefType, nullptr);
16382 }
16383 
16385  QualType CaptureType;
16386  QualType DeclRefType;
16387  return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16388  /*BuildAndDiagnose=*/false, CaptureType,
16389  DeclRefType, nullptr);
16390 }
16391 
16393  QualType CaptureType;
16394  QualType DeclRefType;
16395 
16396  // Determine whether we can capture this variable.
16397  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16398  /*BuildAndDiagnose=*/false, CaptureType,
16399  DeclRefType, nullptr))
16400  return QualType();
16401 
16402  return DeclRefType;
16403 }
16404 
16405 namespace {
16406 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16407 // The produced TemplateArgumentListInfo* points to data stored within this
16408 // object, so should only be used in contexts where the pointer will not be
16409 // used after the CopiedTemplateArgs object is destroyed.
16410 class CopiedTemplateArgs {
16411  bool HasArgs;
16412  TemplateArgumentListInfo TemplateArgStorage;
16413 public:
16414  template<typename RefExpr>
16415  CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16416  if (HasArgs)
16417  E->copyTemplateArgumentsInto(TemplateArgStorage);
16418  }
16419  operator TemplateArgumentListInfo*()
16420 #ifdef __has_cpp_attribute
16421 #if __has_cpp_attribute(clang::lifetimebound)
16422  [[clang::lifetimebound]]
16423 #endif
16424 #endif
16425  {
16426  return HasArgs ? &TemplateArgStorage : nullptr;
16427  }
16428 };
16429 }
16430 
16431 /// Walk the set of potential results of an expression and mark them all as
16432 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16433 ///
16434 /// \return A new expression if we found any potential results, ExprEmpty() if
16435 /// not, and ExprError() if we diagnosed an error.
16437  NonOdrUseReason NOUR) {
16438  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16439  // an object that satisfies the requirements for appearing in a
16440  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16441  // is immediately applied." This function handles the lvalue-to-rvalue
16442  // conversion part.
16443  //
16444  // If we encounter a node that claims to be an odr-use but shouldn't be, we
16445  // transform it into the relevant kind of non-odr-use node and rebuild the
16446  // tree of nodes leading to it.
16447  //
16448  // This is a mini-TreeTransform that only transforms a restricted subset of
16449  // nodes (and only certain operands of them).
16450 
16451  // Rebuild a subexpression.
16452  auto Rebuild = [&](Expr *Sub) {
16453  return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16454  };
16455 
16456  // Check whether a potential result satisfies the requirements of NOUR.
16457  auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16458  // Any entity other than a VarDecl is always odr-used whenever it's named
16459  // in a potentially-evaluated expression.
16460  auto *VD = dyn_cast<VarDecl>(D);
16461  if (!VD)
16462  return true;
16463 
16464  // C++2a [basic.def.odr]p4:
16465  // A variable x whose name appears as a potentially-evalauted expression
16466  // e is odr-used by e unless
16467  // -- x is a reference that is usable in constant expressions, or
16468  // -- x is a variable of non-reference type that is usable in constant
16469  // expressions and has no mutable subobjects, and e is an element of
16470  // the set of potential results of an expression of
16471  // non-volatile-qualified non-class type to which the lvalue-to-rvalue
16472  // conversion is applied, or
16473  // -- x is a variable of non-reference type, and e is an element of the
16474  // set of potential results of a discarded-value expression to which
16475  // the lvalue-to-rvalue conversion is not applied
16476  //
16477  // We check the first bullet and the "potentially-evaluated" condition in
16478  // BuildDeclRefExpr. We check the type requirements in the second bullet
16479  // in CheckLValueToRValueConversionOperand below.
16480  switch (NOUR) {
16481  case NOUR_None:
16482  case NOUR_Unevaluated:
16483  llvm_unreachable("unexpected non-odr-use-reason");
16484 
16485  case NOUR_Constant:
16486  // Constant references were handled when they were built.
16487  if (VD->getType()->isReferenceType())
16488  return true;
16489  if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16490  if (RD->hasMutableFields())
16491  return true;
16492  if (!VD->isUsableInConstantExpressions(S.Context))
16493  return true;
16494  break;
16495 
16496  case NOUR_Discarded:
16497  if (VD->getType()->isReferenceType())
16498  return true;
16499  break;
16500  }
16501  return false;
16502  };
16503 
16504  // Mark that this expression does not constitute an odr-use.
16505  auto MarkNotOdrUsed = [&] {
16506  S.MaybeODRUseExprs.erase(E);
16507  if (LambdaScopeInfo *LSI = S.getCurLambda())
16508  LSI->markVariableExprAsNonODRUsed(E);
16509  };
16510 
16511  // C++2a [basic.def.odr]p2:
16512  // The set of potential results of an expression e is defined as follows:
16513  switch (E->getStmtClass()) {
16514  // -- If e is an id-expression, ...
16515  case Expr::DeclRefExprClass: {
16516  auto *DRE = cast<DeclRefExpr>(E);
16517  if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16518  break;
16519 
16520  // Rebuild as a non-odr-use DeclRefExpr.
16521  MarkNotOdrUsed();
16522  return DeclRefExpr::Create(
16523  S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16524  DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16525  DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16526  DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16527  }
16528 
16529  case Expr::FunctionParmPackExprClass: {
16530  auto *FPPE = cast<FunctionParmPackExpr>(E);
16531  // If any of the declarations in the pack is odr-used, then the expression
16532  // as a whole constitutes an odr-use.
16533  for (VarDecl *D : *FPPE)
16534  if (IsPotentialResultOdrUsed(D))
16535  return ExprEmpty();
16536 
16537  // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16538  // nothing cares about whether we marked this as an odr-use, but it might
16539  // be useful for non-compiler tools.
16540  MarkNotOdrUsed();
16541  break;
16542  }
16543 
16544  // -- If e is a subscripting operation with an array operand...
16545  case Expr::ArraySubscriptExprClass: {
16546  auto *ASE = cast<ArraySubscriptExpr>(E);
16547  Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16548  if (!OldBase->getType()->isArrayType())
16549  break;
16550  ExprResult Base = Rebuild(OldBase);
16551  if (!Base.isUsable())
16552  return Base;
16553  Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16554  Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16555  SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16556  return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16557  ASE->getRBracketLoc());
16558  }
16559 
16560  case Expr::MemberExprClass: {
16561  auto *ME = cast<MemberExpr>(E);
16562  // -- If e is a class member access expression [...] naming a non-static
16563  // data member...
16564  if (isa<FieldDecl>(ME->getMemberDecl())) {
16565  ExprResult Base = Rebuild(ME->getBase());
16566  if (!Base.isUsable())
16567  return Base;
16568  return MemberExpr::Create(
16569  S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16570  ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16571  ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16572  CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16573  ME->getObjectKind(), ME->isNonOdrUse());
16574  }
16575 
16576  if (ME->getMemberDecl()->isCXXInstanceMember())
16577  break;
16578 
16579  // -- If e is a class member access expression naming a static data member,
16580  // ...
16581  if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16582  break;
16583 
16584  // Rebuild as a non-odr-use MemberExpr.
16585  MarkNotOdrUsed();
16586  return MemberExpr::Create(
16587  S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16588  ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16589  ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16590  ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16591  return ExprEmpty();
16592  }
16593 
16594  case Expr::BinaryOperatorClass: {
16595  auto *BO = cast<BinaryOperator>(E);
16596  Expr *LHS = BO->getLHS();
16597  Expr *RHS = BO->getRHS();
16598  // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16599  if (BO->getOpcode() == BO_PtrMemD) {
16600  ExprResult Sub = Rebuild(LHS);
16601  if (!Sub.isUsable())
16602  return Sub;
16603  LHS = Sub.get();
16604  // -- If e is a comma expression, ...
16605  } else if (BO->getOpcode() == BO_Comma) {
16606  ExprResult Sub = Rebuild(RHS);
16607  if (!Sub.isUsable())
16608  return Sub;
16609  RHS = Sub.get();
16610  } else {
16611  break;
16612  }
16613  return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16614  LHS, RHS);
16615  }
16616 
16617  // -- If e has the form (e1)...
16618  case Expr::ParenExprClass: {
16619  auto *PE = cast<ParenExpr>(E);
16620  ExprResult Sub = Rebuild(PE->getSubExpr());
16621  if (!Sub.isUsable())
16622  return Sub;
16623  return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16624  }
16625 
16626  // -- If e is a glvalue conditional expression, ...
16627  // We don't apply this to a binary conditional operator. FIXME: Should we?
16628  case Expr::ConditionalOperatorClass: {
16629  auto *CO = cast<ConditionalOperator>(E);
16630  ExprResult LHS = Rebuild(CO->getLHS());
16631  if (LHS.isInvalid())
16632  return ExprError();
16633  ExprResult RHS = Rebuild(CO->getRHS());
16634  if (RHS.isInvalid())
16635  return ExprError();
16636  if (!LHS.isUsable() && !RHS.isUsable())
16637  return ExprEmpty();
16638  if (!LHS.isUsable())
16639  LHS = CO->getLHS();
16640  if (!RHS.isUsable())
16641  RHS = CO->getRHS();
16642  return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16643  CO->getCond(), LHS.get(), RHS.get());
16644  }
16645 
16646  // [Clang extension]
16647  // -- If e has the form __extension__ e1...
16648  case Expr::UnaryOperatorClass: {
16649  auto *UO = cast<UnaryOperator>(E);
16650  if (UO->getOpcode() != UO_Extension)
16651  break;
16652  ExprResult Sub = Rebuild(UO->getSubExpr());
16653  if (!Sub.isUsable())
16654  return Sub;
16655  return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16656  Sub.get());
16657  }
16658 
16659  // [Clang extension]
16660  // -- If e has the form _Generic(...), the set of potential results is the
16661  // union of the sets of potential results of the associated expressions.
16662  case Expr::GenericSelectionExprClass: {
16663  auto *GSE = cast<GenericSelectionExpr>(E);
16664 
16665  SmallVector<Expr *, 4> AssocExprs;
16666  bool AnyChanged = false;
16667  for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16668  ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16669  if (AssocExpr.isInvalid())
16670  return ExprError();
16671  if (AssocExpr.isUsable()) {
16672  AssocExprs.push_back(AssocExpr.get());
16673  AnyChanged = true;
16674  } else {
16675  AssocExprs.push_back(OrigAssocExpr);
16676  }
16677  }
16678 
16679  return AnyChanged ? S.CreateGenericSelectionExpr(
16680  GSE->getGenericLoc(), GSE->getDefaultLoc(),
16681  GSE->getRParenLoc(), GSE->getControllingExpr(),
16682  GSE->getAssocTypeSourceInfos(), AssocExprs)
16683  : ExprEmpty();
16684  }
16685 
16686  // [Clang extension]
16687  // -- If e has the form __builtin_choose_expr(...), the set of potential
16688  // results is the union of the sets of potential results of the
16689  // second and third subexpressions.
16690  case Expr::ChooseExprClass: {
16691  auto *CE = cast<ChooseExpr>(E);
16692 
16693  ExprResult LHS = Rebuild(CE->getLHS());
16694  if (LHS.isInvalid())
16695  return ExprError();
16696 
16697  ExprResult RHS = Rebuild(CE->getLHS());
16698  if (RHS.isInvalid())
16699  return ExprError();
16700 
16701  if (!LHS.get() && !RHS.get())
16702  return ExprEmpty();
16703  if (!LHS.isUsable())
16704  LHS = CE->getLHS();
16705  if (!RHS.isUsable())
16706  RHS = CE->getRHS();
16707 
16708  return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16709  RHS.get(), CE->getRParenLoc());
16710  }
16711 
16712  // Step through non-syntactic nodes.
16713  case Expr::ConstantExprClass: {
16714  auto *CE = cast<ConstantExpr>(E);
16715  ExprResult Sub = Rebuild(CE->getSubExpr());
16716  if (!Sub.isUsable())
16717  return Sub;
16718  return ConstantExpr::Create(S.Context, Sub.get());
16719  }
16720 
16721  // We could mostly rely on the recursive rebuilding to rebuild implicit
16722  // casts, but not at the top level, so rebuild them here.
16723  case Expr::ImplicitCastExprClass: {
16724  auto *ICE = cast<ImplicitCastExpr>(E);
16725  // Only step through the narrow set of cast kinds we expect to encounter.
16726  // Anything else suggests we've left the region in which potential results
16727  // can be found.
16728  switch (ICE->getCastKind()) {
16729  case CK_NoOp:
16730  case CK_DerivedToBase:
16731  case CK_UncheckedDerivedToBase: {
16732  ExprResult Sub = Rebuild(ICE->getSubExpr());
16733  if (!Sub.isUsable())
16734  return Sub;
16735  CXXCastPath Path(ICE->path());
16736  return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16737  ICE->getValueKind(), &Path);
16738  }
16739 
16740  default:
16741  break;
16742  }
16743  break;
16744  }
16745 
16746  default:
16747  break;
16748  }
16749 
16750  // Can't traverse through this node. Nothing to do.
16751  return ExprEmpty();
16752 }
16753 
16755  // Check whether the operand is or contains an object of non-trivial C union
16756  // type.
16757  if (E->getType().isVolatileQualified() &&
16760  checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16762  NTCUK_Destruct|NTCUK_Copy);
16763 
16764  // C++2a [basic.def.odr]p4:
16765  // [...] an expression of non-volatile-qualified non-class type to which
16766  // the lvalue-to-rvalue conversion is applied [...]
16767  if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16768  return E;
16769 
16770  ExprResult Result =
16772  if (Result.isInvalid())
16773  return ExprError();
16774  return Result.get() ? Result : E;
16775 }
16776 
16778  Res = CorrectDelayedTyposInExpr(Res);
16779 
16780  if (!Res.isUsable())
16781  return Res;
16782 
16783  // If a constant-expression is a reference to a variable where we delay
16784  // deciding whether it is an odr-use, just assume we will apply the
16785  // lvalue-to-rvalue conversion. In the one case where this doesn't happen
16786  // (a non-type template argument), we have special handling anyway.
16787  return CheckLValueToRValueConversionOperand(Res.get());
16788 }
16789 
16791  // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16792  // call.
16793  MaybeODRUseExprSet LocalMaybeODRUseExprs;
16794  std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16795 
16796  for (Expr *E : LocalMaybeODRUseExprs) {
16797  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16798  MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16799  DRE->getLocation(), *this);
16800  } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16801  MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16802  *this);
16803  } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16804  for (VarDecl *VD : *FP)
16805  MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16806  } else {
16807  llvm_unreachable("Unexpected expression");
16808  }
16809  }
16810 
16811  assert(MaybeODRUseExprs.empty() &&
16812  "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16813 }
16814 
16815 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16816  VarDecl *Var, Expr *E) {
16817  assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16818  isa<FunctionParmPackExpr>(E)) &&
16819  "Invalid Expr argument to DoMarkVarDeclReferenced");
16820  Var->setReferenced();
16821 
16822  if (Var->isInvalidDecl())
16823  return;
16824 
16825  auto *MSI = Var->getMemberSpecializationInfo();
16828 
16829  OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16830  bool UsableInConstantExpr =
16832 
16833  // C++20 [expr.const]p12:
16834  // A variable [...] is needed for constant evaluation if it is [...] a
16835  // variable whose name appears as a potentially constant evaluated
16836  // expression that is either a contexpr variable or is of non-volatile
16837  // const-qualified integral type or of reference type
16838  bool NeededForConstantEvaluation =
16839  isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16840 
16841  bool NeedDefinition =
16842  OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16843 
16845  dyn_cast<VarTemplateSpecializationDecl>(Var);
16846  assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16847  "Can't instantiate a partial template specialization.");
16848 
16849  // If this might be a member specialization of a static data member, check
16850  // the specialization is visible. We already did the checks for variable
16851  // template specializations when we created them.
16852  if (NeedDefinition && TSK != TSK_Undeclared &&
16853  !isa<VarTemplateSpecializationDecl>(Var))
16854  SemaRef.checkSpecializationVisibility(Loc, Var);
16855 
16856  // Perform implicit instantiation of static data members, static data member
16857  // templates of class templates, and variable template specializations. Delay
16858  // instantiations of variable templates, except for those that could be used
16859  // in a constant expression.
16860  if (NeedDefinition && isTemplateInstantiation(TSK)) {
16861  // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16862  // instantiation declaration if a variable is usable in a constant
16863  // expression (among other cases).
16864  bool TryInstantiating =
16865  TSK == TSK_ImplicitInstantiation ||
16866  (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16867 
16868  if (TryInstantiating) {
16869  SourceLocation PointOfInstantiation =
16870  MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16871  bool FirstInstantiation = PointOfInstantiation.isInvalid();
16872  if (FirstInstantiation) {
16873  PointOfInstantiation = Loc;
16874  if (MSI)
16875  MSI->setPointOfInstantiation(PointOfInstantiation);
16876  else
16877  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16878  }
16879 
16880  bool InstantiationDependent = false;
16881  bool IsNonDependent =
16883  VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16884  : true;
16885 
16886  // Do not instantiate specializations that are still type-dependent.
16887  if (IsNonDependent) {
16888  if (UsableInConstantExpr) {
16889  // Do not defer instantiations of variables that could be used in a
16890  // constant expression.
16891  SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16892  SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16893  });
16894  } else if (FirstInstantiation ||
16895  isa<VarTemplateSpecializationDecl>(Var)) {
16896  // FIXME: For a specialization of a variable template, we don't
16897  // distinguish between "declaration and type implicitly instantiated"
16898  // and "implicit instantiation of definition requested", so we have
16899  // no direct way to avoid enqueueing the pending instantiation
16900  // multiple times.
16901  SemaRef.PendingInstantiations
16902  .push_back(std::make_pair(Var, PointOfInstantiation));
16903  }
16904  }
16905  }
16906  }
16907 
16908  // C++2a [basic.def.odr]p4:
16909  // A variable x whose name appears as a potentially-evaluated expression e
16910  // is odr-used by e unless
16911  // -- x is a reference that is usable in constant expressions
16912  // -- x is a variable of non-reference type that is usable in constant
16913  // expressions and has no mutable subobjects [FIXME], and e is an
16914  // element of the set of potential results of an expression of
16915  // non-volatile-qualified non-class type to which the lvalue-to-rvalue
16916  // conversion is applied
16917  // -- x is a variable of non-reference type, and e is an element of the set
16918  // of potential results of a discarded-value expression to which the
16919  // lvalue-to-rvalue conversion is not applied [FIXME]
16920  //
16921  // We check the first part of the second bullet here, and
16922  // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16923  // FIXME: To get the third bullet right, we need to delay this even for
16924  // variables that are not usable in constant expressions.
16925 
16926  // If we already know this isn't an odr-use, there's nothing more to do.
16927  if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16928  if (DRE->isNonOdrUse())
16929  return;
16930  if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16931  if (ME->isNonOdrUse())
16932  return;
16933 
16934  switch (OdrUse) {
16935  case OdrUseContext::None:
16936  assert((!E || isa<FunctionParmPackExpr>(E)) &&
16937  "missing non-odr-use marking for unevaluated decl ref");
16938  break;
16939 
16940  case OdrUseContext::FormallyOdrUsed:
16941  // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16942  // behavior.
16943  break;
16944 
16945  case OdrUseContext::Used:
16946  // If we might later find that this expression isn't actually an odr-use,
16947  // delay the marking.
16948  if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16949  SemaRef.MaybeODRUseExprs.insert(E);
16950  else
16951  MarkVarDeclODRUsed(Var, Loc, SemaRef);
16952  break;
16953 
16954  case OdrUseContext::Dependent:
16955  // If this is a dependent context, we don't need to mark variables as
16956  // odr-used, but we may still need to track them for lambda capture.
16957  // FIXME: Do we also need to do this inside dependent typeid expressions
16958  // (which are modeled as unevaluated at this point)?
16959  const bool RefersToEnclosingScope =
16960  (SemaRef.CurContext != Var->getDeclContext() &&
16961  Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16962  if (RefersToEnclosingScope) {
16963  LambdaScopeInfo *const LSI =
16964  SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16965  if (LSI && (!LSI->CallOperator ||
16966  !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16967  // If a variable could potentially be odr-used, defer marking it so
16968  // until we finish analyzing the full expression for any
16969  // lvalue-to-rvalue
16970  // or discarded value conversions that would obviate odr-use.
16971  // Add it to the list of potential captures that will be analyzed
16972  // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16973  // unless the variable is a reference that was initialized by a constant
16974  // expression (this will never need to be captured or odr-used).
16975  //
16976  // FIXME: We can simplify this a lot after implementing P0588R1.
16977  assert(E && "Capture variable should be used in an expression.");
16978  if (!Var->getType()->isReferenceType() ||
16979  !Var->isUsableInConstantExpressions(SemaRef.Context))
16980  LSI->addPotentialCapture(E->IgnoreParens());
16981  }
16982  }
16983  break;
16984  }
16985 }
16986 
16987 /// Mark a variable referenced, and check whether it is odr-used
16988 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
16989 /// used directly for normal expressions referring to VarDecl.
16991  DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16992 }
16993 
16994 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16995  Decl *D, Expr *E, bool MightBeOdrUse) {
16996  if (SemaRef.isInOpenMPDeclareTargetContext())
16997  SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16998 
16999  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17000  DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17001  return;
17002  }
17003 
17004  SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17005 
17006  // If this is a call to a method via a cast, also mark the method in the
17007  // derived class used in case codegen can devirtualize the call.
17008  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17009  if (!ME)
17010  return;
17011  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17012  if (!MD)
17013  return;
17014  // Only attempt to devirtualize if this is truly a virtual call.
17015  bool IsVirtualCall = MD->isVirtual() &&
17016  ME->performsVirtualDispatch(SemaRef.getLangOpts());
17017  if (!IsVirtualCall)
17018  return;
17019 
17020  // If it's possible to devirtualize the call, mark the called function
17021  // referenced.
17023  ME->getBase(), SemaRef.getLangOpts().AppleKext);
17024  if (DM)
17025  SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17026 }
17027 
17028 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17030  // TODO: update this with DR# once a defect report is filed.
17031  // C++11 defect. The address of a pure member should not be an ODR use, even
17032  // if it's a qualified reference.
17033  bool OdrUse = true;
17034  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17035  if (Method->isVirtual() &&
17036  !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17037  OdrUse = false;
17038  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17039 }
17040 
17041 /// Perform reference-marking and odr-use handling for a MemberExpr.
17043  // C++11 [basic.def.odr]p2:
17044  // A non-overloaded function whose name appears as a potentially-evaluated
17045  // expression or a member of a set of candidate functions, if selected by
17046  // overload resolution when referred to from a potentially-evaluated
17047  // expression, is odr-used, unless it is a pure virtual function and its
17048  // name is not explicitly qualified.
17049  bool MightBeOdrUse = true;
17050  if (E->performsVirtualDispatch(getLangOpts())) {
17051  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17052  if (Method->isPure())
17053  MightBeOdrUse = false;
17054  }
17055  SourceLocation Loc =
17056  E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17057  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17058 }
17059 
17060 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17062  for (VarDecl *VD : *E)
17063  MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17064 }
17065 
17066 /// Perform marking for a reference to an arbitrary declaration. It
17067 /// marks the declaration referenced, and performs odr-use checking for
17068 /// functions and variables. This method should not be used when building a
17069 /// normal expression which refers to a variable.
17071  bool MightBeOdrUse) {
17072  if (MightBeOdrUse) {
17073  if (auto *VD = dyn_cast<VarDecl>(D)) {
17074  MarkVariableReferenced(Loc, VD);
17075  return;
17076  }
17077  }
17078  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17079  MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17080  return;
17081  }
17082  D->setReferenced();
17083 }
17084 
17085 namespace {
17086  // Mark all of the declarations used by a type as referenced.
17087  // FIXME: Not fully implemented yet! We need to have a better understanding
17088  // of when we're entering a context we should not recurse into.
17089  // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17090  // TreeTransforms rebuilding the type in a new context. Rather than
17091  // duplicating the TreeTransform logic, we should consider reusing it here.
17092  // Currently that causes problems when rebuilding LambdaExprs.
17093  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17094  Sema &S;
17095  SourceLocation Loc;
17096 
17097  public:
17098  typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17099 
17100  MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17101 
17102  bool TraverseTemplateArgument(const TemplateArgument &Arg);
17103  };
17104 }
17105 
17106 bool MarkReferencedDecls::TraverseTemplateArgument(
17107  const TemplateArgument &Arg) {
17108  {
17109  // A non-type template argument is a constant-evaluated context.
17112  if (Arg.getKind() == TemplateArgument::Declaration) {
17113  if (Decl *D = Arg.getAsDecl())
17114  S.MarkAnyDeclReferenced(Loc, D, true);
17115  } else if (Arg.getKind() == TemplateArgument::Expression) {
17117  }
17118  }
17119 
17120  return Inherited::TraverseTemplateArgument(Arg);
17121 }
17122 
17124  MarkReferencedDecls Marker(*this, Loc);
17125  Marker.TraverseType(T);
17126 }
17127 
17128 namespace {
17129  /// Helper class that marks all of the declarations referenced by
17130  /// potentially-evaluated subexpressions as "referenced".
17131  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
17132  Sema &S;
17133  bool SkipLocalVariables;
17134 
17135  public:
17137 
17138  EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17139  : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
17140 
17141  void VisitDeclRefExpr(DeclRefExpr *E) {
17142  // If we were asked not to visit local variables, don't.
17143  if (SkipLocalVariables) {
17144  if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17145  if (VD->hasLocalStorage())
17146  return;
17147  }
17148 
17149  S.MarkDeclRefReferenced(E);
17150  }
17151 
17152  void VisitMemberExpr(MemberExpr *E) {
17153  S.MarkMemberReferenced(E);
17154  Inherited::VisitMemberExpr(E);
17155  }
17156 
17157  void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
17159  E->getBeginLoc(),
17160  const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
17161  Visit(E->getSubExpr());
17162  }
17163 
17164  void VisitCXXNewExpr(CXXNewExpr *E) {
17165  if (E->getOperatorNew())
17167  if (E->getOperatorDelete())
17169  Inherited::VisitCXXNewExpr(E);
17170  }
17171 
17172  void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17173  if (E->getOperatorDelete())
17176  if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
17177  CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
17179  }
17180 
17181  Inherited::VisitCXXDeleteExpr(E);
17182  }
17183 
17184  void VisitCXXConstructExpr(CXXConstructExpr *E) {
17186  Inherited::VisitCXXConstructExpr(E);
17187  }
17188 
17189  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
17190  Visit(E->getExpr());
17191  }
17192  };
17193 }
17194 
17195 /// Mark any declarations that appear within this expression or any
17196 /// potentially-evaluated subexpressions as "referenced".
17197 ///
17198 /// \param SkipLocalVariables If true, don't mark local variables as
17199 /// 'referenced'.
17201  bool SkipLocalVariables) {
17202  EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17203 }
17204 
17205 /// Emit a diagnostic that describes an effect on the run-time behavior
17206 /// of the program being compiled.
17207 ///
17208 /// This routine emits the given diagnostic when the code currently being
17209 /// type-checked is "potentially evaluated", meaning that there is a
17210 /// possibility that the code will actually be executable. Code in sizeof()
17211 /// expressions, code used only during overload resolution, etc., are not
17212 /// potentially evaluated. This routine will suppress such diagnostics or,
17213 /// in the absolutely nutty case of potentially potentially evaluated
17214 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17215 /// later.
17216 ///
17217 /// This routine should be used for all diagnostics that describe the run-time
17218 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17219 /// Failure to do so will likely result in spurious diagnostics or failures
17220 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17222  const PartialDiagnostic &PD) {
17223  switch (ExprEvalContexts.back().Context) {
17224  case ExpressionEvaluationContext::Unevaluated:
17225  case ExpressionEvaluationContext::UnevaluatedList:
17226  case ExpressionEvaluationContext::UnevaluatedAbstract:
17227  case ExpressionEvaluationContext::DiscardedStatement:
17228  // The argument will never be evaluated, so don't complain.
17229  break;
17230 
17231  case ExpressionEvaluationContext::ConstantEvaluated:
17232  // Relevant diagnostics should be produced by constant evaluation.
17233  break;
17234 
17235  case ExpressionEvaluationContext::PotentiallyEvaluated:
17236  case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17237  if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17238  FunctionScopes.back()->PossiblyUnreachableDiags.
17239  push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17240  return true;
17241  }
17242 
17243  // The initializer of a constexpr variable or of the first declaration of a
17244  // static data member is not syntactically a constant evaluated constant,
17245  // but nonetheless is always required to be a constant expression, so we
17246  // can skip diagnosing.
17247  // FIXME: Using the mangling context here is a hack.
17248  if (auto *VD = dyn_cast_or_null<VarDecl>(
17249  ExprEvalContexts.back().ManglingContextDecl)) {
17250  if (VD->isConstexpr() ||
17251  (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17252  break;
17253  // FIXME: For any other kind of variable, we should build a CFG for its
17254  // initializer and check whether the context in question is reachable.
17255  }
17256 
17257  Diag(Loc, PD);
17258  return true;
17259  }
17260 
17261  return false;
17262 }
17263 
17264 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17265  const PartialDiagnostic &PD) {
17266  return DiagRuntimeBehavior(
17267  Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17268 }
17269 
17271  CallExpr *CE, FunctionDecl *FD) {
17272  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17273  return false;
17274 
17275  // If we're inside a decltype's expression, don't check for a valid return
17276  // type or construct temporaries until we know whether this is the last call.
17277  if (ExprEvalContexts.back().ExprContext ==
17278  ExpressionEvaluationContextRecord::EK_Decltype) {
17279  ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17280  return false;
17281  }
17282 
17283  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17284  FunctionDecl *FD;
17285  CallExpr *CE;
17286 
17287  public:
17288  CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17289  : FD(FD), CE(CE) { }
17290 
17291  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17292  if (!FD) {
17293  S.Diag(Loc, diag::err_call_incomplete_return)
17294  << T << CE->getSourceRange();
17295  return;
17296  }
17297 
17298  S.Diag(Loc, diag::err_call_function_incomplete_return)
17299  << CE->getSourceRange() << FD->getDeclName() << T;
17300  S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17301  << FD->getDeclName();
17302  }
17303  } Diagnoser(FD, CE);
17304 
17305  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17306  return true;
17307 
17308  return false;
17309 }
17310 
17311 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17312 // will prevent this condition from triggering, which is what we want.
17314  SourceLocation Loc;
17315 
17316  unsigned diagnostic = diag::warn_condition_is_assignment;
17317  bool IsOrAssign = false;
17318 
17319  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17320  if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17321  return;
17322 
17323  IsOrAssign = Op->getOpcode() == BO_OrAssign;
17324 
17325  // Greylist some idioms by putting them into a warning subcategory.
17326  if (ObjCMessageExpr *ME
17327  = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17328  Selector Sel = ME->getSelector();
17329 
17330  // self = [<foo> init...]
17331  if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17332  diagnostic = diag::warn_condition_is_idiomatic_assignment;
17333 
17334  // <foo> = [<bar> nextObject]
17335  else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17336  diagnostic = diag::warn_condition_is_idiomatic_assignment;
17337  }
17338 
17339  Loc = Op->getOperatorLoc();
17340  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17341  if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17342  return;
17343 
17344  IsOrAssign = Op->getOperator() == OO_PipeEqual;
17345  Loc = Op->getOperatorLoc();
17346  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17347  return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17348  else {
17349  // Not an assignment.
17350  return;
17351  }
17352 
17353  Diag(Loc, diagnostic) << E->getSourceRange();
17354 
17356  SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17357  Diag(Loc, diag::note_condition_assign_silence)
17358  << FixItHint::CreateInsertion(Open, "(")
17359  << FixItHint::CreateInsertion(Close, ")");
17360 
17361  if (IsOrAssign)
17362  Diag(Loc, diag::note_condition_or_assign_to_comparison)
17363  << FixItHint::CreateReplacement(Loc, "!=");
17364  else
17365  Diag(Loc, diag::note_condition_assign_to_comparison)
17366  << FixItHint::CreateReplacement(Loc, "==");
17367 }
17368 
17369 /// Redundant parentheses over an equality comparison can indicate
17370 /// that the user intended an assignment used as condition.
17372  // Don't warn if the parens came from a macro.
17373  SourceLocation parenLoc = ParenE->getBeginLoc();
17374  if (parenLoc.isInvalid() || parenLoc.isMacroID())
17375  return;
17376  // Don't warn for dependent expressions.
17377  if (ParenE->isTypeDependent())
17378  return;
17379 
17380  Expr *E = ParenE->IgnoreParens();
17381 
17382  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17383  if (opE->getOpcode() == BO_EQ &&
17384  opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17385  == Expr::MLV_Valid) {
17386  SourceLocation Loc = opE->getOperatorLoc();
17387 
17388  Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17389  SourceRange ParenERange = ParenE->getSourceRange();
17390  Diag(Loc, diag::note_equality_comparison_silence)
17391  << FixItHint::CreateRemoval(ParenERange.getBegin())
17392  << FixItHint::CreateRemoval(ParenERange.getEnd());
17393  Diag(Loc, diag::note_equality_comparison_to_assign)
17394  << FixItHint::CreateReplacement(Loc, "=");
17395  }
17396 }
17397 
17399  bool IsConstexpr) {
17400  DiagnoseAssignmentAsCondition(E);
17401  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17402  DiagnoseEqualityWithExtraParens(parenE);
17403 
17404  ExprResult result = CheckPlaceholderExpr(E);
17405  if (result.isInvalid()) return ExprError();
17406  E = result.get();
17407 
17408  if (!E->isTypeDependent()) {
17409  if (getLangOpts().CPlusPlus)
17410  return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17411 
17412  ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17413  if (ERes.isInvalid())
17414  return ExprError();
17415  E = ERes.get();
17416 
17417  QualType T = E->getType();
17418  if (!T->isScalarType()) { // C99 6.8.4.1p1
17419  Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17420  << T << E->getSourceRange();
17421  return ExprError();
17422  }
17423  CheckBoolLikeConversion(E, Loc);
17424  }
17425 
17426  return E;
17427 }
17428 
17430  Expr *SubExpr, ConditionKind CK) {
17431  // Empty conditions are valid in for-statements.
17432  if (!SubExpr)
17433  return ConditionResult();
17434 
17435  ExprResult Cond;
17436  switch (CK) {
17437  case ConditionKind::Boolean:
17438  Cond = CheckBooleanCondition(Loc, SubExpr);
17439  break;
17440 
17441  case ConditionKind::ConstexprIf:
17442  Cond = CheckBooleanCondition(Loc, SubExpr, true);
17443  break;
17444 
17445  case ConditionKind::Switch:
17446  Cond = CheckSwitchCondition(Loc, SubExpr);
17447  break;
17448  }
17449  if (Cond.isInvalid())
17450  return ConditionError();
17451 
17452  // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17453  FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17454  if (!FullExpr.get())
17455  return ConditionError();
17456 
17457  return ConditionResult(*this, nullptr, FullExpr,
17458  CK == ConditionKind::ConstexprIf);
17459 }
17460 
17461 namespace {
17462  /// A visitor for rebuilding a call to an __unknown_any expression
17463  /// to have an appropriate type.
17464  struct RebuildUnknownAnyFunction
17465  : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17466 
17467  Sema &S;
17468 
17469  RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17470 
17471  ExprResult VisitStmt(Stmt *S) {
17472  llvm_unreachable("unexpected statement!");
17473  }
17474 
17475  ExprResult VisitExpr(Expr *E) {
17476  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17477  << E->getSourceRange();
17478  return ExprError();
17479  }
17480 
17481  /// Rebuild an expression which simply semantically wraps another
17482  /// expression which it shares the type and value kind of.
17483  template <class T> ExprResult rebuildSugarExpr(T *E) {
17484  ExprResult SubResult = Visit(E->getSubExpr());
17485  if (SubResult.isInvalid()) return ExprError();
17486 
17487  Expr *SubExpr = SubResult.get();
17488  E->setSubExpr(SubExpr);
17489  E->setType(SubExpr->getType());
17490  E->setValueKind(SubExpr->getValueKind());
17491  assert(E->getObjectKind() == OK_Ordinary);
17492  return E;
17493  }
17494 
17495  ExprResult VisitParenExpr(ParenExpr *E) {
17496  return rebuildSugarExpr(E);
17497  }
17498 
17499  ExprResult VisitUnaryExtension(UnaryOperator *E) {
17500  return rebuildSugarExpr(E);
17501  }
17502 
17503  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17504  ExprResult SubResult = Visit(E->getSubExpr());
17505  if (SubResult.isInvalid()) return ExprError();
17506 
17507  Expr *SubExpr = SubResult.get();
17508  E->setSubExpr(SubExpr);
17509  E->setType(S.Context.getPointerType(SubExpr->getType()));
17510  assert(E->getValueKind() == VK_RValue);
17511  assert(E->getObjectKind() == OK_Ordinary);
17512  return E;
17513  }
17514 
17515  ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17516  if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17517 
17518  E->setType(VD->getType());
17519 
17520  assert(E->getValueKind() == VK_RValue);
17521  if (S.getLangOpts().CPlusPlus &&
17522  !(isa<CXXMethodDecl>(VD) &&
17523  cast<CXXMethodDecl>(VD)->isInstance()))
17524  E->setValueKind(VK_LValue);
17525 
17526  return E;
17527  }
17528 
17529  ExprResult VisitMemberExpr(MemberExpr *E) {
17530  return resolveDecl(E, E->getMemberDecl());
17531  }
17532 
17533  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17534  return resolveDecl(E, E->getDecl());
17535  }
17536  };
17537 }
17538 
17539 /// Given a function expression of unknown-any type, try to rebuild it
17540 /// to have a function type.
17541 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17542  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17543  if (Result.isInvalid()) return ExprError();
17544  return S.DefaultFunctionArrayConversion(Result.get());
17545 }
17546 
17547 namespace {
17548  /// A visitor for rebuilding an expression of type __unknown_anytype
17549  /// into one which resolves the type directly on the referring
17550  /// expression. Strict preservation of the original source
17551  /// structure is not a goal.
17552  struct RebuildUnknownAnyExpr
17553  : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17554 
17555  Sema &S;
17556 
17557  /// The current destination type.
17558  QualType DestType;
17559 
17560  RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17561  : S(S), DestType(CastType) {}
17562 
17563  ExprResult VisitStmt(Stmt *S) {
17564  llvm_unreachable("unexpected statement!");
17565  }
17566 
17567  ExprResult VisitExpr(Expr *E) {
17568  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17569  << E->getSourceRange();
17570  return ExprError();
17571  }
17572 
17573  ExprResult VisitCallExpr(CallExpr *E);
17574  ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17575 
17576  /// Rebuild an expression which simply semantically wraps another
17577  /// expression which it shares the type and value kind of.
17578  template <class T> ExprResult rebuildSugarExpr(T *E) {
17579  ExprResult SubResult = Visit(E->getSubExpr());
17580  if (SubResult.isInvalid()) return ExprError();
17581  Expr *SubExpr = SubResult.get();
17582  E->setSubExpr(SubExpr);
17583  E->setType(SubExpr->getType());
17584  E->setValueKind(SubExpr->getValueKind());
17585  assert(E->getObjectKind() == OK_Ordinary);
17586  return E;
17587  }
17588 
17589  ExprResult VisitParenExpr(ParenExpr *E) {
17590  return rebuildSugarExpr(E);
17591  }
17592 
17593  ExprResult VisitUnaryExtension(UnaryOperator *E) {
17594  return rebuildSugarExpr(E);
17595  }
17596 
17597  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17598  const PointerType *Ptr = DestType->getAs<PointerType>();
17599  if (!Ptr) {
17600  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17601  << E->getSourceRange();
17602  return ExprError();
17603  }
17604 
17605  if (isa<CallExpr>(E->getSubExpr())) {
17606  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17607  << E->getSourceRange();
17608  return ExprError();
17609  }
17610 
17611  assert(E->getValueKind() == VK_RValue);
17612  assert(E->getObjectKind() == OK_Ordinary);
17613  E->setType(DestType);
17614 
17615  // Build the sub-expression as if it were an object of the pointee type.
17616  DestType = Ptr->getPointeeType();
17617  ExprResult SubResult = Visit(E->getSubExpr());
17618  if (SubResult.isInvalid()) return ExprError();
17619  E->setSubExpr(SubResult.get());
17620  return E;
17621  }
17622 
17623  ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17624 
17625  ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17626 
17627  ExprResult VisitMemberExpr(MemberExpr *E) {
17628  return resolveDecl(E, E->getMemberDecl());
17629  }
17630 
17631  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17632  return resolveDecl(E, E->getDecl());
17633  }
17634  };
17635 }
17636 
17637 /// Rebuilds a call expression which yielded __unknown_anytype.
17638 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17639  Expr *CalleeExpr = E->getCallee();
17640 
17641  enum FnKind {
17642  FK_MemberFunction,
17643  FK_FunctionPointer,
17644  FK_BlockPointer
17645  };
17646 
17647  FnKind Kind;
17648  QualType CalleeType = CalleeExpr->getType();
17649  if (CalleeType == S.Context.BoundMemberTy) {
17650  assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17651  Kind = FK_MemberFunction;
17652  CalleeType = Expr::findBoundMemberType(CalleeExpr);
17653  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17654  CalleeType = Ptr->getPointeeType();
17655  Kind = FK_FunctionPointer;
17656  } else {
17657  CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17658  Kind = FK_BlockPointer;
17659  }
17660  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17661 
17662  // Verify that this is a legal result type of a function.
17663  if (DestType->isArrayType() || DestType->isFunctionType()) {
17664  unsigned diagID = diag::err_func_returning_array_function;
17665  if (Kind == FK_BlockPointer)
17666  diagID = diag::err_block_returning_array_function;
17667 
17668  S.Diag(E->getExprLoc(), diagID)
17669  << DestType->isFunctionType() << DestType;
17670  return ExprError();
17671  }
17672 
17673  // Otherwise, go ahead and set DestType as the call's result.
17674  E->setType(DestType.getNonLValueExprType(S.Context));
17676  assert(E->getObjectKind() == OK_Ordinary);
17677 
17678  // Rebuild the function type, replacing the result type with DestType.
17679  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17680  if (Proto) {
17681  // __unknown_anytype(...) is a special case used by the debugger when
17682  // it has no idea what a function's signature is.
17683  //
17684  // We want to build this call essentially under the K&R
17685  // unprototyped rules, but making a FunctionNoProtoType in C++
17686  // would foul up all sorts of assumptions. However, we cannot
17687  // simply pass all arguments as variadic arguments, nor can we
17688  // portably just call the function under a non-variadic type; see
17689  // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17690  // However, it turns out that in practice it is generally safe to
17691  // call a function declared as "A foo(B,C,D);" under the prototype
17692  // "A foo(B,C,D,...);". The only known exception is with the
17693  // Windows ABI, where any variadic function is implicitly cdecl
17694  // regardless of its normal CC. Therefore we change the parameter
17695  // types to match the types of the arguments.
17696  //
17697  // This is a hack, but it is far superior to moving the
17698  // corresponding target-specific code from IR-gen to Sema/AST.
17699 
17700  ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17701  SmallVector<QualType, 8> ArgTypes;
17702  if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17703  ArgTypes.reserve(E->getNumArgs());
17704  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17705  Expr *Arg = E->getArg(i);
17706  QualType ArgType = Arg->getType();
17707  if (E->isLValue()) {
17708  ArgType = S.Context.getLValueReferenceType(ArgType);
17709  } else if (E->isXValue()) {
17710  ArgType = S.Context.getRValueReferenceType(ArgType);
17711  }
17712  ArgTypes.push_back(ArgType);
17713  }
17714  ParamTypes = ArgTypes;
17715  }
17716  DestType = S.Context.getFunctionType(DestType, ParamTypes,
17717  Proto->getExtProtoInfo());
17718  } else {
17719  DestType = S.Context.getFunctionNoProtoType(DestType,
17720  FnType->getExtInfo());
17721  }
17722 
17723  // Rebuild the appropriate pointer-to-function type.
17724  switch (Kind) {
17725  case FK_MemberFunction:
17726  // Nothing to do.
17727  break;
17728 
17729  case FK_FunctionPointer:
17730  DestType = S.Context.getPointerType(DestType);
17731  break;
17732 
17733  case FK_BlockPointer:
17734  DestType = S.Context.getBlockPointerType(DestType);
17735  break;
17736  }
17737 
17738  // Finally, we can recurse.
17739  ExprResult CalleeResult = Visit(CalleeExpr);
17740  if (!CalleeResult.isUsable()) return ExprError();
17741  E->setCallee(CalleeResult.get());
17742 
17743  // Bind a temporary if necessary.
17744  return S.MaybeBindToTemporary(E);
17745 }
17746 
17747 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17748  // Verify that this is a legal result type of a call.
17749  if (DestType->isArrayType() || DestType->isFunctionType()) {
17750  S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17751  << DestType->isFunctionType() << DestType;
17752  return ExprError();
17753  }
17754 
17755  // Rewrite the method result type if available.
17756  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17757  assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17758  Method->setReturnType(DestType);
17759  }
17760 
17761  // Change the type of the message.
17762  E->setType(DestType.getNonReferenceType());
17764 
17765  return S.MaybeBindToTemporary(E);
17766 }
17767 
17768 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17769  // The only case we should ever see here is a function-to-pointer decay.
17770  if (E->getCastKind() == CK_FunctionToPointerDecay) {
17771  assert(E->getValueKind() == VK_RValue);
17772  assert(E->getObjectKind() == OK_Ordinary);
17773 
17774  E->setType(DestType);
17775 
17776  // Rebuild the sub-expression as the pointee (function) type.
17777  DestType = DestType->castAs<PointerType>()->getPointeeType();
17778 
17779  ExprResult Result = Visit(E->getSubExpr());
17780  if (!Result.isUsable()) return ExprError();
17781 
17782  E->setSubExpr(Result.get());
17783  return E;
17784  } else if (E->getCastKind() == CK_LValueToRValue) {
17785  assert(E->getValueKind() == VK_RValue);
17786  assert(E->getObjectKind() == OK_Ordinary);
17787 
17788  assert(isa<BlockPointerType>(E->getType()));
17789 
17790  E->setType(DestType);
17791 
17792  // The sub-expression has to be a lvalue reference, so rebuild it as such.
17793  DestType = S.Context.getLValueReferenceType(DestType);
17794 
17795  ExprResult Result = Visit(E->getSubExpr());
17796  if (!Result.isUsable()) return ExprError();
17797 
17798  E->setSubExpr(Result.get());
17799  return E;
17800  } else {
17801  llvm_unreachable("Unhandled cast type!");
17802  }
17803 }
17804 
17805 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17806  ExprValueKind ValueKind = VK_LValue;
17807  QualType Type = DestType;
17808 
17809  // We know how to make this work for certain kinds of decls:
17810 
17811  // - functions
17812  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17813  if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17814  DestType = Ptr->getPointeeType();
17815  ExprResult Result = resolveDecl(E, VD);
17816  if (Result.isInvalid()) return ExprError();
17817  return S.ImpCastExprToType(Result.get(), Type,
17818  CK_FunctionToPointerDecay, VK_RValue);
17819  }
17820 
17821  if (!Type->isFunctionType()) {
17822  S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17823  << VD << E->getSourceRange();
17824  return ExprError();
17825  }
17826  if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17827  // We must match the FunctionDecl's type to the hack introduced in
17828  // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17829  // type. See the lengthy commentary in that routine.
17830  QualType FDT = FD->getType();
17831  const FunctionType *FnType = FDT->castAs<FunctionType>();
17832  const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17833  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17834  if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17835  SourceLocation Loc = FD->getLocation();
17837  S.Context, FD->getDeclContext(), Loc, Loc,
17838  FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17839  SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17840  /*ConstexprKind*/ CSK_unspecified);
17841 
17842  if (FD->getQualifier())
17843  NewFD->setQualifierInfo(FD->getQualifierLoc());
17844 
17846  for (const auto &AI : FT->param_types()) {
17847  ParmVarDecl *Param =
17848  S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17849  Param->setScopeInfo(0, Params.size());
17850  Params.push_back(Param);
17851  }
17852  NewFD->setParams(Params);
17853  DRE->setDecl(NewFD);
17854  VD = DRE->getDecl();
17855  }
17856  }
17857 
17858  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17859  if (MD->isInstance()) {
17860  ValueKind = VK_RValue;
17861  Type = S.Context.BoundMemberTy;
17862  }
17863 
17864  // Function references aren't l-values in C.
17865  if (!S.getLangOpts().CPlusPlus)
17866  ValueKind = VK_RValue;
17867 
17868  // - variables
17869  } else if (isa<VarDecl>(VD)) {
17870  if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17871  Type = RefTy->getPointeeType();
17872  } else if (Type->isFunctionType()) {
17873  S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17874  << VD << E->getSourceRange();
17875  return ExprError();
17876  }
17877 
17878  // - nothing else
17879  } else {
17880  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17881  << VD << E->getSourceRange();
17882  return ExprError();
17883  }
17884 
17885  // Modifying the declaration like this is friendly to IR-gen but
17886  // also really dangerous.
17887  VD->setType(DestType);
17888  E->setType(Type);
17889  E->setValueKind(ValueKind);
17890  return E;
17891 }
17892 
17893 /// Check a cast of an unknown-any type. We intentionally only
17894 /// trigger this for C-style casts.
17897  ExprValueKind &VK, CXXCastPath &Path) {
17898  // The type we're casting to must be either void or complete.
17899  if (!CastType->isVoidType() &&
17900  RequireCompleteType(TypeRange.getBegin(), CastType,
17901  diag::err_typecheck_cast_to_incomplete))
17902  return ExprError();
17903 
17904  // Rewrite the casted expression from scratch.
17905  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17906  if (!result.isUsable()) return ExprError();
17907 
17908  CastExpr = result.get();
17909  VK = CastExpr->getValueKind();
17910  CastKind = CK_NoOp;
17911 
17912  return CastExpr;
17913 }
17914 
17916  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17917 }
17918 
17920  Expr *arg, QualType &paramType) {
17921  // If the syntactic form of the argument is not an explicit cast of
17922  // any sort, just do default argument promotion.
17923  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17924  if (!castArg) {
17925  ExprResult result = DefaultArgumentPromotion(arg);
17926  if (result.isInvalid()) return ExprError();
17927  paramType = result.get()->getType();
17928  return result;
17929  }
17930 
17931  // Otherwise, use the type that was written in the explicit cast.
17932  assert(!arg->hasPlaceholderType());
17933  paramType = castArg->getTypeAsWritten();
17934 
17935  // Copy-initialize a parameter of that type.
17936  InitializedEntity entity =
17937  InitializedEntity::InitializeParameter(Context, paramType,
17938  /*consumed*/ false);
17939  return PerformCopyInitialization(entity, callLoc, arg);
17940 }
17941 
17943  Expr *orig = E;
17944  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17945  while (true) {
17946  E = E->IgnoreParenImpCasts();
17947  if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17948  E = call->getCallee();
17949  diagID = diag::err_uncasted_call_of_unknown_any;
17950  } else {
17951  break;
17952  }
17953  }
17954 
17955  SourceLocation loc;
17956  NamedDecl *d;
17957  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17958  loc = ref->getLocation();
17959  d = ref->getDecl();
17960  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17961  loc = mem->getMemberLoc();
17962  d = mem->getMemberDecl();
17963  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17964  diagID = diag::err_uncasted_call_of_unknown_any;
17965  loc = msg->getSelectorStartLoc();
17966  d = msg->getMethodDecl();
17967  if (!d) {
17968  S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17969  << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17970  << orig->getSourceRange();
17971  return ExprError();
17972  }
17973  } else {
17974  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17975  << E->getSourceRange();
17976  return ExprError();
17977  }
17978 
17979  S.Diag(loc, diagID) << d << orig->getSourceRange();
17980 
17981  // Never recoverable.
17982  return ExprError();
17983 }
17984 
17985 /// Check for operands with placeholder types and complain if found.
17986 /// Returns ExprError() if there was an error and no recovery was possible.
17988  if (!getLangOpts().CPlusPlus) {
17989  // C cannot handle TypoExpr nodes on either side of a binop because it
17990  // doesn't handle dependent types properly, so make sure any TypoExprs have
17991  // been dealt with before checking the operands.
17992  ExprResult Result = CorrectDelayedTyposInExpr(E);
17993  if (!Result.isUsable()) return ExprError();
17994  E = Result.get();
17995  }
17996 
17997  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17998  if (!placeholderType) return E;
17999 
18000  switch (placeholderType->getKind()) {
18001 
18002  // Overloaded expressions.
18003  case BuiltinType::Overload: {
18004  // Try to resolve a single function template specialization.
18005  // This is obligatory.
18006  ExprResult Result = E;
18007  if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18008  return Result;
18009 
18010  // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18011  // leaves Result unchanged on failure.
18012  Result = E;
18013  if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18014  return Result;
18015 
18016  // If that failed, try to recover with a call.
18017  tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18018  /*complain*/ true);
18019  return Result;
18020  }
18021 
18022  // Bound member functions.
18023  case BuiltinType::BoundMember: {
18024  ExprResult result = E;
18025  const Expr *BME = E->IgnoreParens();
18026  PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18027  // Try to give a nicer diagnostic if it is a bound member that we recognize.
18028  if (isa<CXXPseudoDestructorExpr>(BME)) {
18029  PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18030  } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18031  if (ME->getMemberNameInfo().getName().getNameKind() ==
18033  PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18034  }
18035  tryToRecoverWithCall(result, PD,
18036  /*complain*/ true);
18037  return result;
18038  }
18039 
18040  // ARC unbridged casts.
18041  case BuiltinType::ARCUnbridgedCast: {
18042  Expr *realCast = stripARCUnbridgedCast(E);
18043  diagnoseARCUnbridgedCast(realCast);
18044  return realCast;
18045  }
18046 
18047  // Expressions of unknown type.
18048  case BuiltinType::UnknownAny:
18049  return diagnoseUnknownAnyExpr(*this, E);
18050 
18051  // Pseudo-objects.
18052  case BuiltinType::PseudoObject:
18053  return checkPseudoObjectRValue(E);
18054 
18055  case BuiltinType::BuiltinFn: {
18056  // Accept __noop without parens by implicitly converting it to a call expr.
18057  auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18058  if (DRE) {
18059  auto *FD = cast<FunctionDecl>(DRE->getDecl());
18060  if (FD->getBuiltinID() == Builtin::BI__noop) {
18061  E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18062  CK_BuiltinFnToFnPtr)
18063  .get();
18064  return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18066  }
18067  }
18068 
18069  Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18070  return ExprError();
18071  }
18072 
18073  // Expressions of unknown type.
18074  case BuiltinType::OMPArraySection:
18075  Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18076  return ExprError();
18077 
18078  // Everything else should be impossible.
18079 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18080  case BuiltinType::Id:
18081 #include "clang/Basic/OpenCLImageTypes.def"
18082 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18083  case BuiltinType::Id:
18084 #include "clang/Basic/OpenCLExtensionTypes.def"
18085 #define SVE_TYPE(Name, Id, SingletonId) \
18086  case BuiltinType::Id:
18087 #include "clang/Basic/AArch64SVEACLETypes.def"
18088 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18089 #define PLACEHOLDER_TYPE(Id, SingletonId)
18090 #include "clang/AST/BuiltinTypes.def"
18091  break;
18092  }
18093 
18094  llvm_unreachable("invalid placeholder type!");
18095 }
18096 
18098  if (E->isTypeDependent())
18099  return true;
18100  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18101  return E->getType()->isIntegralOrEnumerationType();
18102  return false;
18103 }
18104 
18105 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18106 ExprResult
18108  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18109  "Unknown Objective-C Boolean value!");
18110  QualType BoolT = Context.ObjCBuiltinBoolTy;
18111  if (!Context.getBOOLDecl()) {
18112  LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18114  if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18115  NamedDecl *ND = Result.getFoundDecl();
18116  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18117  Context.setBOOLDecl(TD);
18118  }
18119  }
18120  if (Context.getBOOLDecl())
18121  BoolT = Context.getBOOLType();
18122  return new (Context)
18123  ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18124 }
18125 
18128  SourceLocation RParen) {
18129 
18130  StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18131 
18132  auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18133  return Spec.getPlatform() == Platform;
18134  });
18135 
18136  VersionTuple Version;
18137  if (Spec != AvailSpecs.end())
18138  Version = Spec->getVersion();
18139 
18140  // The use of `@available` in the enclosing function should be analyzed to
18141  // warn when it's used inappropriately (i.e. not if(@available)).
18142  if (getCurFunctionOrMethodDecl())
18143  getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18144  else if (getCurBlock() || getCurLambda())
18145  getCurFunction()->HasPotentialAvailabilityViolations = true;
18146 
18147  return new (Context)
18148  ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18149 }
18150 
18152  assert(E->isTypeDependent());
18153  return isa<UnresolvedLookupExpr>(E);
18154 }
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1665
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:9500
void setTypoName(IdentifierInfo *II)
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1607
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
Definition: SemaExpr.cpp:13203
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5593
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1549
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2326
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:17200
VariadicCallType
Definition: Sema.h:10527
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1628
QualType getCurrentThisType()
Try to retrieve the type of the &#39;this&#39; pointer.
QualType withConst() const
Retrieves a version of this type with const applied.
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:17429
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1352
bool isClassMethod() const
Definition: DeclObjC.h:431
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:13566
CanQualType LongLongTy
Definition: ASTContext.h:1025
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
bool mightBeUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2292
Represents a function declaration or definition.
Definition: Decl.h:1783
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:15828
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1707
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:6824
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2692
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:800
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:6772
SourceRange getCorrectionRange() const
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc", where we know the signature a priori.
Definition: Builtins.h:138
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:10640
bool isObjCQualifiedIdType() const
True if this is equivalent to &#39;id.
Definition: Type.h:6030
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:790
bool isSignedOverflowDefined() const
Definition: LangOptions.h:322
CanQualType AccumTy
Definition: ASTContext.h:1029
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
void setKind(UnqualifiedIdKind kind)
Definition: DeclSpec.h:1043
A comparison.
Definition: Sema.h:10581
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1874
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:16754
A class which contains all the information about a particular captured value.
Definition: Decl.h:4043
PtrTy get() const
Definition: Ownership.h:80
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:15196
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
QualType getPointeeType() const
Definition: Type.h:2627
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3483
A (possibly-)qualified type.
Definition: Type.h:654
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
bool isBlockPointerType() const
Definition: Type.h:6512
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7043
Simple class containing the result of Sema::CorrectTypo.
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType)
Definition: SemaExpr.cpp:11993
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2185
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:6398
bool isArrayType() const
Definition: Type.h:6570
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:461
bool isMemberPointerType() const
Definition: Type.h:6552
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2919
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter&#39;s...
Definition: Overload.h:105
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:7436
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2525
unsigned char getFixedPointScale(QualType Ty) const
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2702
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:4156
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:12762
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1155
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3075
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:227
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:9484
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1929
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:7912
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:401
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:1283
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3445
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1064
llvm::APSInt getValue() const
Definition: FixedPoint.h:110
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:6603
CanQualType FractTy
Definition: ASTContext.h:1032
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C...
Definition: Type.h:6459
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3435
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:6945
CanQualType Char32Ty
Definition: ASTContext.h:1024
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7030
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:17942
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:248
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3306
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:245
bool isArithmeticType() const
Definition: Type.cpp:2036
Stmt - This represents one statement.
Definition: Stmt.h:66
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2689
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:38
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:315
Kind getKind() const
Definition: Type.h:2495
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:557
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:994
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:2941
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2021
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:659
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:225
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:11559
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:481
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4450
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:3173
Defines the SourceManager interface.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
static CharSourceRange getTokenRange(SourceRange R)
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:823
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:5049
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2200
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:140
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:86
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:10307
bool isAscii() const
Definition: Expr.h:1830
bool isRecordType() const
Definition: Type.h:6594
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Definition: SemaExpr.cpp:8865
Expr * getBase() const
Definition: Expr.h:2913
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:11948
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6764
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1958
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
const Type * getTypeForDecl() const
Definition: Decl.h:3053
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1411
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:9424
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:625
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:6954
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:14236
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:11756
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4086
StringRef getPlatform() const
Definition: Availability.h:52
bool isVirtual() const
Definition: DeclCXX.h:1976
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2218
bool isExtVectorType() const
Definition: Type.h:6610
void setType(QualType t)
Definition: Expr.h:138
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:8541
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:10601
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3037
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:11573
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3469
This is a while, do, switch, for, etc that can have break statements embedded into it...
Definition: Scope.h:51
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:906
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:4874
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer...
Definition: SemaExpr.cpp:7237
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:2732
Not a narrowing conversion.
Definition: Overload.h:231
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3901
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:774
bool isCopyCapture() const
Definition: ScopeInfo.h:584
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1994
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6452
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4149
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:17915
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4732
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1047
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2918
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14550
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
The base class of the type hierarchy.
Definition: Type.h:1450
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanQualType LongTy
Definition: ASTContext.h:1025
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10097
bool isClkEventT() const
Definition: Type.h:6691
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9808
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1931
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2889
Declaration of a variable template.
QualType getCorrespondingUnsignedType(QualType T) const
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:63
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:49
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1422
SourceLocation getEndLoc() const LLVM_READONLY
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:404
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:323
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
QualType withConst() const
Definition: Type.h:826
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:10167
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3688
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:707
TemplateNameKind Kind
The kind of template that Template refers to.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
A container of type source information.
Definition: Type.h:6227
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2481
static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1008
QualType getLogicalOperationType() const
The result type of logical operations, &#39;<&#39;, &#39;>&#39;, &#39;!=&#39;, etc.
Definition: ASTContext.h:1810
Floating point control options.
Definition: LangOptions.h:357
constexpr XRayInstrMask Function
Definition: XRayInstr.h:38
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=CSK_unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:1955
MS property subscript expression.
Definition: ExprCXX.h:937
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2883
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11392
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:11820
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1187
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition: Decl.cpp:3571
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:11090
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
Definition: SemaExpr.cpp:7376
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2383
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:554
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:4924
CanQualType WideCharTy
Definition: ASTContext.h:1020
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr *> Args)
Definition: SemaExpr.cpp:5101
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:15519
size_t param_size() const
Definition: Decl.h:2415
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:13800
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
isModifiableLvalueResult
Definition: Expr.h:278
CanQualType HalfTy
Definition: ASTContext.h:1040
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:14671
This name appears in an unevaluated operand.
Definition: Specifiers.h:164
QualType getElementType() const
Definition: Type.h:2910
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:592
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:13981
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:98
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1968
This file provides some common utility functions for processing Lambda related AST Constructs...
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:6684
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:10219
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:574
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.cpp:587
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:2945
RAII object that enters a new expression evaluation context.
Definition: Sema.h:12029
Represents a variable declaration or definition.
Definition: Decl.h:820
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
Definition: SemaExpr.cpp:15393
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:1088
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:243
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1792
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC &#39;id&#39; type.
Definition: ExprObjC.h:1492
void removeObjCLifetime()
Definition: Type.h:339
QualType getReturnType() const
Definition: Decl.h:2445
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3077
bool isParamConsumed(unsigned I) const
Definition: Type.h:4181
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:10196
unsigned getNumParams() const
Definition: Type.h:3964
bool isEnumeralType() const
Definition: Type.h:6598
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
APFixedPoint getFixedPointMax(QualType Ty) const
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:6907
CanQualType Float128Ty
Definition: ASTContext.h:1028
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3837
CanQualType ShortAccumTy
Definition: ASTContext.h:1029
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:8967
Represents a variable template specialization, which refers to a variable template with a given set o...
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:414
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1203
bool isAmbiguous() const
Definition: Lookup.h:301
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclClass * getCorrectionDeclAs() const
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
Definition: SemaExpr.cpp:2678
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Converts an integer to complex float type.
Definition: SemaExpr.cpp:986
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:13899
bool isInvalidDecl() const
Definition: DeclBase.h:553
bool isOverloaded() const
const Expr * getExprStmt() const
Definition: Stmt.cpp:335
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4093
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:176
static InitializationKind CreateDirectList(SourceLocation InitLoc)
CanQualType ShortFractTy
Definition: ASTContext.h:1032
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
Definition: SemaExpr.cpp:13837
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:16151
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
Definition: SemaExpr.cpp:11631
std::vector< FixItHint > Hints
The list of Hints generated so far.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:644
Represents a parameter to a function.
Definition: Decl.h:1595
Defines the clang::Expr interface and subclasses for C++ expressions.
tok::TokenKind getKind() const
Definition: Token.h:92
bool isAdditiveOp() const
Definition: Expr.h:3511
bool isEqualityOp() const
Definition: Expr.h:3522
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:669
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2105
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:9703
The collection of all-type qualifiers we support.
Definition: Type.h:143
bool isVariableArrayType() const
Definition: Type.h:6582
tok::TokenKind ContextKind
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g., it is a floating-point type or a vector thereof.
Definition: Type.cpp:2014
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1390
bool isXValue() const
Definition: Expr.h:260
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3395
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:17123
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:8210
Represents a struct/union/class.
Definition: Decl.h:3748
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
Definition: SemaExpr.cpp:7322
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:99
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:7587
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:361
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:425
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1012
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:725
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:272
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4408
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:14695
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1161
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:353
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3838
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:938
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1063
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1240
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations. ...
Definition: Decl.cpp:1879
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, QualType SrcType)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
Definition: SemaExpr.cpp:12908
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:10729
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:218
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(), or __builtin_FILE().
Definition: Expr.h:4295
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Represents a class type in Objective C.
Definition: Type.h:5694
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:147
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:329
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
Definition: SemaExpr.cpp:7826
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
A C++ nested-name-specifier augmented with source location information.
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:8412
ExprResult ExprEmpty()
Definition: Ownership.h:285
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:9535
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3971
LineState State
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4080
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2523
ObjCMethodFamily
A family of Objective-C methods.
Used for GCC&#39;s __alignof.
Definition: TypeTraits.h:106
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:950
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3428
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:5525
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
Definition: SemaExpr.cpp:8021
bool isCharType() const
Definition: Type.cpp:1871
field_range fields() const
Definition: Decl.h:3963
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:275
NameKind getNameKind() const
Determine what kind of name this is.
bool isObjCIdType() const
Definition: Type.h:6651
Represents a member of a struct/union/class.
Definition: Decl.h:2729
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We&#39;ve found a use of a templated declaration that would trigger an implicit instantiation.
The current expression is potentially evaluated at run time, which means that code may be generated t...
void setBOOLDecl(TypedefDecl *TD)
Save declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1910
Identity conversion (no conversion)
Definition: Overload.h:107
Stmt * getStmtExprResult()
Definition: Stmt.h:1424
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:96
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:1259
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:233
CanQualType LongAccumTy
Definition: ASTContext.h:1029
Floating point conversions (C++ [conv.double].
Definition: Overload.h:137
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4210
bool isReferenceType() const
Definition: Type.h:6516
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2712
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:17371
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:533
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:2723
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:855
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:10629
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:9450
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6744
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1908
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3771
bool isNull() const
Definition: Diagnostic.h:86
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
void setKind(tok::TokenKind K)
Definition: Token.h:93
A conditional (?:) operator.
Definition: Sema.h:10583
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:5518
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:18107
LookupResultKind getResultKind() const
Definition: Lookup.h:321
Expr * getSubExpr()
Definition: Expr.h:3202
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:723
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:7450
bool isObjCQualifiedClassType() const
Definition: Type.h:6645
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:470
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:15279
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:6433
bool isAssignmentOp() const
Definition: Expr.h:3563
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6881
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
IdentifierTable & Idents
Definition: ASTContext.h:580
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:100
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:125
bool isInvalidType() const
Definition: DeclSpec.h:2530
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2399
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
Values of this type can be null.
bool isUnarySelector() const
CanQualType LongFractTy
Definition: ASTContext.h:1032
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:62
DeclClass * getAsSingle() const
Definition: Lookup.h:507
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2570
StringRef getOpcodeStr() const
Definition: Expr.h:3490
SourceLocation getOpLoc() const
Definition: ExprObjC.h:597
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1286
static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:6993
bool isGLValue() const
Definition: Expr.h:261
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:997
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr *> Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4502
Describes an C or C++ initializer list.
Definition: Expr.h:4403
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter, check that it is non-null, and that if it is formed by array-to-pointer decay, the underlying array is sufficiently large.
Definition: SemaExpr.cpp:5386
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:11609
bool isArrow() const
Definition: ExprObjC.h:584
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:14365
bool isThisCapture() const
Definition: ScopeInfo.h:579
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:3853
BinaryOperatorKind
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:960
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:950
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:54
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10620
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2807
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:573
unsigned getLength() const
Definition: Expr.h:1823
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:527
Represents the results of name lookup.
Definition: Lookup.h:46
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:7267
PtrTy get() const
Definition: Ownership.h:170
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:703
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
Definition: SemaExpr.cpp:9005
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:446
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:2894
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2399
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:6929
static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:15874
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:14207
QualType getOriginalType() const
Definition: Decl.cpp:2681
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1309
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1866
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5706
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:588
A convenient class for passing around template argument information.
Definition: TemplateBase.h:554
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
const FormatToken & Tok
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:1400
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:7053
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing, variable initialization, and function return values.
Definition: SemaExpr.cpp:8244
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:55
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS)
Check for comparisons of floating point operands using != and ==.
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2173
Whether values of this type can be null is (explicitly) unspecified.
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:134
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:414
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of &#39;this&#39; is actually available in the current context, if it is a potentially ev...
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:66
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:5599
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3056
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:17029
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes...
Definition: SemaExpr.cpp:2233
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:726
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2549
Represents a declaration of a type.
Definition: Decl.h:3029
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3434
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6326
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:737
CanQualType PseudoObjectTy
Definition: ASTContext.h:1047
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:6392
LangAS getAddressSpace() const
Definition: Type.h:359
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:7172
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion, integral conversion, floating point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, or boolean conversion.
Definition: Overload.h:267
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:18126
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
void setTypoNNS(NestedNameSpecifier *NNS)
bool isArrow() const
Definition: Expr.h:3020
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:237
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1674
CanQualType LongDoubleTy
Definition: ASTContext.h:1028
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3000
Values of this type can never be null.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope...
Definition: SemaExpr.cpp:16392
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:81
Expr * getSizeExpr() const
Definition: Type.h:3058
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:7750
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
TypedefDecl * getBOOLDecl() const
Retrieve declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1905
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3871
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:492
StringKind
StringLiteral is followed by several trailing objects.
Definition: Expr.h:1733
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr *> Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:5909
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1166
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1709
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:5978
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2274
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:15243
bool isInt() const
Definition: APValue.h:361
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token...
Definition: Lexer.h:363
bool isRelationalOp() const
Definition: Expr.h:3519
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Definition: Decl.h:3425
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4159
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3150
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc)
CheckIndirectionOperand - Type check unary indirection (prefix &#39;*&#39;).
Definition: SemaExpr.cpp:12638
Helper class for OffsetOfExpr.
Definition: Expr.h:2163
The current expression occurs within a discarded statement.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2078
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1373
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1392
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:3983
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1818
const LangOptions & getLangOpts() const
Definition: Sema.h:1324
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:928
bool isInstance() const
Definition: DeclCXX.h:1959
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:176
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:691
bool isScalarType() const
Definition: Type.h:6866
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3511
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:8666
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:517
An ordinary object is located at an address in memory.
Definition: Specifiers.h:141
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:615
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for &#39;&&&#39; in the right hand of a &#39;||&#39; expr.
Definition: SemaExpr.cpp:13296
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:8441
Represents an ObjC class declaration.
Definition: DeclObjC.h:1186
This is an odr-use.
Definition: Specifiers.h:162
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition: Sema.h:1064
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2080
QualType getReturnType() const
Definition: DeclObjC.h:324
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:426
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3173
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:6394
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:5625
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:10625
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3034
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use...
Definition: SemaExpr.cpp:15481
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:404
QualType getBOOLType() const
type of &#39;BOOL&#39; type.
Definition: ASTContext.h:1915
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:3540
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:142
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that&#39;s being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:17919
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3).
Definition: SemaExpr.cpp:16990
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2172
CanQualType UnsignedCharTy
Definition: ASTContext.h:1026
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1202
const LangOptions & LangOpts
Definition: Sema.h:383
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6862
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2975
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:508
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e.g., it is an unsigned integer type or a vector.
Definition: Type.cpp:1998
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1662
void ActOnStmtExprError()
Definition: SemaExpr.cpp:13903
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:576
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:316
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:1054
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:2119
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
Definition: SemaExpr.cpp:16436
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:638
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1328
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1857
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas...
Definition: ScopeInfo.h:908
bool isHalfType() const
Definition: Type.h:6783
NodeId Parent
Definition: ASTDiff.cpp:191
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:9337
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why...
Definition: SemaExpr.cpp:1885
OverloadFixItKind Kind
The type of fix applied.
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3360
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:44
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK)
Definition: SemaExpr.cpp:3318
bool hasAttr() const
Definition: DeclBase.h:542
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3732
QualType getCorrespondingSaturatedType(QualType Ty) const
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:336
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:13370
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2560
void setNamingClass(CXXRecordDecl *Record)
Sets the &#39;naming class&#39; for this lookup.
Definition: Lookup.h:408
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
static bool ExprLooksBoolean(Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:7805
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:814
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1332
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1690
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:876
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:118
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:7862
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:574
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:17070
bool isUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2323
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:496
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:12839
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc...
Definition: SemaExpr.cpp:12918
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3501
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:533
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if &#39;E&#39;, which is an expression that is about to be modified, refers to a shadowing declaration...
Definition: SemaDecl.cpp:7477
Retains information about a captured region.
Definition: ScopeInfo.h:742
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1494
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
Definition: SemaExpr.cpp:13313
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:158
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr *> Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:1998
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1998
static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, ExprResult &RHS)
Handle when one or both operands are void type.
Definition: SemaExpr.cpp:7012
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:583
Specifies that the expression should never be value-dependent.
Definition: Expr.h:735
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9713
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:10615
void setSubExpr(Expr *E)
Definition: Expr.h:2077
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2372
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:6771
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:2047
OdrUseContext
Definition: SemaExpr.cpp:15466
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2601
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6331
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:9652
llvm::SmallPtrSet< Expr *, 2 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition: Sema.h:614
SourceLocation getLocation() const
Definition: Expr.h:1255
SourceRange getRange() const
Definition: DeclSpec.h:68
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
QualType getUsageType(QualType objectType) const
Retrieve the type of this instance variable when viewed as a member of a specific object type...
Definition: DeclObjC.cpp:1839
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4244
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:29
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:234
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:263
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6836
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1190
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr *> Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1695
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:9460
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
std::string getAsString(const LangOptions &LO) const
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:11456
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr&#39;s will refer to the same value as a comparison operand.
Definition: Expr.cpp:3985
unsigned Offset
Definition: Format.cpp:1827
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:939
unsigned getValue() const
Definition: Expr.h:1564
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3401
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:6157
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:154
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:151
void runWithSufficientStackSpace(llvm::function_ref< void()> Diag, llvm::function_ref< void()> Fn)
Run a given function on a stack with "sufficient" space.
Definition: Stack.h:40
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition...
Definition: SemaExpr.cpp:17313
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:13405
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6...
Definition: SemaExpr.cpp:1430
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1084
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:716
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:800
QualType getElementType() const
Definition: Type.h:2567
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1384
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4675
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:15364
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function)...
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4037
bool isInvalid() const
Definition: ScopeInfo.h:591
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:619
This represents one expression.
Definition: Expr.h:108
SourceLocation End
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:122
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for &#39;&&&#39; in the left hand of a &#39;||&#39; expr.
Definition: SemaExpr.cpp:13274
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2827
void setCallee(Expr *F)
Definition: Expr.h:2665
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:2130
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: Decl.h:2147
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:15859
int Id
Definition: ASTDiff.cpp:190
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1474
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1045
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4606
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:396
static bool EvaluatesAsTrue(Sema &S, Expr *E)
Returns true if the given expression can be evaluated as a constant &#39;true&#39;.
Definition: SemaExpr.cpp:13259
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1401
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2904
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition: ExprCXX.cpp:1531
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:315
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5732
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool isObjCBuiltinType() const
Definition: Type.h:6669
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7067
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:14738
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:13950
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:167
#define V(N, I)
Definition: ASTContext.h:2941
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5579
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2649
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1055
Expr * getCallee()
Definition: Expr.h:2663
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP constructs.
std::string getAsString() const
Retrieve the human-readable string for this name.
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:558
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:126
Defines the clang::Preprocessor interface.
bool isNullPtrType() const
Definition: Type.h:6802
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:15007
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
#define bool
Definition: stdbool.h:15
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3054
ObjCLifetime getObjCLifetime() const
Definition: Type.h:333
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:294
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we&#39;re currently inside an ObjC method...
Definition: SemaExpr.cpp:2605
bool isObjCClassType() const
Definition: Type.h:6657
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:13342
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
DeclContext * getDeclContext()
Definition: DeclBase.h:438
SourceLocation getLParenLoc() const
Definition: Expr.h:5188
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1809
Overload resolution succeeded.
Definition: Overload.h:53
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:6013
bool isAnyComplexType() const
Definition: Type.h:6602
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:8259
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode. ...
Definition: Expr.cpp:1318
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:13419
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:337
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1446
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:14757
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
Definition: DeclCXX.cpp:543
CanQualType ShortTy
Definition: ASTContext.h:1025
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:5642
static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, ValueDecl *var, DeclContext *DC)
Definition: SemaExpr.cpp:15786
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don&#39;t permit to be...
Definition: Sema.h:10634
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:17987
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2051
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2681
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1377
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:984
Represents a C++ template name within the type system.
Definition: TemplateName.h:191
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4442
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7919
Defines the clang::TypeLoc interface and its subclasses.
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:143
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1042
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:15344
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn&#39;t...
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:739
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:10399
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2859
QualType getType() const
Definition: Expr.h:137
bool isFunctionOrMethod() const
Definition: DeclBase.h:1836
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2203
Permit vector bitcasts between all vectors with the same total bit-width.
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:1047
Capture & getCapture(VarDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:697
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:620
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:11929
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:431
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:308
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:257
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
Definition: RewriteRule.cpp:82
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
void setAddressSpace(LangAS space)
Definition: Type.h:379
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, IdentKind IK, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:633
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr *> Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:5146
ScalarTypeKind
Definition: Type.h:2132
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:950
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:64
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:1079
bool isInvalid() const
Definition: Ownership.h:166
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:12740
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:2046
bool isInstanceMethod() const
Definition: DeclObjC.h:423
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1401
Preprocessor & getPreprocessor() const
Definition: Sema.h:1330
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of &#39;F&#39;...
Definition: Expr.h:3025
Represents a GCC generic vector type.
Definition: Type.h:3235
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2912
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14163
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2699
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1091
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:16790
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:6757
ValueDecl * getDecl()
Definition: Expr.h:1247
bool isUsable() const
Definition: Ownership.h:167
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2713
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1417
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:181
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2122
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:6386
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:301
const Expr * getSubExpr() const
Definition: Expr.h:2010
const Expr * getSubExpr() const
Definition: ExprCXX.h:1396
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:757
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:616
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:6171
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:415
void setBlockMangling(unsigned Number, Decl *Ctx)
Definition: Decl.h:4207
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:283
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:199
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args)
Check an argument list for placeholders that we won&#39;t try to handle later.
Definition: SemaExpr.cpp:5498
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:265
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2435
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:124
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2088
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12887
SourceRange getSourceRange() const
Definition: ExprCXX.h:141
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1662
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:6338
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14689
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:163
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:5368
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:421
A narrowing conversion, because a non-constant-expression variable might have got narrowed...
Definition: Overload.h:241
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing...
Definition: SemaExpr.cpp:5444
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6848
bool isUnresolvableResult() const
Definition: Lookup.h:317
static CharSourceRange getCharRange(SourceRange R)
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType)
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3604
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:110
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6315
bool isVoidPointerType() const
Definition: Type.cpp:521
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3848
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector...
Definition: SemaExpr.cpp:6629
bool isComparisonOp() const
Definition: Expr.h:3525
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:12391
RecordDecl * getDecl() const
Definition: Type.h:4505
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:129
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse)
Definition: SemaExpr.cpp:16994
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3515
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:754
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1590
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2056
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:7198
Wrapper for source info for arrays.
Definition: TypeLoc.h:1484
static bool captureInLambda(LambdaScopeInfo *LSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:16053
Expr * IgnoreConversionOperator() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3004
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:661
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
CanQualType OverloadTy
Definition: ASTContext.h:1045
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:9514
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:1075
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:1943
Integral conversions (C++ [conv.integral])
Definition: Overload.h:134
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1053
QualType getObjCIdRedefinitionType() const
Retrieve the type that id has been defined to, which may be different from the built-in id if id has ...
Definition: ASTContext.h:1661
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
CanQualType BuiltinFnTy
Definition: ASTContext.h:1046
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:171
Kind
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2844
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:513
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
QualType getCanonicalType() const
Definition: Type.h:6295
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:18097
not a target-specific vector type
Definition: Type.h:3239
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we&#39;re currently inside an ObjC method...
Definition: SemaExpr.cpp:2743
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5715
param_type_range param_types() const
Definition: Type.h:4119
A stack object to be created when performing template instantiation.
Definition: Sema.h:8243
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4167
VarDecl * getVariable() const
Definition: ScopeInfo.h:605
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3975
ASTContext & getASTContext() const
Definition: Sema.h:1331
Permit no implicit vector bitcasts.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:294
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:423
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5169
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3743
Encodes a location in the source.
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:5895
QualType getReturnType() const
Definition: Type.h:3680
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result)
GetFloatValue - Convert this numeric literal to a floating value, using the specified APFloat fltSema...
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4521
SourceLocation getOperatorLoc() const
Definition: Expr.h:3466
llvm::APSInt APSInt
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:6379
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6377
This represents &#39;#pragma omp declare reduction ...&#39; directive.
Definition: DeclOpenMP.h:102
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:556
Expression is not a Null pointer constant.
Definition: Expr.h:712
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:967
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:826
Expr * getSubExpr() const
Definition: Expr.h:2076
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5894
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
Definition: SemaExpr.cpp:7729
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2166
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:797
QualType getObjCSelRedefinitionType() const
Retrieve the type that &#39;SEL&#39; has been defined to, which may be different from the built-in &#39;SEL&#39; if &#39;...
Definition: ASTContext.h:1687
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12196
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10702
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:14703
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema &S, bool Invalid)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:16016
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:550
CastKind getCastKind() const
Definition: Expr.h:3196
Rounding to nearest, corresponds to "round.tonearest".
Definition: LangOptions.h:200
static void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:15755
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:2100
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2339
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:12334
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:3919
ArithConvKind
Context in which we&#39;re performing a usual arithmetic conversion.
Definition: Sema.h:10575
DeclarationName getName() const
getName - Returns the embedded declaration name.
static bool IgnoreCommaOperand(const Expr *E)
Definition: SemaExpr.cpp:12126
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of &#39;signed long long&#39; and &#39;unsigned long long&#39; for this targ...
Definition: TargetInfo.h:406
QualType getElementType() const
Definition: Type.h:3270
void setReferenced(bool R=true)
Definition: DeclBase.h:588
Represents the declaration of a label.
Definition: Decl.h:451
IncompatiblePointer - The assignment is between two pointers types that are not compatible, but we accept them as an extension.
Definition: Sema.h:10619
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3388
bool isOverloadedResult() const
Determines if the results are overloaded.
Definition: Lookup.h:313
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:139
bool isExternalWithNoLinkageType(ValueDecl *VD)
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can&#39;t b...
Definition: Sema.cpp:672
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr *> exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1550
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1844
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type...
Definition: SemaExpr.cpp:8948
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2466
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:15185
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl)
Definition: Expr.cpp:673
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:183
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:590
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
CanQualType FloatTy
Definition: ASTContext.h:1028
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2422
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:6270
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:743
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
CanQualType VoidTy
Definition: ASTContext.h:1016
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:24
Expr * getExpr(unsigned Init)
Definition: Expr.h:5171
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Describes the kind of initialization being performed, along with location information for tokens rela...
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
const TemplateArgumentListInfo & getTemplateArgsInfo() const
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
A compound assignment expression.
Definition: Sema.h:10585
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1886
Qualifiers withoutObjCLifetime() const
Definition: Type.h:321
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:8614
CanQualType Float16Ty
Definition: ASTContext.h:1041
bool isAnyPointerType() const
Definition: Type.h:6508
bool isObjCObjectPointerType() const
Definition: Type.h:6618
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:17061
This declaration is only a declaration.
Definition: Decl.h:1156
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3248
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:651
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion...
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:15779
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
llvm::APInt APInt
Definition: Integral.h:27
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:1058
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda&#39;s captured variables in the OpenMP region before the original lambda...
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:741
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3274
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1174
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2800
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:258
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
is AltiVec vector
Definition: Type.h:3242
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1713
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR)
Definition: SemaExpr.cpp:15001
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:207
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc)
Definition: SemaExpr.cpp:4584
bool isAddressSpaceOverlapping(const PointerType &other) const
Returns true if address spaces of pointers overlap.
Definition: Type.h:2637
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:914
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:6832
TypeClass getTypeClass() const
Definition: Type.h:1876
Used for C&#39;s _Alignof and C++&#39;s alignof.
Definition: TypeTraits.h:100
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3263
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:398
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:178
bool typesAreBlockPointerCompatible(QualType, QualType)
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1907
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:62
EnumDecl * getDecl() const
Definition: Type.h:4528
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
bool isVectorType() const
Definition: Type.h:6606
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:167
Optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
Assigning into this object requires a lifetime extension.
Definition: Type.h:177
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3954
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:896
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:163
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1569
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:15352
bool isCanonical() const
Definition: Type.h:6300
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:573
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:594
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2345
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
Definition: SemaExpr.cpp:10011
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2220
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag)
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2156
Defines the fixed point number interface.
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13912
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:224
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat &#39;semantics&#39; for the specified scalar floating point type.
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:9925
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1172
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptions FPFeatures)
Definition: SemaExpr.cpp:12854
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:17895
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3654
A POD class for pairing a NamedDecl* with an access specifier.
bool isRealType() const
Definition: Type.cpp:2027
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:6751
VersionTuple getVersion() const
Definition: Availability.h:51
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we&#39;re in ARC.
Definition: SemaExpr.cpp:6364
ReuseLambdaContextDecl_t
Definition: Sema.h:4437
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template...
Definition: Decl.cpp:2633
bool isMacroDefined(StringRef Id)
Represents an element in a path from a derived class to a base class.
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3910
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:17042
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4337
CanQualType CharTy
Definition: ASTContext.h:1018
Represents a template argument.
Definition: TemplateBase.h:50
bool isPipeType() const
Definition: Type.h:6710
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:1976
static bool isInvalid(LocType Loc, bool *Invalid)
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:170
NonConstCaptureKind
Is the given expression (which must be &#39;const&#39;) a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:11572
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union...
Definition: SemaExpr.cpp:8595
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2672
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:130
Dataflow Directional Tag Classes.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i...
bool isValid() const
Return true if this is a valid SourceLocation object.
ExtInfo getExtInfo() const
Definition: Type.h:3691
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:13239
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:214
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:9919
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2624
UnaryOperatorKind
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input)
Definition: SemaExpr.cpp:13885
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:586
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:11919
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2359
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
ArrayRef< Capture > captures() const
Definition: Decl.h:4164
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:9622
bool isSentinelNullExpr(const Expr *E)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:402
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:11198
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:529
typedef char* __builtin_va_list;
Definition: TargetInfo.h:228
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128 and long double if there is no support for such conve...
Definition: SemaExpr.cpp:1134
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:132
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:11238
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3756
bool isRecord() const
Definition: DeclBase.h:1863
bool isShiftOp() const
Definition: Expr.h:3513
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:10265
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2193
Represents a field injected from an anonymous union/struct into the parent scope. ...
Definition: Decl.h:2980
The &#39;<=>&#39; operator was used in an expression and a builtin operator was selected. ...
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
Definition: SemaExpr.cpp:8901
void setSubExpr(Expr *E)
Definition: Expr.h:3204
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:5874
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:17264
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:9301
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:1807
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:10413
const Expr * getInit() const
Definition: Decl.h:1229
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:595
A runtime availability query.
Definition: ExprObjC.h:1699
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> AssocTypes, ArrayRef< Expr *> AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression.
Definition: Expr.cpp:4243
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:113
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:189
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3027
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of &#39;this&#39;; zero if &#39;this&#39; is not captured...
Definition: ScopeInfo.h:648
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:3942
The name of a declaration.
StmtClass getStmtClass() const
Definition: Stmt.h:1109
VectorKind getVectorKind() const
Definition: Type.h:3280
const char * getCastKindName() const
Definition: Expr.h:3200
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:517
Expr * getDefaultArg()
Definition: Decl.cpp:2710
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2228
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:990
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:328
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2046
const Expr * getExpr() const
Definition: ExprCXX.h:1241
bool isBooleanType() const
Definition: Type.h:6894
Kind getKind() const
Definition: DeclBase.h:432
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type...
Definition: SemaExpr.cpp:17541
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:719
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6704
A set of unresolved declarations.
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR)=0
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:10658
bool InitField(InterpState &S, CodePtr OpPC, uint32_t I)
Definition: Interp.h:465
Expression is a C++11 nullptr.
Definition: Expr.h:725
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
Definition: SemaExpr.cpp:10357
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:3703
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a &#39;&&&#39; expr that is inside a &#39;||&#39; one.
Definition: SemaExpr.cpp:13246
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:175
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Expr * get() const
Definition: Sema.h:4072
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1421
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3337
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4428
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3371
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4521
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:11278
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:16777
unsigned getLength() const
Definition: Token.h:129
IdentifierInfo * getCorrectionAsIdentifierInfo() const
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1143
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr *> Args, SmallVectorImpl< Expr *> &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5262
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> Types, ArrayRef< Expr *> Exprs)
Definition: SemaExpr.cpp:1541
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2995
void addConst()
Definition: Type.h:263
bool isMacroID() const
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression&#39;s result is syntactically ignored, perform any conversions that are required.
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions)
Represents a pointer to an Objective C object.
Definition: Type.h:5951
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1333
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
Pointer to a block type.
Definition: Type.h:2716
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1049
The standard open() call: int open(const char *path, int oflag, ...);.
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures...
Definition: Sema.h:4035
static bool EvaluatesAsFalse(Sema &S, Expr *E)
Returns true if the given expression can be evaluated as a constant &#39;false&#39;.
Definition: SemaExpr.cpp:13267
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2410
unsigned getIntWidth(QualType T) const
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:9385
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2983
bool isUnscopedEnumerationType() const
Definition: Type.cpp:1864
Not an overloaded operator.
Definition: OperatorKinds.h:22
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4354
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:559
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4495
Complex values, per C99 6.2.5p11.
Definition: Type.h:2554
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:449
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2752
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length...
CanQualType UnknownAnyTy
Definition: ASTContext.h:1045
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3806
bool body_empty() const
Definition: Stmt.h:1359
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:6007
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2462
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it&#39;s possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:2094
ObjCLiteralKind
Definition: Sema.h:3105
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator"...
Definition: SemaExpr.cpp:7404
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6811
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2525
CanQualType UnsignedLongTy
Definition: ASTContext.h:1026
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1829
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
T * getAttr() const
Definition: DeclBase.h:538
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:6737
SourceLocation getLocation() const
Definition: ExprObjC.h:589
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:13328
const llvm::APInt & getSize() const
Definition: Type.h:2958
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2108
CanQualType DependentTy
Definition: ASTContext.h:1045
bool isImageType() const
Definition: Type.h:6703
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:1304
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:9567
bool isAtomicType() const
Definition: Type.h:6631
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:545
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:10577
bool isFunctionType() const
Definition: Type.h:6500
bool isObjCQualifiedIdType() const
Definition: Type.h:6639
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:1687
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:700
ExtVectorType - Extended vector type.
Definition: Type.h:3354
Opcode getOpcode() const
Definition: Expr.h:2071
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2750
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1747
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2321
CanQualType BoundMemberTy
Definition: ASTContext.h:1045
LValueClassification
Definition: Expr.h:263
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1112
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:8159
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:9834
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:13576
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn&#39;t need to call Usual...
Definition: SemaExpr.cpp:12232
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
qual_range quals() const
Definition: Type.h:6074
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3003
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:253
const Expr * getBase() const
Definition: ExprObjC.h:580
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3828
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Determine the kind of template specialization this function represents for the purpose of template in...
Definition: Decl.cpp:3772
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2915
bool isConstantArrayType() const
Definition: Type.h:6574
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:6372
llvm::DenseMap< VarDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:644
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:115
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:14144
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:144
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
Definition: SemaExpr.cpp:9049
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:413
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2104
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:546
This is a scope that can contain a declaration.
Definition: Scope.h:59
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:10156
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:8838
bool isObjCObjectType() const
Definition: Type.h:6622
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2115
CanQualType Char8Ty
Definition: ASTContext.h:1022
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2513
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function&#39;s address can be taken or not, optionally emitting a diagnostic if...
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:846
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1652
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2305
bool IsDependentFunctionNameExpr(Expr *E)
Check whether the given type-dependent expression will be the name of a function or another callable ...
Definition: SemaExpr.cpp:18151
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, and if so, remove it from the list of volatile-qualified assignments that we are going to warn are deprecated.
Definition: SemaExpr.cpp:15263
bool isArithmeticOp() const
Definition: Expr.h:2127
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:403
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:4724
Reading or writing from this object requires a barrier call.
Definition: Type.h:174
bool isQueueT() const
Definition: Type.h:6695
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4265
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:234
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
QualType getParamType(unsigned i) const
Definition: Type.h:3966
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:923
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:722
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E)
Definition: SemaExpr.cpp:16815
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:116
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr *> ArgExprs)
Definition: SemaExpr.cpp:1515
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2836
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:1042
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:11414
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:661
Describes the sequence of initializations required to initialize a given object or reference with a s...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:263
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6336
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1095
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2722
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:10206
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
Definition: Type.cpp:1958
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
Compatible - the types are compatible according to the standard.
Definition: Sema.h:10603
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
bool isVoidType() const
Definition: Type.h:6777
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CUDAFunctionTarget
Definition: Sema.h:11315
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:598
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1493
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4712
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2014
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4130
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3181
bool isNested() const
Definition: ScopeInfo.h:589
static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
Definition: SemaExpr.cpp:7759
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3808
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:1818
SourceLocation getRParenLoc() const
Definition: Expr.h:5189
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6283
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal...
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1959
CanQualType Char16Ty
Definition: ASTContext.h:1023
bool isMultiplicativeOp() const
Definition: Expr.h:3509
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that&#39;s ...
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type...
Definition: SemaExpr.cpp:6656
TryCaptureKind
Definition: Sema.h:4479
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:16384
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:1486
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10756
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:9398
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=None, OverloadCandidateParamOrder PO={})
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:582
Location information for a TemplateArgument.
Definition: TemplateBase.h:392
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:397
bool isSamplerT() const
Definition: Type.h:6683
bool isCXXThisCaptured() const
Determine whether the C++ &#39;this&#39; is captured.
Definition: ScopeInfo.h:679
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:184
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
Definition: Expr.h:223
bool isRValue() const
Definition: Expr.h:259
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:476
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1042
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2465
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr *> Args=None, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2034
SourceManager & getSourceManager() const
Definition: Sema.h:1329
iterator end() const
Definition: Lookup.h:336
A template-id, e.g., f<int>.
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, DeclContext *UsedContext)
Definition: ExprCXX.h:1229
This represents &#39;#pragma omp declare mapper ...&#39; directive.
Definition: DeclOpenMP.h:217
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:263
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12147
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all...
Definition: Sema.h:995
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3451
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1711
Defines the clang::TargetInfo interface.
bool isComplexIntegerType() const
Definition: Type.cpp:539
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2546
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:10540
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion)
type checking for vector binary operators.
Definition: SemaExpr.cpp:9130
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:160
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:1746
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3868
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:250
unsigned getCVRQualifiers() const
Definition: Type.h:276
ExprResult ExprError()
Definition: Ownership.h:279
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber...
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member&#39;s actual type.
Definition: SemaExpr.cpp:2778
uint64_t Width
Definition: ASTContext.h:157
CanQualType IntTy
Definition: ASTContext.h:1025
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:160
unsigned getNumElements() const
Definition: Type.h:3271
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:85
AssumedTemplateKind
Definition: Sema.h:6845
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2150
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:5667
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1751
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1171
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:825
The class facilities generation and storage of conversion FixIts.
Expr * getRHS() const
Definition: Expr.h:3476
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14557
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2259
bool isPointerType() const
Definition: Type.h:6504
bool isBitwiseOp() const
Definition: Expr.h:3516
bool isIncrementDecrementOp() const
Definition: Expr.h:2120
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e.g.
Definition: SemaExpr.cpp:1731
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2094
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:202
DeclaratorContext getContext() const
Definition: DeclSpec.h:1920
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1144
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:583
void setLocation(SourceLocation L)
Definition: Token.h:134
QualType getType() const
Definition: Decl.h:630
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:129
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
bool isFloatingType() const
Definition: Type.cpp:2005
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:385
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3158
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1531
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:10663
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:17398
This represents a decl that may have a name.
Definition: Decl.h:223
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1049
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:157
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:6846
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1274
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:1084
CanQualType BoolTy
Definition: ASTContext.h:1017
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3039
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression&#39;s return type is complete.
Definition: SemaExpr.cpp:17270
No keyword precedes the qualified type name.
Definition: Type.h:5227
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1882
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:13460
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1394
APSInt & getInt()
Definition: APValue.h:380
AccessControl getAccessControl() const
Definition: DeclObjC.h:1998
iterator begin() const
Definition: Lookup.h:335
CanQualType DoubleTy
Definition: ASTContext.h:1028
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parenthese and casts which do not change the value (including ptr->int casts of the sam...
Definition: Expr.cpp:3022
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:606
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2084
Describes an entity that is being initialized.
bool isFunctionPointerType() const
Definition: Type.h:6538
unsigned NumArgs
NumArgs - The number of template arguments.
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:524
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr *> Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:370
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:332
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, ArrayRef< Expr *> Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:85
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:7356
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3242
void setType(QualType newType)
Definition: Decl.h:631
void removeAddressSpace()
Definition: Type.h:384
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:15427
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3524
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
bool hasInit() const
Definition: Decl.cpp:2226
SourceLocation getBegin() const
AssignmentAction
Definition: Sema.h:2894
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:107
const LangOptions & getLangOpts() const
Definition: ASTContext.h:724
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1058
void WillReplaceSpecifier(bool ForceReplacement)
static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:15942
bool isBlockCapture() const
Definition: ScopeInfo.h:586
An implicit &#39;self&#39; parameter.
The lookup resulted in an error.
Definition: Sema.h:3509
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:12798
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2935
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:7744
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types...
Definition: Sema.h:10646
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
Defines enum values for all the target-independent builtin functions.
Declaration of a template function.
Definition: DeclTemplate.h:977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:592
ActionResult< Decl * > DeclResult
Definition: Ownership.h:269
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3533
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:140
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:15512
The current expression occurs within a braced-init-list within an unevaluated operand.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Definition: Expr.h:710
One specifier in an expression.
Definition: Availability.h:30
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2096
Attr - This represents one attribute.
Definition: Attr.h:45
SourceLocation getLocation() const
Definition: DeclBase.h:429
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1926
CastType
Definition: SemaCast.cpp:45
void startToken()
Reset all flags to cleared.
Definition: Token.h:171
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:13891
bool isExternallyVisible() const
Definition: Decl.h:362
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1372
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:12403
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6238
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:368
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:9473
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth, signed/unsigned.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:14353
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we&#39;re in an extern inline function and referring to a variable or function with interna...
Definition: SemaExpr.cpp:140
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1364
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2991
OriginalExprKind
Definition: SemaExpr.cpp:11750
CanQualType UnsignedIntTy
Definition: ASTContext.h:1026
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:3833
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1080
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:12619
A RAII object to temporarily push a declaration context.
Definition: Sema.h:797
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5057
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5967
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:256
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4371