clang  7.0.0
SemaExpr.cpp
Go to the documentation of this file.
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/TypeLoc.h"
31 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54  // See if this is an auto-typed variable whose initializer we are parsing.
55  if (ParsingInitForAutoVars.count(D))
56  return false;
57 
58  // See if this is a deleted function.
59  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60  if (FD->isDeleted())
61  return false;
62 
63  // If the function has a deduced return type, and we can't deduce it,
64  // then we can't use it either.
65  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66  DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67  return false;
68  }
69 
70  // See if this function is unavailable.
71  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
72  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
73  return false;
74 
75  return true;
76 }
77 
79  // Warn if this is used but marked unused.
80  if (const auto *A = D->getAttr<UnusedAttr>()) {
81  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
82  // should diagnose them.
83  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
84  A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
85  const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
86  if (DC && !DC->hasAttr<UnusedAttr>())
87  S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
88  }
89  }
90 }
91 
92 /// Emit a note explaining that this function is deleted.
94  assert(Decl->isDeleted());
95 
96  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
97 
98  if (Method && Method->isDeleted() && Method->isDefaulted()) {
99  // If the method was explicitly defaulted, point at that declaration.
100  if (!Method->isImplicit())
101  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
102 
103  // Try to diagnose why this special member function was implicitly
104  // deleted. This might fail, if that reason no longer applies.
105  CXXSpecialMember CSM = getSpecialMember(Method);
106  if (CSM != CXXInvalid)
107  ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
108 
109  return;
110  }
111 
112  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
113  if (Ctor && Ctor->isInheritingConstructor())
114  return NoteDeletedInheritingConstructor(Ctor);
115 
116  Diag(Decl->getLocation(), diag::note_availability_specified_here)
117  << Decl << true;
118 }
119 
120 /// Determine whether a FunctionDecl was ever declared with an
121 /// explicit storage class.
123  for (auto I : D->redecls()) {
124  if (I->getStorageClass() != SC_None)
125  return true;
126  }
127  return false;
128 }
129 
130 /// Check whether we're in an extern inline function and referring to a
131 /// variable or function with internal linkage (C11 6.7.4p3).
132 ///
133 /// This is only a warning because we used to silently accept this code, but
134 /// in many cases it will not behave correctly. This is not enabled in C++ mode
135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
136 /// and so while there may still be user mistakes, most of the time we can't
137 /// prove that there are errors.
139  const NamedDecl *D,
140  SourceLocation Loc) {
141  // This is disabled under C++; there are too many ways for this to fire in
142  // contexts where the warning is a false positive, or where it is technically
143  // correct but benign.
144  if (S.getLangOpts().CPlusPlus)
145  return;
146 
147  // Check if this is an inlined function or method.
148  FunctionDecl *Current = S.getCurFunctionDecl();
149  if (!Current)
150  return;
151  if (!Current->isInlined())
152  return;
153  if (!Current->isExternallyVisible())
154  return;
155 
156  // Check if the decl has internal linkage.
157  if (D->getFormalLinkage() != InternalLinkage)
158  return;
159 
160  // Downgrade from ExtWarn to Extension if
161  // (1) the supposedly external inline function is in the main file,
162  // and probably won't be included anywhere else.
163  // (2) the thing we're referencing is a pure function.
164  // (3) the thing we're referencing is another inline function.
165  // This last can give us false negatives, but it's better than warning on
166  // wrappers for simple C library functions.
167  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
168  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
169  if (!DowngradeWarning && UsedFn)
170  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
171 
172  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
173  : diag::ext_internal_in_extern_inline)
174  << /*IsVar=*/!UsedFn << D;
175 
177 
178  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
179  << D;
180 }
181 
183  const FunctionDecl *First = Cur->getFirstDecl();
184 
185  // Suggest "static" on the function, if possible.
186  if (!hasAnyExplicitStorageClass(First)) {
187  SourceLocation DeclBegin = First->getSourceRange().getBegin();
188  Diag(DeclBegin, diag::note_convert_inline_to_static)
189  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
190  }
191 }
192 
193 /// Determine whether the use of this declaration is valid, and
194 /// emit any corresponding diagnostics.
195 ///
196 /// This routine diagnoses various problems with referencing
197 /// declarations that can occur when using a declaration. For example,
198 /// it might warn if a deprecated or unavailable declaration is being
199 /// used, or produce an error (and return true) if a C++0x deleted
200 /// function is being used.
201 ///
202 /// \returns true if there was an error (this declaration cannot be
203 /// referenced), false otherwise.
204 ///
206  const ObjCInterfaceDecl *UnknownObjCClass,
207  bool ObjCPropertyAccess,
208  bool AvoidPartialAvailabilityChecks) {
209  SourceLocation Loc = Locs.front();
210  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
211  // If there were any diagnostics suppressed by template argument deduction,
212  // emit them now.
213  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
214  if (Pos != SuppressedDiagnostics.end()) {
215  for (const PartialDiagnosticAt &Suppressed : Pos->second)
216  Diag(Suppressed.first, Suppressed.second);
217 
218  // Clear out the list of suppressed diagnostics, so that we don't emit
219  // them again for this specialization. However, we don't obsolete this
220  // entry from the table, because we want to avoid ever emitting these
221  // diagnostics again.
222  Pos->second.clear();
223  }
224 
225  // C++ [basic.start.main]p3:
226  // The function 'main' shall not be used within a program.
227  if (cast<FunctionDecl>(D)->isMain())
228  Diag(Loc, diag::ext_main_used);
229  }
230 
231  // See if this is an auto-typed variable whose initializer we are parsing.
232  if (ParsingInitForAutoVars.count(D)) {
233  if (isa<BindingDecl>(D)) {
234  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
235  << D->getDeclName();
236  } else {
237  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
238  << D->getDeclName() << cast<VarDecl>(D)->getType();
239  }
240  return true;
241  }
242 
243  // See if this is a deleted function.
244  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245  if (FD->isDeleted()) {
246  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
247  if (Ctor && Ctor->isInheritingConstructor())
248  Diag(Loc, diag::err_deleted_inherited_ctor_use)
249  << Ctor->getParent()
250  << Ctor->getInheritedConstructor().getConstructor()->getParent();
251  else
252  Diag(Loc, diag::err_deleted_function_use);
253  NoteDeletedFunction(FD);
254  return true;
255  }
256 
257  // If the function has a deduced return type, and we can't deduce it,
258  // then we can't use it either.
259  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
260  DeduceReturnType(FD, Loc))
261  return true;
262 
263  if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
264  return true;
265  }
266 
267  auto getReferencedObjCProp = [](const NamedDecl *D) ->
268  const ObjCPropertyDecl * {
269  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
270  return MD->findPropertyDecl();
271  return nullptr;
272  };
273  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
274  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
275  return true;
276  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
277  return true;
278  }
279 
280  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
281  // Only the variables omp_in and omp_out are allowed in the combiner.
282  // Only the variables omp_priv and omp_orig are allowed in the
283  // initializer-clause.
284  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
285  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
286  isa<VarDecl>(D)) {
287  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
288  << getCurFunction()->HasOMPDeclareReductionCombiner;
289  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
290  return true;
291  }
292 
293  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
294  AvoidPartialAvailabilityChecks);
295 
296  DiagnoseUnusedOfDecl(*this, D, Loc);
297 
299 
300  return false;
301 }
302 
303 /// Retrieve the message suffix that should be added to a
304 /// diagnostic complaining about the given function being deleted or
305 /// unavailable.
307  std::string Message;
308  if (FD->getAvailability(&Message))
309  return ": " + Message;
310 
311  return std::string();
312 }
313 
314 /// DiagnoseSentinelCalls - This routine checks whether a call or
315 /// message-send is to a declaration with the sentinel attribute, and
316 /// if so, it checks that the requirements of the sentinel are
317 /// satisfied.
319  ArrayRef<Expr *> Args) {
320  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
321  if (!attr)
322  return;
323 
324  // The number of formal parameters of the declaration.
325  unsigned numFormalParams;
326 
327  // The kind of declaration. This is also an index into a %select in
328  // the diagnostic.
329  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
330 
331  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
332  numFormalParams = MD->param_size();
333  calleeType = CT_Method;
334  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
335  numFormalParams = FD->param_size();
336  calleeType = CT_Function;
337  } else if (isa<VarDecl>(D)) {
338  QualType type = cast<ValueDecl>(D)->getType();
339  const FunctionType *fn = nullptr;
340  if (const PointerType *ptr = type->getAs<PointerType>()) {
341  fn = ptr->getPointeeType()->getAs<FunctionType>();
342  if (!fn) return;
343  calleeType = CT_Function;
344  } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345  fn = ptr->getPointeeType()->castAs<FunctionType>();
346  calleeType = CT_Block;
347  } else {
348  return;
349  }
350 
351  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352  numFormalParams = proto->getNumParams();
353  } else {
354  numFormalParams = 0;
355  }
356  } else {
357  return;
358  }
359 
360  // "nullPos" is the number of formal parameters at the end which
361  // effectively count as part of the variadic arguments. This is
362  // useful if you would prefer to not have *any* formal parameters,
363  // but the language forces you to have at least one.
364  unsigned nullPos = attr->getNullPos();
365  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
367 
368  // The number of arguments which should follow the sentinel.
369  unsigned numArgsAfterSentinel = attr->getSentinel();
370 
371  // If there aren't enough arguments for all the formal parameters,
372  // the sentinel, and the args after the sentinel, complain.
373  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
374  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
375  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
376  return;
377  }
378 
379  // Otherwise, find the sentinel expression.
380  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
381  if (!sentinelExpr) return;
382  if (sentinelExpr->isValueDependent()) return;
383  if (Context.isSentinelNullExpr(sentinelExpr)) return;
384 
385  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
386  // or 'NULL' if those are actually defined in the context. Only use
387  // 'nil' for ObjC methods, where it's much more likely that the
388  // variadic arguments form a list of object pointers.
389  SourceLocation MissingNilLoc
390  = getLocForEndOfToken(sentinelExpr->getLocEnd());
391  std::string NullValue;
392  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
393  NullValue = "nil";
394  else if (getLangOpts().CPlusPlus11)
395  NullValue = "nullptr";
396  else if (PP.isMacroDefined("NULL"))
397  NullValue = "NULL";
398  else
399  NullValue = "(void*) 0";
400 
401  if (MissingNilLoc.isInvalid())
402  Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
403  else
404  Diag(MissingNilLoc, diag::warn_missing_sentinel)
405  << int(calleeType)
406  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
407  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
408 }
409 
411  return E ? E->getSourceRange() : SourceRange();
412 }
413 
414 //===----------------------------------------------------------------------===//
415 // Standard Promotions and Conversions
416 //===----------------------------------------------------------------------===//
417 
418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
420  // Handle any placeholder expressions which made it here.
421  if (E->getType()->isPlaceholderType()) {
422  ExprResult result = CheckPlaceholderExpr(E);
423  if (result.isInvalid()) return ExprError();
424  E = result.get();
425  }
426 
427  QualType Ty = E->getType();
428  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
429 
430  if (Ty->isFunctionType()) {
431  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
432  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
433  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
434  return ExprError();
435 
436  E = ImpCastExprToType(E, Context.getPointerType(Ty),
437  CK_FunctionToPointerDecay).get();
438  } else if (Ty->isArrayType()) {
439  // In C90 mode, arrays only promote to pointers if the array expression is
440  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
441  // type 'array of type' is converted to an expression that has type 'pointer
442  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
443  // that has type 'array of type' ...". The relevant change is "an lvalue"
444  // (C90) to "an expression" (C99).
445  //
446  // C++ 4.2p1:
447  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
448  // T" can be converted to an rvalue of type "pointer to T".
449  //
450  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
451  E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
452  CK_ArrayToPointerDecay).get();
453  }
454  return E;
455 }
456 
458  // Check to see if we are dereferencing a null pointer. If so,
459  // and if not volatile-qualified, this is undefined behavior that the
460  // optimizer will delete, so warn about it. People sometimes try to use this
461  // to get a deterministic trap and are surprised by clang's behavior. This
462  // only handles the pattern "*null", which is a very syntactic check.
463  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
464  if (UO->getOpcode() == UO_Deref &&
465  UO->getSubExpr()->IgnoreParenCasts()->
466  isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
467  !UO->getType().isVolatileQualified()) {
468  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
469  S.PDiag(diag::warn_indirection_through_null)
470  << UO->getSubExpr()->getSourceRange());
471  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
472  S.PDiag(diag::note_indirection_through_null));
473  }
474 }
475 
476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
477  SourceLocation AssignLoc,
478  const Expr* RHS) {
479  const ObjCIvarDecl *IV = OIRE->getDecl();
480  if (!IV)
481  return;
482 
483  DeclarationName MemberName = IV->getDeclName();
484  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
485  if (!Member || !Member->isStr("isa"))
486  return;
487 
488  const Expr *Base = OIRE->getBase();
489  QualType BaseType = Base->getType();
490  if (OIRE->isArrow())
491  BaseType = BaseType->getPointeeType();
492  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
493  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
494  ObjCInterfaceDecl *ClassDeclared = nullptr;
495  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
496  if (!ClassDeclared->getSuperClass()
497  && (*ClassDeclared->ivar_begin()) == IV) {
498  if (RHS) {
499  NamedDecl *ObjectSetClass =
501  &S.Context.Idents.get("object_setClass"),
503  if (ObjectSetClass) {
504  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
505  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
506  FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
508  AssignLoc), ",") <<
509  FixItHint::CreateInsertion(RHSLocEnd, ")");
510  }
511  else
512  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
513  } else {
514  NamedDecl *ObjectGetClass =
516  &S.Context.Idents.get("object_getClass"),
518  if (ObjectGetClass)
519  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
520  FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
522  SourceRange(OIRE->getOpLoc(),
523  OIRE->getLocEnd()), ")");
524  else
525  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
526  }
527  S.Diag(IV->getLocation(), diag::note_ivar_decl);
528  }
529  }
530 }
531 
533  // Handle any placeholder expressions which made it here.
534  if (E->getType()->isPlaceholderType()) {
535  ExprResult result = CheckPlaceholderExpr(E);
536  if (result.isInvalid()) return ExprError();
537  E = result.get();
538  }
539 
540  // C++ [conv.lval]p1:
541  // A glvalue of a non-function, non-array type T can be
542  // converted to a prvalue.
543  if (!E->isGLValue()) return E;
544 
545  QualType T = E->getType();
546  assert(!T.isNull() && "r-value conversion on typeless expression?");
547 
548  // We don't want to throw lvalue-to-rvalue casts on top of
549  // expressions of certain types in C++.
550  if (getLangOpts().CPlusPlus &&
551  (E->getType() == Context.OverloadTy ||
552  T->isDependentType() ||
553  T->isRecordType()))
554  return E;
555 
556  // The C standard is actually really unclear on this point, and
557  // DR106 tells us what the result should be but not why. It's
558  // generally best to say that void types just doesn't undergo
559  // lvalue-to-rvalue at all. Note that expressions of unqualified
560  // 'void' type are never l-values, but qualified void can be.
561  if (T->isVoidType())
562  return E;
563 
564  // OpenCL usually rejects direct accesses to values of 'half' type.
565  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
566  T->isHalfType()) {
567  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
568  << 0 << T;
569  return ExprError();
570  }
571 
573  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
574  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
575  &Context.Idents.get("object_getClass"),
576  SourceLocation(), LookupOrdinaryName);
577  if (ObjectGetClass)
578  Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
579  FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
581  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
582  else
583  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
584  }
585  else if (const ObjCIvarRefExpr *OIRE =
586  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
587  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
588 
589  // C++ [conv.lval]p1:
590  // [...] If T is a non-class type, the type of the prvalue is the
591  // cv-unqualified version of T. Otherwise, the type of the
592  // rvalue is T.
593  //
594  // C99 6.3.2.1p2:
595  // If the lvalue has qualified type, the value has the unqualified
596  // version of the type of the lvalue; otherwise, the value has the
597  // type of the lvalue.
598  if (T.hasQualifiers())
599  T = T.getUnqualifiedType();
600 
601  // Under the MS ABI, lock down the inheritance model now.
602  if (T->isMemberPointerType() &&
603  Context.getTargetInfo().getCXXABI().isMicrosoft())
604  (void)isCompleteType(E->getExprLoc(), T);
605 
606  UpdateMarkingForLValueToRValue(E);
607 
608  // Loading a __weak object implicitly retains the value, so we need a cleanup to
609  // balance that.
611  Cleanup.setExprNeedsCleanups(true);
612 
613  ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
614  nullptr, VK_RValue);
615 
616  // C11 6.3.2.1p2:
617  // ... if the lvalue has atomic type, the value has the non-atomic version
618  // of the type of the lvalue ...
619  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
620  T = Atomic->getValueType().getUnqualifiedType();
621  Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
622  nullptr, VK_RValue);
623  }
624 
625  return Res;
626 }
627 
629  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
630  if (Res.isInvalid())
631  return ExprError();
632  Res = DefaultLvalueConversion(Res.get());
633  if (Res.isInvalid())
634  return ExprError();
635  return Res;
636 }
637 
638 /// CallExprUnaryConversions - a special case of an unary conversion
639 /// performed on a function designator of a call expression.
641  QualType Ty = E->getType();
642  ExprResult Res = E;
643  // Only do implicit cast for a function type, but not for a pointer
644  // to function type.
645  if (Ty->isFunctionType()) {
646  Res = ImpCastExprToType(E, Context.getPointerType(Ty),
647  CK_FunctionToPointerDecay).get();
648  if (Res.isInvalid())
649  return ExprError();
650  }
651  Res = DefaultLvalueConversion(Res.get());
652  if (Res.isInvalid())
653  return ExprError();
654  return Res.get();
655 }
656 
657 /// UsualUnaryConversions - Performs various conversions that are common to most
658 /// operators (C99 6.3). The conversions of array and function types are
659 /// sometimes suppressed. For example, the array->pointer conversion doesn't
660 /// apply if the array is an argument to the sizeof or address (&) operators.
661 /// In these instances, this routine should *not* be called.
663  // First, convert to an r-value.
664  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
665  if (Res.isInvalid())
666  return ExprError();
667  E = Res.get();
668 
669  QualType Ty = E->getType();
670  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
671 
672  // Half FP have to be promoted to float unless it is natively supported
673  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
674  return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
675 
676  // Try to perform integral promotions if the object has a theoretically
677  // promotable type.
679  // C99 6.3.1.1p2:
680  //
681  // The following may be used in an expression wherever an int or
682  // unsigned int may be used:
683  // - an object or expression with an integer type whose integer
684  // conversion rank is less than or equal to the rank of int
685  // and unsigned int.
686  // - A bit-field of type _Bool, int, signed int, or unsigned int.
687  //
688  // If an int can represent all values of the original type, the
689  // value is converted to an int; otherwise, it is converted to an
690  // unsigned int. These are called the integer promotions. All
691  // other types are unchanged by the integer promotions.
692 
693  QualType PTy = Context.isPromotableBitField(E);
694  if (!PTy.isNull()) {
695  E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
696  return E;
697  }
698  if (Ty->isPromotableIntegerType()) {
699  QualType PT = Context.getPromotedIntegerType(Ty);
700  E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
701  return E;
702  }
703  }
704  return E;
705 }
706 
707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
708 /// do not have a prototype. Arguments that have type float or __fp16
709 /// are promoted to double. All other argument types are converted by
710 /// UsualUnaryConversions().
712  QualType Ty = E->getType();
713  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
714 
715  ExprResult Res = UsualUnaryConversions(E);
716  if (Res.isInvalid())
717  return ExprError();
718  E = Res.get();
719 
720  // If this is a 'float' or '__fp16' (CVR qualified or typedef)
721  // promote to double.
722  // Note that default argument promotion applies only to float (and
723  // half/fp16); it does not apply to _Float16.
724  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725  if (BTy && (BTy->getKind() == BuiltinType::Half ||
726  BTy->getKind() == BuiltinType::Float)) {
727  if (getLangOpts().OpenCL &&
728  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
729  if (BTy->getKind() == BuiltinType::Half) {
730  E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
731  }
732  } else {
733  E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
734  }
735  }
736 
737  // C++ performs lvalue-to-rvalue conversion as a default argument
738  // promotion, even on class types, but note:
739  // C++11 [conv.lval]p2:
740  // When an lvalue-to-rvalue conversion occurs in an unevaluated
741  // operand or a subexpression thereof the value contained in the
742  // referenced object is not accessed. Otherwise, if the glvalue
743  // has a class type, the conversion copy-initializes a temporary
744  // of type T from the glvalue and the result of the conversion
745  // is a prvalue for the temporary.
746  // FIXME: add some way to gate this entire thing for correctness in
747  // potentially potentially evaluated contexts.
748  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
749  ExprResult Temp = PerformCopyInitialization(
751  E->getExprLoc(), E);
752  if (Temp.isInvalid())
753  return ExprError();
754  E = Temp.get();
755  }
756 
757  return E;
758 }
759 
760 /// Determine the degree of POD-ness for an expression.
761 /// Incomplete types are considered POD, since this check can be performed
762 /// when we're in an unevaluated context.
764  if (Ty->isIncompleteType()) {
765  // C++11 [expr.call]p7:
766  // After these conversions, if the argument does not have arithmetic,
767  // enumeration, pointer, pointer to member, or class type, the program
768  // is ill-formed.
769  //
770  // Since we've already performed array-to-pointer and function-to-pointer
771  // decay, the only such type in C++ is cv void. This also handles
772  // initializer lists as variadic arguments.
773  if (Ty->isVoidType())
774  return VAK_Invalid;
775 
776  if (Ty->isObjCObjectType())
777  return VAK_Invalid;
778  return VAK_Valid;
779  }
780 
782  return VAK_Invalid;
783 
784  if (Ty.isCXX98PODType(Context))
785  return VAK_Valid;
786 
787  // C++11 [expr.call]p7:
788  // Passing a potentially-evaluated argument of class type (Clause 9)
789  // having a non-trivial copy constructor, a non-trivial move constructor,
790  // or a non-trivial destructor, with no corresponding parameter,
791  // is conditionally-supported with implementation-defined semantics.
792  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
793  if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
794  if (!Record->hasNonTrivialCopyConstructor() &&
795  !Record->hasNonTrivialMoveConstructor() &&
796  !Record->hasNonTrivialDestructor())
797  return VAK_ValidInCXX11;
798 
799  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
800  return VAK_Valid;
801 
802  if (Ty->isObjCObjectType())
803  return VAK_Invalid;
804 
805  if (getLangOpts().MSVCCompat)
806  return VAK_MSVCUndefined;
807 
808  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
809  // permitted to reject them. We should consider doing so.
810  return VAK_Undefined;
811 }
812 
814  // Don't allow one to pass an Objective-C interface to a vararg.
815  const QualType &Ty = E->getType();
816  VarArgKind VAK = isValidVarArgType(Ty);
817 
818  // Complain about passing non-POD types through varargs.
819  switch (VAK) {
820  case VAK_ValidInCXX11:
821  DiagRuntimeBehavior(
822  E->getLocStart(), nullptr,
823  PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
824  << Ty << CT);
825  LLVM_FALLTHROUGH;
826  case VAK_Valid:
827  if (Ty->isRecordType()) {
828  // This is unlikely to be what the user intended. If the class has a
829  // 'c_str' member function, the user probably meant to call that.
830  DiagRuntimeBehavior(E->getLocStart(), nullptr,
831  PDiag(diag::warn_pass_class_arg_to_vararg)
832  << Ty << CT << hasCStrMethod(E) << ".c_str()");
833  }
834  break;
835 
836  case VAK_Undefined:
837  case VAK_MSVCUndefined:
838  DiagRuntimeBehavior(
839  E->getLocStart(), nullptr,
840  PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
841  << getLangOpts().CPlusPlus11 << Ty << CT);
842  break;
843 
844  case VAK_Invalid:
846  Diag(E->getLocStart(),
847  diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
848  else if (Ty->isObjCObjectType())
849  DiagRuntimeBehavior(
850  E->getLocStart(), nullptr,
851  PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
852  << Ty << CT);
853  else
854  Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
855  << isa<InitListExpr>(E) << Ty << CT;
856  break;
857  }
858 }
859 
860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
861 /// will create a trap if the resulting type is not a POD type.
863  FunctionDecl *FDecl) {
864  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
865  // Strip the unbridged-cast placeholder expression off, if applicable.
866  if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
867  (CT == VariadicMethod ||
868  (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
869  E = stripARCUnbridgedCast(E);
870 
871  // Otherwise, do normal placeholder checking.
872  } else {
873  ExprResult ExprRes = CheckPlaceholderExpr(E);
874  if (ExprRes.isInvalid())
875  return ExprError();
876  E = ExprRes.get();
877  }
878  }
879 
880  ExprResult ExprRes = DefaultArgumentPromotion(E);
881  if (ExprRes.isInvalid())
882  return ExprError();
883  E = ExprRes.get();
884 
885  // Diagnostics regarding non-POD argument types are
886  // emitted along with format string checking in Sema::CheckFunctionCall().
887  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
888  // Turn this into a trap.
889  CXXScopeSpec SS;
890  SourceLocation TemplateKWLoc;
891  UnqualifiedId Name;
892  Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
893  E->getLocStart());
894  ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
895  Name, true, false);
896  if (TrapFn.isInvalid())
897  return ExprError();
898 
899  ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
900  E->getLocStart(), None,
901  E->getLocEnd());
902  if (Call.isInvalid())
903  return ExprError();
904 
905  ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
906  Call.get(), E);
907  if (Comma.isInvalid())
908  return ExprError();
909  return Comma.get();
910  }
911 
912  if (!getLangOpts().CPlusPlus &&
913  RequireCompleteType(E->getExprLoc(), E->getType(),
914  diag::err_call_incomplete_argument))
915  return ExprError();
916 
917  return E;
918 }
919 
920 /// Converts an integer to complex float type. Helper function of
921 /// UsualArithmeticConversions()
922 ///
923 /// \return false if the integer expression is an integer type and is
924 /// successfully converted to the complex type.
926  ExprResult &ComplexExpr,
927  QualType IntTy,
928  QualType ComplexTy,
929  bool SkipCast) {
930  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
931  if (SkipCast) return false;
932  if (IntTy->isIntegerType()) {
933  QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
934  IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
935  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
936  CK_FloatingRealToComplex);
937  } else {
938  assert(IntTy->isComplexIntegerType());
939  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
940  CK_IntegralComplexToFloatingComplex);
941  }
942  return false;
943 }
944 
945 /// Handle arithmetic conversion with complex types. Helper function of
946 /// UsualArithmeticConversions()
948  ExprResult &RHS, QualType LHSType,
949  QualType RHSType,
950  bool IsCompAssign) {
951  // if we have an integer operand, the result is the complex type.
952  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
953  /*skipCast*/false))
954  return LHSType;
955  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
956  /*skipCast*/IsCompAssign))
957  return RHSType;
958 
959  // This handles complex/complex, complex/float, or float/complex.
960  // When both operands are complex, the shorter operand is converted to the
961  // type of the longer, and that is the type of the result. This corresponds
962  // to what is done when combining two real floating-point operands.
963  // The fun begins when size promotion occur across type domains.
964  // From H&S 6.3.4: When one operand is complex and the other is a real
965  // floating-point type, the less precise type is converted, within it's
966  // real or complex domain, to the precision of the other type. For example,
967  // when combining a "long double" with a "double _Complex", the
968  // "double _Complex" is promoted to "long double _Complex".
969 
970  // Compute the rank of the two types, regardless of whether they are complex.
971  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
972 
973  auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
974  auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
975  QualType LHSElementType =
976  LHSComplexType ? LHSComplexType->getElementType() : LHSType;
977  QualType RHSElementType =
978  RHSComplexType ? RHSComplexType->getElementType() : RHSType;
979 
980  QualType ResultType = S.Context.getComplexType(LHSElementType);
981  if (Order < 0) {
982  // Promote the precision of the LHS if not an assignment.
983  ResultType = S.Context.getComplexType(RHSElementType);
984  if (!IsCompAssign) {
985  if (LHSComplexType)
986  LHS =
987  S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
988  else
989  LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
990  }
991  } else if (Order > 0) {
992  // Promote the precision of the RHS.
993  if (RHSComplexType)
994  RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
995  else
996  RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
997  }
998  return ResultType;
999 }
1000 
1001 /// Handle arithmetic conversion from integer to float. Helper function
1002 /// of UsualArithmeticConversions()
1004  ExprResult &IntExpr,
1005  QualType FloatTy, QualType IntTy,
1006  bool ConvertFloat, bool ConvertInt) {
1007  if (IntTy->isIntegerType()) {
1008  if (ConvertInt)
1009  // Convert intExpr to the lhs floating point type.
1010  IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1011  CK_IntegralToFloating);
1012  return FloatTy;
1013  }
1014 
1015  // Convert both sides to the appropriate complex float.
1016  assert(IntTy->isComplexIntegerType());
1017  QualType result = S.Context.getComplexType(FloatTy);
1018 
1019  // _Complex int -> _Complex float
1020  if (ConvertInt)
1021  IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1022  CK_IntegralComplexToFloatingComplex);
1023 
1024  // float -> _Complex float
1025  if (ConvertFloat)
1026  FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1027  CK_FloatingRealToComplex);
1028 
1029  return result;
1030 }
1031 
1032 /// Handle arithmethic conversion with floating point types. Helper
1033 /// function of UsualArithmeticConversions()
1035  ExprResult &RHS, QualType LHSType,
1036  QualType RHSType, bool IsCompAssign) {
1037  bool LHSFloat = LHSType->isRealFloatingType();
1038  bool RHSFloat = RHSType->isRealFloatingType();
1039 
1040  // If we have two real floating types, convert the smaller operand
1041  // to the bigger result.
1042  if (LHSFloat && RHSFloat) {
1043  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1044  if (order > 0) {
1045  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1046  return LHSType;
1047  }
1048 
1049  assert(order < 0 && "illegal float comparison");
1050  if (!IsCompAssign)
1051  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1052  return RHSType;
1053  }
1054 
1055  if (LHSFloat) {
1056  // Half FP has to be promoted to float unless it is natively supported
1057  if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1058  LHSType = S.Context.FloatTy;
1059 
1060  return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1061  /*convertFloat=*/!IsCompAssign,
1062  /*convertInt=*/ true);
1063  }
1064  assert(RHSFloat);
1065  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1066  /*convertInt=*/ true,
1067  /*convertFloat=*/!IsCompAssign);
1068 }
1069 
1070 /// Diagnose attempts to convert between __float128 and long double if
1071 /// there is no support for such conversion. Helper function of
1072 /// UsualArithmeticConversions().
1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1074  QualType RHSType) {
1075  /* No issue converting if at least one of the types is not a floating point
1076  type or the two types have the same rank.
1077  */
1078  if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1079  S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1080  return false;
1081 
1082  assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1083  "The remaining types must be floating point types.");
1084 
1085  auto *LHSComplex = LHSType->getAs<ComplexType>();
1086  auto *RHSComplex = RHSType->getAs<ComplexType>();
1087 
1088  QualType LHSElemType = LHSComplex ?
1089  LHSComplex->getElementType() : LHSType;
1090  QualType RHSElemType = RHSComplex ?
1091  RHSComplex->getElementType() : RHSType;
1092 
1093  // No issue if the two types have the same representation
1094  if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1095  &S.Context.getFloatTypeSemantics(RHSElemType))
1096  return false;
1097 
1098  bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1099  RHSElemType == S.Context.LongDoubleTy);
1100  Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1101  RHSElemType == S.Context.Float128Ty);
1102 
1103  // We've handled the situation where __float128 and long double have the same
1104  // representation. We allow all conversions for all possible long double types
1105  // except PPC's double double.
1106  return Float128AndLongDouble &&
1108  &llvm::APFloat::PPCDoubleDouble());
1109 }
1110 
1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1112 
1113 namespace {
1114 /// These helper callbacks are placed in an anonymous namespace to
1115 /// permit their use as function template parameters.
1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1117  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1118 }
1119 
1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1121  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1122  CK_IntegralComplexCast);
1123 }
1124 }
1125 
1126 /// Handle integer arithmetic conversions. Helper function of
1127 /// UsualArithmeticConversions()
1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1130  ExprResult &RHS, QualType LHSType,
1131  QualType RHSType, bool IsCompAssign) {
1132  // The rules for this case are in C99 6.3.1.8
1133  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1134  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1135  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1136  if (LHSSigned == RHSSigned) {
1137  // Same signedness; use the higher-ranked type
1138  if (order >= 0) {
1139  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1140  return LHSType;
1141  } else if (!IsCompAssign)
1142  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1143  return RHSType;
1144  } else if (order != (LHSSigned ? 1 : -1)) {
1145  // The unsigned type has greater than or equal rank to the
1146  // signed type, so use the unsigned type
1147  if (RHSSigned) {
1148  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1149  return LHSType;
1150  } else if (!IsCompAssign)
1151  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1152  return RHSType;
1153  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1154  // The two types are different widths; if we are here, that
1155  // means the signed type is larger than the unsigned type, so
1156  // use the signed type.
1157  if (LHSSigned) {
1158  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159  return LHSType;
1160  } else if (!IsCompAssign)
1161  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162  return RHSType;
1163  } else {
1164  // The signed type is higher-ranked than the unsigned type,
1165  // but isn't actually any bigger (like unsigned int and long
1166  // on most 32-bit systems). Use the unsigned type corresponding
1167  // to the signed type.
1168  QualType result =
1169  S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1170  RHS = (*doRHSCast)(S, RHS.get(), result);
1171  if (!IsCompAssign)
1172  LHS = (*doLHSCast)(S, LHS.get(), result);
1173  return result;
1174  }
1175 }
1176 
1177 /// Handle conversions with GCC complex int extension. Helper function
1178 /// of UsualArithmeticConversions()
1180  ExprResult &RHS, QualType LHSType,
1181  QualType RHSType,
1182  bool IsCompAssign) {
1183  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1184  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1185 
1186  if (LHSComplexInt && RHSComplexInt) {
1187  QualType LHSEltType = LHSComplexInt->getElementType();
1188  QualType RHSEltType = RHSComplexInt->getElementType();
1189  QualType ScalarType =
1190  handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1191  (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1192 
1193  return S.Context.getComplexType(ScalarType);
1194  }
1195 
1196  if (LHSComplexInt) {
1197  QualType LHSEltType = LHSComplexInt->getElementType();
1198  QualType ScalarType =
1199  handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1200  (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1201  QualType ComplexType = S.Context.getComplexType(ScalarType);
1202  RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1203  CK_IntegralRealToComplex);
1204 
1205  return ComplexType;
1206  }
1207 
1208  assert(RHSComplexInt);
1209 
1210  QualType RHSEltType = RHSComplexInt->getElementType();
1211  QualType ScalarType =
1212  handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1213  (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1214  QualType ComplexType = S.Context.getComplexType(ScalarType);
1215 
1216  if (!IsCompAssign)
1217  LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1218  CK_IntegralRealToComplex);
1219  return ComplexType;
1220 }
1221 
1222 /// UsualArithmeticConversions - Performs various conversions that are common to
1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1224 /// routine returns the first non-arithmetic type found. The client is
1225 /// responsible for emitting appropriate error diagnostics.
1227  bool IsCompAssign) {
1228  if (!IsCompAssign) {
1229  LHS = UsualUnaryConversions(LHS.get());
1230  if (LHS.isInvalid())
1231  return QualType();
1232  }
1233 
1234  RHS = UsualUnaryConversions(RHS.get());
1235  if (RHS.isInvalid())
1236  return QualType();
1237 
1238  // For conversion purposes, we ignore any qualifiers.
1239  // For example, "const float" and "float" are equivalent.
1240  QualType LHSType =
1241  Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1242  QualType RHSType =
1243  Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1244 
1245  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1246  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1247  LHSType = AtomicLHS->getValueType();
1248 
1249  // If both types are identical, no conversion is needed.
1250  if (LHSType == RHSType)
1251  return LHSType;
1252 
1253  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1254  // The caller can deal with this (e.g. pointer + int).
1255  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1256  return QualType();
1257 
1258  // Apply unary and bitfield promotions to the LHS's type.
1259  QualType LHSUnpromotedType = LHSType;
1260  if (LHSType->isPromotableIntegerType())
1261  LHSType = Context.getPromotedIntegerType(LHSType);
1262  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1263  if (!LHSBitfieldPromoteTy.isNull())
1264  LHSType = LHSBitfieldPromoteTy;
1265  if (LHSType != LHSUnpromotedType && !IsCompAssign)
1266  LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1267 
1268  // If both types are identical, no conversion is needed.
1269  if (LHSType == RHSType)
1270  return LHSType;
1271 
1272  // At this point, we have two different arithmetic types.
1273 
1274  // Diagnose attempts to convert between __float128 and long double where
1275  // such conversions currently can't be handled.
1276  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1277  return QualType();
1278 
1279  // Handle complex types first (C99 6.3.1.8p1).
1280  if (LHSType->isComplexType() || RHSType->isComplexType())
1281  return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1282  IsCompAssign);
1283 
1284  // Now handle "real" floating types (i.e. float, double, long double).
1285  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1286  return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1287  IsCompAssign);
1288 
1289  // Handle GCC complex int extension.
1290  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1291  return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1292  IsCompAssign);
1293 
1294  // Finally, we have two differing integer types.
1295  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1296  (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1297 }
1298 
1299 
1300 //===----------------------------------------------------------------------===//
1301 // Semantic Analysis for various Expression Types
1302 //===----------------------------------------------------------------------===//
1303 
1304 
1305 ExprResult
1307  SourceLocation DefaultLoc,
1308  SourceLocation RParenLoc,
1309  Expr *ControllingExpr,
1310  ArrayRef<ParsedType> ArgTypes,
1311  ArrayRef<Expr *> ArgExprs) {
1312  unsigned NumAssocs = ArgTypes.size();
1313  assert(NumAssocs == ArgExprs.size());
1314 
1315  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1316  for (unsigned i = 0; i < NumAssocs; ++i) {
1317  if (ArgTypes[i])
1318  (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1319  else
1320  Types[i] = nullptr;
1321  }
1322 
1323  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1324  ControllingExpr,
1325  llvm::makeArrayRef(Types, NumAssocs),
1326  ArgExprs);
1327  delete [] Types;
1328  return ER;
1329 }
1330 
1331 ExprResult
1333  SourceLocation DefaultLoc,
1334  SourceLocation RParenLoc,
1335  Expr *ControllingExpr,
1337  ArrayRef<Expr *> Exprs) {
1338  unsigned NumAssocs = Types.size();
1339  assert(NumAssocs == Exprs.size());
1340 
1341  // Decay and strip qualifiers for the controlling expression type, and handle
1342  // placeholder type replacement. See committee discussion from WG14 DR423.
1343  {
1346  ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1347  if (R.isInvalid())
1348  return ExprError();
1349  ControllingExpr = R.get();
1350  }
1351 
1352  // The controlling expression is an unevaluated operand, so side effects are
1353  // likely unintended.
1354  if (!inTemplateInstantiation() &&
1355  ControllingExpr->HasSideEffects(Context, false))
1356  Diag(ControllingExpr->getExprLoc(),
1357  diag::warn_side_effects_unevaluated_context);
1358 
1359  bool TypeErrorFound = false,
1360  IsResultDependent = ControllingExpr->isTypeDependent(),
1361  ContainsUnexpandedParameterPack
1362  = ControllingExpr->containsUnexpandedParameterPack();
1363 
1364  for (unsigned i = 0; i < NumAssocs; ++i) {
1365  if (Exprs[i]->containsUnexpandedParameterPack())
1366  ContainsUnexpandedParameterPack = true;
1367 
1368  if (Types[i]) {
1369  if (Types[i]->getType()->containsUnexpandedParameterPack())
1370  ContainsUnexpandedParameterPack = true;
1371 
1372  if (Types[i]->getType()->isDependentType()) {
1373  IsResultDependent = true;
1374  } else {
1375  // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1376  // complete object type other than a variably modified type."
1377  unsigned D = 0;
1378  if (Types[i]->getType()->isIncompleteType())
1379  D = diag::err_assoc_type_incomplete;
1380  else if (!Types[i]->getType()->isObjectType())
1381  D = diag::err_assoc_type_nonobject;
1382  else if (Types[i]->getType()->isVariablyModifiedType())
1383  D = diag::err_assoc_type_variably_modified;
1384 
1385  if (D != 0) {
1386  Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1387  << Types[i]->getTypeLoc().getSourceRange()
1388  << Types[i]->getType();
1389  TypeErrorFound = true;
1390  }
1391 
1392  // C11 6.5.1.1p2 "No two generic associations in the same generic
1393  // selection shall specify compatible types."
1394  for (unsigned j = i+1; j < NumAssocs; ++j)
1395  if (Types[j] && !Types[j]->getType()->isDependentType() &&
1396  Context.typesAreCompatible(Types[i]->getType(),
1397  Types[j]->getType())) {
1398  Diag(Types[j]->getTypeLoc().getBeginLoc(),
1399  diag::err_assoc_compatible_types)
1400  << Types[j]->getTypeLoc().getSourceRange()
1401  << Types[j]->getType()
1402  << Types[i]->getType();
1403  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1404  diag::note_compat_assoc)
1405  << Types[i]->getTypeLoc().getSourceRange()
1406  << Types[i]->getType();
1407  TypeErrorFound = true;
1408  }
1409  }
1410  }
1411  }
1412  if (TypeErrorFound)
1413  return ExprError();
1414 
1415  // If we determined that the generic selection is result-dependent, don't
1416  // try to compute the result expression.
1417  if (IsResultDependent)
1418  return new (Context) GenericSelectionExpr(
1419  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1420  ContainsUnexpandedParameterPack);
1421 
1422  SmallVector<unsigned, 1> CompatIndices;
1423  unsigned DefaultIndex = -1U;
1424  for (unsigned i = 0; i < NumAssocs; ++i) {
1425  if (!Types[i])
1426  DefaultIndex = i;
1427  else if (Context.typesAreCompatible(ControllingExpr->getType(),
1428  Types[i]->getType()))
1429  CompatIndices.push_back(i);
1430  }
1431 
1432  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1433  // type compatible with at most one of the types named in its generic
1434  // association list."
1435  if (CompatIndices.size() > 1) {
1436  // We strip parens here because the controlling expression is typically
1437  // parenthesized in macro definitions.
1438  ControllingExpr = ControllingExpr->IgnoreParens();
1439  Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1440  << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1441  << (unsigned) CompatIndices.size();
1442  for (unsigned I : CompatIndices) {
1443  Diag(Types[I]->getTypeLoc().getBeginLoc(),
1444  diag::note_compat_assoc)
1445  << Types[I]->getTypeLoc().getSourceRange()
1446  << Types[I]->getType();
1447  }
1448  return ExprError();
1449  }
1450 
1451  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1452  // its controlling expression shall have type compatible with exactly one of
1453  // the types named in its generic association list."
1454  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1455  // We strip parens here because the controlling expression is typically
1456  // parenthesized in macro definitions.
1457  ControllingExpr = ControllingExpr->IgnoreParens();
1458  Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1459  << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1460  return ExprError();
1461  }
1462 
1463  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1464  // type name that is compatible with the type of the controlling expression,
1465  // then the result expression of the generic selection is the expression
1466  // in that generic association. Otherwise, the result expression of the
1467  // generic selection is the expression in the default generic association."
1468  unsigned ResultIndex =
1469  CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1470 
1471  return new (Context) GenericSelectionExpr(
1472  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1473  ContainsUnexpandedParameterPack, ResultIndex);
1474 }
1475 
1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1477 /// location of the token and the offset of the ud-suffix within it.
1479  unsigned Offset) {
1480  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1481  S.getLangOpts());
1482 }
1483 
1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1487  IdentifierInfo *UDSuffix,
1488  SourceLocation UDSuffixLoc,
1489  ArrayRef<Expr*> Args,
1490  SourceLocation LitEndLoc) {
1491  assert(Args.size() <= 2 && "too many arguments for literal operator");
1492 
1493  QualType ArgTy[2];
1494  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1495  ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1496  if (ArgTy[ArgIdx]->isArrayType())
1497  ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1498  }
1499 
1500  DeclarationName OpName =
1502  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1503  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1504 
1505  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1506  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1507  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1508  /*AllowStringTemplate*/ false,
1509  /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1510  return ExprError();
1511 
1512  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1513 }
1514 
1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1516 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1518 /// multiple tokens. However, the common case is that StringToks points to one
1519 /// string.
1520 ///
1521 ExprResult
1523  assert(!StringToks.empty() && "Must have at least one string!");
1524 
1525  StringLiteralParser Literal(StringToks, PP);
1526  if (Literal.hadError)
1527  return ExprError();
1528 
1529  SmallVector<SourceLocation, 4> StringTokLocs;
1530  for (const Token &Tok : StringToks)
1531  StringTokLocs.push_back(Tok.getLocation());
1532 
1533  QualType CharTy = Context.CharTy;
1535  if (Literal.isWide()) {
1536  CharTy = Context.getWideCharType();
1537  Kind = StringLiteral::Wide;
1538  } else if (Literal.isUTF8()) {
1539  if (getLangOpts().Char8)
1540  CharTy = Context.Char8Ty;
1541  Kind = StringLiteral::UTF8;
1542  } else if (Literal.isUTF16()) {
1543  CharTy = Context.Char16Ty;
1544  Kind = StringLiteral::UTF16;
1545  } else if (Literal.isUTF32()) {
1546  CharTy = Context.Char32Ty;
1547  Kind = StringLiteral::UTF32;
1548  } else if (Literal.isPascal()) {
1549  CharTy = Context.UnsignedCharTy;
1550  }
1551 
1552  QualType CharTyConst = CharTy;
1553  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1554  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1555  CharTyConst.addConst();
1556 
1557  CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1558 
1559  // Get an array type for the string, according to C99 6.4.5. This includes
1560  // the nul terminator character as well as the string length for pascal
1561  // strings.
1562  QualType StrTy = Context.getConstantArrayType(
1563  CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1564  ArrayType::Normal, 0);
1565 
1566  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1567  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1568  Kind, Literal.Pascal, StrTy,
1569  &StringTokLocs[0],
1570  StringTokLocs.size());
1571  if (Literal.getUDSuffix().empty())
1572  return Lit;
1573 
1574  // We're building a user-defined literal.
1575  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1576  SourceLocation UDSuffixLoc =
1577  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1578  Literal.getUDSuffixOffset());
1579 
1580  // Make sure we're allowed user-defined literals here.
1581  if (!UDLScope)
1582  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1583 
1584  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1585  // operator "" X (str, len)
1586  QualType SizeType = Context.getSizeType();
1587 
1588  DeclarationName OpName =
1589  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593  QualType ArgTy[] = {
1594  Context.getArrayDecayedType(StrTy), SizeType
1595  };
1596 
1597  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1598  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1599  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1600  /*AllowStringTemplate*/ true,
1601  /*DiagnoseMissing*/ true)) {
1602 
1603  case LOLR_Cooked: {
1604  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1605  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1606  StringTokLocs[0]);
1607  Expr *Args[] = { Lit, LenArg };
1608 
1609  return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1610  }
1611 
1612  case LOLR_StringTemplate: {
1613  TemplateArgumentListInfo ExplicitArgs;
1614 
1615  unsigned CharBits = Context.getIntWidth(CharTy);
1616  bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1617  llvm::APSInt Value(CharBits, CharIsUnsigned);
1618 
1619  TemplateArgument TypeArg(CharTy);
1620  TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1621  ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1622 
1623  for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1624  Value = Lit->getCodeUnit(I);
1625  TemplateArgument Arg(Context, Value, CharTy);
1626  TemplateArgumentLocInfo ArgInfo;
1627  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1628  }
1629  return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1630  &ExplicitArgs);
1631  }
1632  case LOLR_Raw:
1633  case LOLR_Template:
1634  case LOLR_ErrorNoDiagnostic:
1635  llvm_unreachable("unexpected literal operator lookup result");
1636  case LOLR_Error:
1637  return ExprError();
1638  }
1639  llvm_unreachable("unexpected literal operator lookup result");
1640 }
1641 
1642 ExprResult
1644  SourceLocation Loc,
1645  const CXXScopeSpec *SS) {
1646  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1647  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1648 }
1649 
1650 /// BuildDeclRefExpr - Build an expression that references a
1651 /// declaration that does not require a closure capture.
1652 ExprResult
1654  const DeclarationNameInfo &NameInfo,
1655  const CXXScopeSpec *SS, NamedDecl *FoundD,
1656  const TemplateArgumentListInfo *TemplateArgs) {
1657  bool RefersToCapturedVariable =
1658  isa<VarDecl>(D) &&
1659  NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1660 
1661  DeclRefExpr *E;
1662  if (isa<VarTemplateSpecializationDecl>(D)) {
1664  cast<VarTemplateSpecializationDecl>(D);
1665 
1666  E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1668  VarSpec->getTemplateKeywordLoc(), D,
1669  RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1670  FoundD, TemplateArgs);
1671  } else {
1672  assert(!TemplateArgs && "No template arguments for non-variable"
1673  " template specialization references");
1674  E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1676  SourceLocation(), D, RefersToCapturedVariable,
1677  NameInfo, Ty, VK, FoundD);
1678  }
1679 
1680  MarkDeclRefReferenced(E);
1681 
1682  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1683  Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1684  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1685  getCurFunction()->recordUseOfWeak(E);
1686 
1687  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1689  FD = IFD->getAnonField();
1690  if (FD) {
1691  UnusedPrivateFields.remove(FD);
1692  // Just in case we're building an illegal pointer-to-member.
1693  if (FD->isBitField())
1694  E->setObjectKind(OK_BitField);
1695  }
1696 
1697  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1698  // designates a bit-field.
1699  if (auto *BD = dyn_cast<BindingDecl>(D))
1700  if (auto *BE = BD->getBinding())
1701  E->setObjectKind(BE->getObjectKind());
1702 
1703  return E;
1704 }
1705 
1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1707 /// possibly a list of template arguments.
1708 ///
1709 /// If this produces template arguments, it is permitted to call
1710 /// DecomposeTemplateName.
1711 ///
1712 /// This actually loses a lot of source location information for
1713 /// non-standard name kinds; we should consider preserving that in
1714 /// some way.
1715 void
1717  TemplateArgumentListInfo &Buffer,
1718  DeclarationNameInfo &NameInfo,
1719  const TemplateArgumentListInfo *&TemplateArgs) {
1721  Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1722  Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1723 
1724  ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1725  Id.TemplateId->NumArgs);
1726  translateTemplateArguments(TemplateArgsPtr, Buffer);
1727 
1728  TemplateName TName = Id.TemplateId->Template.get();
1729  SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1730  NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1731  TemplateArgs = &Buffer;
1732  } else {
1733  NameInfo = GetNameFromUnqualifiedId(Id);
1734  TemplateArgs = nullptr;
1735  }
1736 }
1737 
1739  const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1740  DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1741  unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1742  DeclContext *Ctx =
1743  SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1744  if (!TC) {
1745  // Emit a special diagnostic for failed member lookups.
1746  // FIXME: computing the declaration context might fail here (?)
1747  if (Ctx)
1748  SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1749  << SS.getRange();
1750  else
1751  SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1752  return;
1753  }
1754 
1755  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1756  bool DroppedSpecifier =
1757  TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1758  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1759  ? diag::note_implicit_param_decl
1760  : diag::note_previous_decl;
1761  if (!Ctx)
1762  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1763  SemaRef.PDiag(NoteID));
1764  else
1765  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1766  << Typo << Ctx << DroppedSpecifier
1767  << SS.getRange(),
1768  SemaRef.PDiag(NoteID));
1769 }
1770 
1771 /// Diagnose an empty lookup.
1772 ///
1773 /// \return false if new lookup candidates were found
1774 bool
1776  std::unique_ptr<CorrectionCandidateCallback> CCC,
1777  TemplateArgumentListInfo *ExplicitTemplateArgs,
1778  ArrayRef<Expr *> Args, TypoExpr **Out) {
1779  DeclarationName Name = R.getLookupName();
1780 
1781  unsigned diagnostic = diag::err_undeclared_var_use;
1782  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1786  diagnostic = diag::err_undeclared_use;
1787  diagnostic_suggest = diag::err_undeclared_use_suggest;
1788  }
1789 
1790  // If the original lookup was an unqualified lookup, fake an
1791  // unqualified lookup. This is useful when (for example) the
1792  // original lookup would not have found something because it was a
1793  // dependent name.
1794  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1795  while (DC) {
1796  if (isa<CXXRecordDecl>(DC)) {
1797  LookupQualifiedName(R, DC);
1798 
1799  if (!R.empty()) {
1800  // Don't give errors about ambiguities in this lookup.
1801  R.suppressDiagnostics();
1802 
1803  // During a default argument instantiation the CurContext points
1804  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1805  // function parameter list, hence add an explicit check.
1806  bool isDefaultArgument =
1807  !CodeSynthesisContexts.empty() &&
1808  CodeSynthesisContexts.back().Kind ==
1809  CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1810  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1811  bool isInstance = CurMethod &&
1812  CurMethod->isInstance() &&
1813  DC == CurMethod->getParent() && !isDefaultArgument;
1814 
1815  // Give a code modification hint to insert 'this->'.
1816  // TODO: fixit for inserting 'Base<T>::' in the other cases.
1817  // Actually quite difficult!
1818  if (getLangOpts().MSVCCompat)
1819  diagnostic = diag::ext_found_via_dependent_bases_lookup;
1820  if (isInstance) {
1821  Diag(R.getNameLoc(), diagnostic) << Name
1822  << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1823  CheckCXXThisCapture(R.getNameLoc());
1824  } else {
1825  Diag(R.getNameLoc(), diagnostic) << Name;
1826  }
1827 
1828  // Do we really want to note all of these?
1829  for (NamedDecl *D : R)
1830  Diag(D->getLocation(), diag::note_dependent_var_use);
1831 
1832  // Return true if we are inside a default argument instantiation
1833  // and the found name refers to an instance member function, otherwise
1834  // the function calling DiagnoseEmptyLookup will try to create an
1835  // implicit member call and this is wrong for default argument.
1836  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1837  Diag(R.getNameLoc(), diag::err_member_call_without_object);
1838  return true;
1839  }
1840 
1841  // Tell the callee to try to recover.
1842  return false;
1843  }
1844 
1845  R.clear();
1846  }
1847 
1848  // In Microsoft mode, if we are performing lookup from within a friend
1849  // function definition declared at class scope then we must set
1850  // DC to the lexical parent to be able to search into the parent
1851  // class.
1852  if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1853  cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1854  DC->getLexicalParent()->isRecord())
1855  DC = DC->getLexicalParent();
1856  else
1857  DC = DC->getParent();
1858  }
1859 
1860  // We didn't find anything, so try to correct for a typo.
1861  TypoCorrection Corrected;
1862  if (S && Out) {
1863  SourceLocation TypoLoc = R.getNameLoc();
1864  assert(!ExplicitTemplateArgs &&
1865  "Diagnosing an empty lookup with explicit template args!");
1866  *Out = CorrectTypoDelayed(
1867  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1868  [=](const TypoCorrection &TC) {
1869  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1870  diagnostic, diagnostic_suggest);
1871  },
1872  nullptr, CTK_ErrorRecovery);
1873  if (*Out)
1874  return true;
1875  } else if (S && (Corrected =
1876  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1877  &SS, std::move(CCC), CTK_ErrorRecovery))) {
1878  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1879  bool DroppedSpecifier =
1880  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1881  R.setLookupName(Corrected.getCorrection());
1882 
1883  bool AcceptableWithRecovery = false;
1884  bool AcceptableWithoutRecovery = false;
1885  NamedDecl *ND = Corrected.getFoundDecl();
1886  if (ND) {
1887  if (Corrected.isOverloaded()) {
1891  for (NamedDecl *CD : Corrected) {
1892  if (FunctionTemplateDecl *FTD =
1893  dyn_cast<FunctionTemplateDecl>(CD))
1894  AddTemplateOverloadCandidate(
1895  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1896  Args, OCS);
1897  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1898  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1899  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1900  Args, OCS);
1901  }
1902  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1903  case OR_Success:
1904  ND = Best->FoundDecl;
1905  Corrected.setCorrectionDecl(ND);
1906  break;
1907  default:
1908  // FIXME: Arbitrarily pick the first declaration for the note.
1909  Corrected.setCorrectionDecl(ND);
1910  break;
1911  }
1912  }
1913  R.addDecl(ND);
1914  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1915  CXXRecordDecl *Record = nullptr;
1916  if (Corrected.getCorrectionSpecifier()) {
1917  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1918  Record = Ty->getAsCXXRecordDecl();
1919  }
1920  if (!Record)
1921  Record = cast<CXXRecordDecl>(
1922  ND->getDeclContext()->getRedeclContext());
1923  R.setNamingClass(Record);
1924  }
1925 
1926  auto *UnderlyingND = ND->getUnderlyingDecl();
1927  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1928  isa<FunctionTemplateDecl>(UnderlyingND);
1929  // FIXME: If we ended up with a typo for a type name or
1930  // Objective-C class name, we're in trouble because the parser
1931  // is in the wrong place to recover. Suggest the typo
1932  // correction, but don't make it a fix-it since we're not going
1933  // to recover well anyway.
1934  AcceptableWithoutRecovery =
1935  isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1936  } else {
1937  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1938  // because we aren't able to recover.
1939  AcceptableWithoutRecovery = true;
1940  }
1941 
1942  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1943  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1944  ? diag::note_implicit_param_decl
1945  : diag::note_previous_decl;
1946  if (SS.isEmpty())
1947  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1948  PDiag(NoteID), AcceptableWithRecovery);
1949  else
1950  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1951  << Name << computeDeclContext(SS, false)
1952  << DroppedSpecifier << SS.getRange(),
1953  PDiag(NoteID), AcceptableWithRecovery);
1954 
1955  // Tell the callee whether to try to recover.
1956  return !AcceptableWithRecovery;
1957  }
1958  }
1959  R.clear();
1960 
1961  // Emit a special diagnostic for failed member lookups.
1962  // FIXME: computing the declaration context might fail here (?)
1963  if (!SS.isEmpty()) {
1964  Diag(R.getNameLoc(), diag::err_no_member)
1965  << Name << computeDeclContext(SS, false)
1966  << SS.getRange();
1967  return true;
1968  }
1969 
1970  // Give up, we can't recover.
1971  Diag(R.getNameLoc(), diagnostic) << Name;
1972  return true;
1973 }
1974 
1975 /// In Microsoft mode, if we are inside a template class whose parent class has
1976 /// dependent base classes, and we can't resolve an unqualified identifier, then
1977 /// assume the identifier is a member of a dependent base class. We can only
1978 /// recover successfully in static methods, instance methods, and other contexts
1979 /// where 'this' is available. This doesn't precisely match MSVC's
1980 /// instantiation model, but it's close enough.
1981 static Expr *
1983  DeclarationNameInfo &NameInfo,
1984  SourceLocation TemplateKWLoc,
1985  const TemplateArgumentListInfo *TemplateArgs) {
1986  // Only try to recover from lookup into dependent bases in static methods or
1987  // contexts where 'this' is available.
1988  QualType ThisType = S.getCurrentThisType();
1989  const CXXRecordDecl *RD = nullptr;
1990  if (!ThisType.isNull())
1991  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1992  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1993  RD = MD->getParent();
1994  if (!RD || !RD->hasAnyDependentBases())
1995  return nullptr;
1996 
1997  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
1998  // is available, suggest inserting 'this->' as a fixit.
1999  SourceLocation Loc = NameInfo.getLoc();
2000  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2001  DB << NameInfo.getName() << RD;
2002 
2003  if (!ThisType.isNull()) {
2004  DB << FixItHint::CreateInsertion(Loc, "this->");
2006  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2007  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2008  /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2009  }
2010 
2011  // Synthesize a fake NNS that points to the derived class. This will
2012  // perform name lookup during template instantiation.
2013  CXXScopeSpec SS;
2014  auto *NNS =
2015  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2016  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2018  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2019  TemplateArgs);
2020 }
2021 
2022 ExprResult
2024  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2025  bool HasTrailingLParen, bool IsAddressOfOperand,
2026  std::unique_ptr<CorrectionCandidateCallback> CCC,
2027  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2028  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2029  "cannot be direct & operand and have a trailing lparen");
2030  if (SS.isInvalid())
2031  return ExprError();
2032 
2033  TemplateArgumentListInfo TemplateArgsBuffer;
2034 
2035  // Decompose the UnqualifiedId into the following data.
2036  DeclarationNameInfo NameInfo;
2037  const TemplateArgumentListInfo *TemplateArgs;
2038  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2039 
2040  DeclarationName Name = NameInfo.getName();
2041  IdentifierInfo *II = Name.getAsIdentifierInfo();
2042  SourceLocation NameLoc = NameInfo.getLoc();
2043 
2044  if (II && II->isEditorPlaceholder()) {
2045  // FIXME: When typed placeholders are supported we can create a typed
2046  // placeholder expression node.
2047  return ExprError();
2048  }
2049 
2050  // C++ [temp.dep.expr]p3:
2051  // An id-expression is type-dependent if it contains:
2052  // -- an identifier that was declared with a dependent type,
2053  // (note: handled after lookup)
2054  // -- a template-id that is dependent,
2055  // (note: handled in BuildTemplateIdExpr)
2056  // -- a conversion-function-id that specifies a dependent type,
2057  // -- a nested-name-specifier that contains a class-name that
2058  // names a dependent type.
2059  // Determine whether this is a member of an unknown specialization;
2060  // we need to handle these differently.
2061  bool DependentID = false;
2063  Name.getCXXNameType()->isDependentType()) {
2064  DependentID = true;
2065  } else if (SS.isSet()) {
2066  if (DeclContext *DC = computeDeclContext(SS, false)) {
2067  if (RequireCompleteDeclContext(SS, DC))
2068  return ExprError();
2069  } else {
2070  DependentID = true;
2071  }
2072  }
2073 
2074  if (DependentID)
2075  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2076  IsAddressOfOperand, TemplateArgs);
2077 
2078  // Perform the required lookup.
2079  LookupResult R(*this, NameInfo,
2081  ? LookupObjCImplicitSelfParam
2082  : LookupOrdinaryName);
2083  if (TemplateKWLoc.isValid() || TemplateArgs) {
2084  // Lookup the template name again to correctly establish the context in
2085  // which it was found. This is really unfortunate as we already did the
2086  // lookup to determine that it was a template name in the first place. If
2087  // this becomes a performance hit, we can work harder to preserve those
2088  // results until we get here but it's likely not worth it.
2089  bool MemberOfUnknownSpecialization;
2090  if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091  MemberOfUnknownSpecialization, TemplateKWLoc))
2092  return ExprError();
2093 
2094  if (MemberOfUnknownSpecialization ||
2096  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2097  IsAddressOfOperand, TemplateArgs);
2098  } else {
2099  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2100  LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2101 
2102  // If the result might be in a dependent base class, this is a dependent
2103  // id-expression.
2105  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2106  IsAddressOfOperand, TemplateArgs);
2107 
2108  // If this reference is in an Objective-C method, then we need to do
2109  // some special Objective-C lookup, too.
2110  if (IvarLookupFollowUp) {
2111  ExprResult E(LookupInObjCMethod(R, S, II, true));
2112  if (E.isInvalid())
2113  return ExprError();
2114 
2115  if (Expr *Ex = E.getAs<Expr>())
2116  return Ex;
2117  }
2118  }
2119 
2120  if (R.isAmbiguous())
2121  return ExprError();
2122 
2123  // This could be an implicitly declared function reference (legal in C90,
2124  // extension in C99, forbidden in C++).
2125  if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2126  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2127  if (D) R.addDecl(D);
2128  }
2129 
2130  // Determine whether this name might be a candidate for
2131  // argument-dependent lookup.
2132  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2133 
2134  if (R.empty() && !ADL) {
2135  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2136  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2137  TemplateKWLoc, TemplateArgs))
2138  return E;
2139  }
2140 
2141  // Don't diagnose an empty lookup for inline assembly.
2142  if (IsInlineAsmIdentifier)
2143  return ExprError();
2144 
2145  // If this name wasn't predeclared and if this is not a function
2146  // call, diagnose the problem.
2147  TypoExpr *TE = nullptr;
2148  auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2149  II, SS.isValid() ? SS.getScopeRep() : nullptr);
2150  DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2151  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2152  "Typo correction callback misconfigured");
2153  if (CCC) {
2154  // Make sure the callback knows what the typo being diagnosed is.
2155  CCC->setTypoName(II);
2156  if (SS.isValid())
2157  CCC->setTypoNNS(SS.getScopeRep());
2158  }
2159  // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2160  // a template name, but we happen to have always already looked up the name
2161  // before we get here if it must be a template name.
2162  if (DiagnoseEmptyLookup(S, SS, R,
2163  CCC ? std::move(CCC) : std::move(DefaultValidator),
2164  nullptr, None, &TE)) {
2165  if (TE && KeywordReplacement) {
2166  auto &State = getTypoExprState(TE);
2167  auto BestTC = State.Consumer->getNextCorrection();
2168  if (BestTC.isKeyword()) {
2169  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2170  if (State.DiagHandler)
2171  State.DiagHandler(BestTC);
2172  KeywordReplacement->startToken();
2173  KeywordReplacement->setKind(II->getTokenID());
2174  KeywordReplacement->setIdentifierInfo(II);
2175  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2176  // Clean up the state associated with the TypoExpr, since it has
2177  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2178  clearDelayedTypo(TE);
2179  // Signal that a correction to a keyword was performed by returning a
2180  // valid-but-null ExprResult.
2181  return (Expr*)nullptr;
2182  }
2183  State.Consumer->resetCorrectionStream();
2184  }
2185  return TE ? TE : ExprError();
2186  }
2187 
2188  assert(!R.empty() &&
2189  "DiagnoseEmptyLookup returned false but added no results");
2190 
2191  // If we found an Objective-C instance variable, let
2192  // LookupInObjCMethod build the appropriate expression to
2193  // reference the ivar.
2194  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2195  R.clear();
2196  ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2197  // In a hopelessly buggy code, Objective-C instance variable
2198  // lookup fails and no expression will be built to reference it.
2199  if (!E.isInvalid() && !E.get())
2200  return ExprError();
2201  return E;
2202  }
2203  }
2204 
2205  // This is guaranteed from this point on.
2206  assert(!R.empty() || ADL);
2207 
2208  // Check whether this might be a C++ implicit instance member access.
2209  // C++ [class.mfct.non-static]p3:
2210  // When an id-expression that is not part of a class member access
2211  // syntax and not used to form a pointer to member is used in the
2212  // body of a non-static member function of class X, if name lookup
2213  // resolves the name in the id-expression to a non-static non-type
2214  // member of some class C, the id-expression is transformed into a
2215  // class member access expression using (*this) as the
2216  // postfix-expression to the left of the . operator.
2217  //
2218  // But we don't actually need to do this for '&' operands if R
2219  // resolved to a function or overloaded function set, because the
2220  // expression is ill-formed if it actually works out to be a
2221  // non-static member function:
2222  //
2223  // C++ [expr.ref]p4:
2224  // Otherwise, if E1.E2 refers to a non-static member function. . .
2225  // [t]he expression can be used only as the left-hand operand of a
2226  // member function call.
2227  //
2228  // There are other safeguards against such uses, but it's important
2229  // to get this right here so that we don't end up making a
2230  // spuriously dependent expression if we're inside a dependent
2231  // instance method.
2232  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2233  bool MightBeImplicitMember;
2234  if (!IsAddressOfOperand)
2235  MightBeImplicitMember = true;
2236  else if (!SS.isEmpty())
2237  MightBeImplicitMember = false;
2238  else if (R.isOverloadedResult())
2239  MightBeImplicitMember = false;
2240  else if (R.isUnresolvableResult())
2241  MightBeImplicitMember = true;
2242  else
2243  MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2244  isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2245  isa<MSPropertyDecl>(R.getFoundDecl());
2246 
2247  if (MightBeImplicitMember)
2248  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2249  R, TemplateArgs, S);
2250  }
2251 
2252  if (TemplateArgs || TemplateKWLoc.isValid()) {
2253 
2254  // In C++1y, if this is a variable template id, then check it
2255  // in BuildTemplateIdExpr().
2256  // The single lookup result must be a variable template declaration.
2258  Id.TemplateId->Kind == TNK_Var_template) {
2259  assert(R.getAsSingle<VarTemplateDecl>() &&
2260  "There should only be one declaration found.");
2261  }
2262 
2263  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2264  }
2265 
2266  return BuildDeclarationNameExpr(SS, R, ADL);
2267 }
2268 
2269 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2270 /// declaration name, generally during template instantiation.
2271 /// There's a large number of things which don't need to be done along
2272 /// this path.
2274  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2275  bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2276  DeclContext *DC = computeDeclContext(SS, false);
2277  if (!DC)
2278  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2279  NameInfo, /*TemplateArgs=*/nullptr);
2280 
2281  if (RequireCompleteDeclContext(SS, DC))
2282  return ExprError();
2283 
2284  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2285  LookupQualifiedName(R, DC);
2286 
2287  if (R.isAmbiguous())
2288  return ExprError();
2289 
2291  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2292  NameInfo, /*TemplateArgs=*/nullptr);
2293 
2294  if (R.empty()) {
2295  Diag(NameInfo.getLoc(), diag::err_no_member)
2296  << NameInfo.getName() << DC << SS.getRange();
2297  return ExprError();
2298  }
2299 
2300  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2301  // Diagnose a missing typename if this resolved unambiguously to a type in
2302  // a dependent context. If we can recover with a type, downgrade this to
2303  // a warning in Microsoft compatibility mode.
2304  unsigned DiagID = diag::err_typename_missing;
2305  if (RecoveryTSI && getLangOpts().MSVCCompat)
2306  DiagID = diag::ext_typename_missing;
2307  SourceLocation Loc = SS.getBeginLoc();
2308  auto D = Diag(Loc, DiagID);
2309  D << SS.getScopeRep() << NameInfo.getName().getAsString()
2310  << SourceRange(Loc, NameInfo.getEndLoc());
2311 
2312  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2313  // context.
2314  if (!RecoveryTSI)
2315  return ExprError();
2316 
2317  // Only issue the fixit if we're prepared to recover.
2318  D << FixItHint::CreateInsertion(Loc, "typename ");
2319 
2320  // Recover by pretending this was an elaborated type.
2321  QualType Ty = Context.getTypeDeclType(TD);
2322  TypeLocBuilder TLB;
2323  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2324 
2325  QualType ET = getElaboratedType(ETK_None, SS, Ty);
2326  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2328  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2329 
2330  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2331 
2332  return ExprEmpty();
2333  }
2334 
2335  // Defend against this resolving to an implicit member access. We usually
2336  // won't get here if this might be a legitimate a class member (we end up in
2337  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2338  // a pointer-to-member or in an unevaluated context in C++11.
2339  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2340  return BuildPossibleImplicitMemberExpr(SS,
2341  /*TemplateKWLoc=*/SourceLocation(),
2342  R, /*TemplateArgs=*/nullptr, S);
2343 
2344  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2345 }
2346 
2347 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2348 /// detected that we're currently inside an ObjC method. Perform some
2349 /// additional lookup.
2350 ///
2351 /// Ideally, most of this would be done by lookup, but there's
2352 /// actually quite a lot of extra work involved.
2353 ///
2354 /// Returns a null sentinel to indicate trivial success.
2355 ExprResult
2357  IdentifierInfo *II, bool AllowBuiltinCreation) {
2358  SourceLocation Loc = Lookup.getNameLoc();
2359  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2360 
2361  // Check for error condition which is already reported.
2362  if (!CurMethod)
2363  return ExprError();
2364 
2365  // There are two cases to handle here. 1) scoped lookup could have failed,
2366  // in which case we should look for an ivar. 2) scoped lookup could have
2367  // found a decl, but that decl is outside the current instance method (i.e.
2368  // a global variable). In these two cases, we do a lookup for an ivar with
2369  // this name, if the lookup sucedes, we replace it our current decl.
2370 
2371  // If we're in a class method, we don't normally want to look for
2372  // ivars. But if we don't find anything else, and there's an
2373  // ivar, that's an error.
2374  bool IsClassMethod = CurMethod->isClassMethod();
2375 
2376  bool LookForIvars;
2377  if (Lookup.empty())
2378  LookForIvars = true;
2379  else if (IsClassMethod)
2380  LookForIvars = false;
2381  else
2382  LookForIvars = (Lookup.isSingleResult() &&
2384  ObjCInterfaceDecl *IFace = nullptr;
2385  if (LookForIvars) {
2386  IFace = CurMethod->getClassInterface();
2387  ObjCInterfaceDecl *ClassDeclared;
2388  ObjCIvarDecl *IV = nullptr;
2389  if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2390  // Diagnose using an ivar in a class method.
2391  if (IsClassMethod)
2392  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2393  << IV->getDeclName());
2394 
2395  // If we're referencing an invalid decl, just return this as a silent
2396  // error node. The error diagnostic was already emitted on the decl.
2397  if (IV->isInvalidDecl())
2398  return ExprError();
2399 
2400  // Check if referencing a field with __attribute__((deprecated)).
2401  if (DiagnoseUseOfDecl(IV, Loc))
2402  return ExprError();
2403 
2404  // Diagnose the use of an ivar outside of the declaring class.
2405  if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2406  !declaresSameEntity(ClassDeclared, IFace) &&
2407  !getLangOpts().DebuggerSupport)
2408  Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2409 
2410  // FIXME: This should use a new expr for a direct reference, don't
2411  // turn this into Self->ivar, just return a BareIVarExpr or something.
2412  IdentifierInfo &II = Context.Idents.get("self");
2413  UnqualifiedId SelfName;
2414  SelfName.setIdentifier(&II, SourceLocation());
2416  CXXScopeSpec SelfScopeSpec;
2417  SourceLocation TemplateKWLoc;
2418  ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2419  SelfName, false, false);
2420  if (SelfExpr.isInvalid())
2421  return ExprError();
2422 
2423  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2424  if (SelfExpr.isInvalid())
2425  return ExprError();
2426 
2427  MarkAnyDeclReferenced(Loc, IV, true);
2428 
2429  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2430  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2431  !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2432  Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2433 
2434  ObjCIvarRefExpr *Result = new (Context)
2435  ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2436  IV->getLocation(), SelfExpr.get(), true, true);
2437 
2438  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2439  if (!isUnevaluatedContext() &&
2440  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2441  getCurFunction()->recordUseOfWeak(Result);
2442  }
2443  if (getLangOpts().ObjCAutoRefCount) {
2444  if (CurContext->isClosure())
2445  Diag(Loc, diag::warn_implicitly_retains_self)
2446  << FixItHint::CreateInsertion(Loc, "self->");
2447  }
2448 
2449  return Result;
2450  }
2451  } else if (CurMethod->isInstanceMethod()) {
2452  // We should warn if a local variable hides an ivar.
2453  if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2454  ObjCInterfaceDecl *ClassDeclared;
2455  if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2456  if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2457  declaresSameEntity(IFace, ClassDeclared))
2458  Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2459  }
2460  }
2461  } else if (Lookup.isSingleResult() &&
2463  // If accessing a stand-alone ivar in a class method, this is an error.
2464  if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2465  return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2466  << IV->getDeclName());
2467  }
2468 
2469  if (Lookup.empty() && II && AllowBuiltinCreation) {
2470  // FIXME. Consolidate this with similar code in LookupName.
2471  if (unsigned BuiltinID = II->getBuiltinID()) {
2472  if (!(getLangOpts().CPlusPlus &&
2473  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2474  NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2475  S, Lookup.isForRedeclaration(),
2476  Lookup.getNameLoc());
2477  if (D) Lookup.addDecl(D);
2478  }
2479  }
2480  }
2481  // Sentinel value saying that we didn't do anything special.
2482  return ExprResult((Expr *)nullptr);
2483 }
2484 
2485 /// Cast a base object to a member's actual type.
2486 ///
2487 /// Logically this happens in three phases:
2488 ///
2489 /// * First we cast from the base type to the naming class.
2490 /// The naming class is the class into which we were looking
2491 /// when we found the member; it's the qualifier type if a
2492 /// qualifier was provided, and otherwise it's the base type.
2493 ///
2494 /// * Next we cast from the naming class to the declaring class.
2495 /// If the member we found was brought into a class's scope by
2496 /// a using declaration, this is that class; otherwise it's
2497 /// the class declaring the member.
2498 ///
2499 /// * Finally we cast from the declaring class to the "true"
2500 /// declaring class of the member. This conversion does not
2501 /// obey access control.
2502 ExprResult
2504  NestedNameSpecifier *Qualifier,
2505  NamedDecl *FoundDecl,
2506  NamedDecl *Member) {
2507  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2508  if (!RD)
2509  return From;
2510 
2511  QualType DestRecordType;
2512  QualType DestType;
2513  QualType FromRecordType;
2514  QualType FromType = From->getType();
2515  bool PointerConversions = false;
2516  if (isa<FieldDecl>(Member)) {
2517  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2518 
2519  if (FromType->getAs<PointerType>()) {
2520  DestType = Context.getPointerType(DestRecordType);
2521  FromRecordType = FromType->getPointeeType();
2522  PointerConversions = true;
2523  } else {
2524  DestType = DestRecordType;
2525  FromRecordType = FromType;
2526  }
2527  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2528  if (Method->isStatic())
2529  return From;
2530 
2531  DestType = Method->getThisType(Context);
2532  DestRecordType = DestType->getPointeeType();
2533 
2534  if (FromType->getAs<PointerType>()) {
2535  FromRecordType = FromType->getPointeeType();
2536  PointerConversions = true;
2537  } else {
2538  FromRecordType = FromType;
2539  DestType = DestRecordType;
2540  }
2541  } else {
2542  // No conversion necessary.
2543  return From;
2544  }
2545 
2546  if (DestType->isDependentType() || FromType->isDependentType())
2547  return From;
2548 
2549  // If the unqualified types are the same, no conversion is necessary.
2550  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2551  return From;
2552 
2553  SourceRange FromRange = From->getSourceRange();
2554  SourceLocation FromLoc = FromRange.getBegin();
2555 
2556  ExprValueKind VK = From->getValueKind();
2557 
2558  // C++ [class.member.lookup]p8:
2559  // [...] Ambiguities can often be resolved by qualifying a name with its
2560  // class name.
2561  //
2562  // If the member was a qualified name and the qualified referred to a
2563  // specific base subobject type, we'll cast to that intermediate type
2564  // first and then to the object in which the member is declared. That allows
2565  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2566  //
2567  // class Base { public: int x; };
2568  // class Derived1 : public Base { };
2569  // class Derived2 : public Base { };
2570  // class VeryDerived : public Derived1, public Derived2 { void f(); };
2571  //
2572  // void VeryDerived::f() {
2573  // x = 17; // error: ambiguous base subobjects
2574  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2575  // }
2576  if (Qualifier && Qualifier->getAsType()) {
2577  QualType QType = QualType(Qualifier->getAsType(), 0);
2578  assert(QType->isRecordType() && "lookup done with non-record type");
2579 
2580  QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2581 
2582  // In C++98, the qualifier type doesn't actually have to be a base
2583  // type of the object type, in which case we just ignore it.
2584  // Otherwise build the appropriate casts.
2585  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2586  CXXCastPath BasePath;
2587  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2588  FromLoc, FromRange, &BasePath))
2589  return ExprError();
2590 
2591  if (PointerConversions)
2592  QType = Context.getPointerType(QType);
2593  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2594  VK, &BasePath).get();
2595 
2596  FromType = QType;
2597  FromRecordType = QRecordType;
2598 
2599  // If the qualifier type was the same as the destination type,
2600  // we're done.
2601  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2602  return From;
2603  }
2604  }
2605 
2606  bool IgnoreAccess = false;
2607 
2608  // If we actually found the member through a using declaration, cast
2609  // down to the using declaration's type.
2610  //
2611  // Pointer equality is fine here because only one declaration of a
2612  // class ever has member declarations.
2613  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2614  assert(isa<UsingShadowDecl>(FoundDecl));
2615  QualType URecordType = Context.getTypeDeclType(
2616  cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2617 
2618  // We only need to do this if the naming-class to declaring-class
2619  // conversion is non-trivial.
2620  if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2621  assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2622  CXXCastPath BasePath;
2623  if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2624  FromLoc, FromRange, &BasePath))
2625  return ExprError();
2626 
2627  QualType UType = URecordType;
2628  if (PointerConversions)
2629  UType = Context.getPointerType(UType);
2630  From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2631  VK, &BasePath).get();
2632  FromType = UType;
2633  FromRecordType = URecordType;
2634  }
2635 
2636  // We don't do access control for the conversion from the
2637  // declaring class to the true declaring class.
2638  IgnoreAccess = true;
2639  }
2640 
2641  CXXCastPath BasePath;
2642  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2643  FromLoc, FromRange, &BasePath,
2644  IgnoreAccess))
2645  return ExprError();
2646 
2647  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2648  VK, &BasePath);
2649 }
2650 
2652  const LookupResult &R,
2653  bool HasTrailingLParen) {
2654  // Only when used directly as the postfix-expression of a call.
2655  if (!HasTrailingLParen)
2656  return false;
2657 
2658  // Never if a scope specifier was provided.
2659  if (SS.isSet())
2660  return false;
2661 
2662  // Only in C++ or ObjC++.
2663  if (!getLangOpts().CPlusPlus)
2664  return false;
2665 
2666  // Turn off ADL when we find certain kinds of declarations during
2667  // normal lookup:
2668  for (NamedDecl *D : R) {
2669  // C++0x [basic.lookup.argdep]p3:
2670  // -- a declaration of a class member
2671  // Since using decls preserve this property, we check this on the
2672  // original decl.
2673  if (D->isCXXClassMember())
2674  return false;
2675 
2676  // C++0x [basic.lookup.argdep]p3:
2677  // -- a block-scope function declaration that is not a
2678  // using-declaration
2679  // NOTE: we also trigger this for function templates (in fact, we
2680  // don't check the decl type at all, since all other decl types
2681  // turn off ADL anyway).
2682  if (isa<UsingShadowDecl>(D))
2683  D = cast<UsingShadowDecl>(D)->getTargetDecl();
2684  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2685  return false;
2686 
2687  // C++0x [basic.lookup.argdep]p3:
2688  // -- a declaration that is neither a function or a function
2689  // template
2690  // And also for builtin functions.
2691  if (isa<FunctionDecl>(D)) {
2692  FunctionDecl *FDecl = cast<FunctionDecl>(D);
2693 
2694  // But also builtin functions.
2695  if (FDecl->getBuiltinID() && FDecl->isImplicit())
2696  return false;
2697  } else if (!isa<FunctionTemplateDecl>(D))
2698  return false;
2699  }
2700 
2701  return true;
2702 }
2703 
2704 
2705 /// Diagnoses obvious problems with the use of the given declaration
2706 /// as an expression. This is only actually called for lookups that
2707 /// were not overloaded, and it doesn't promise that the declaration
2708 /// will in fact be used.
2709 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2710  if (D->isInvalidDecl())
2711  return true;
2712 
2713  if (isa<TypedefNameDecl>(D)) {
2714  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2715  return true;
2716  }
2717 
2718  if (isa<ObjCInterfaceDecl>(D)) {
2719  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2720  return true;
2721  }
2722 
2723  if (isa<NamespaceDecl>(D)) {
2724  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2725  return true;
2726  }
2727 
2728  return false;
2729 }
2730 
2731 // Certain multiversion types should be treated as overloaded even when there is
2732 // only one result.
2734  assert(R.isSingleResult() && "Expected only a single result");
2735  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2736  return FD &&
2737  (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2738 }
2739 
2741  LookupResult &R, bool NeedsADL,
2742  bool AcceptInvalidDecl) {
2743  // If this is a single, fully-resolved result and we don't need ADL,
2744  // just build an ordinary singleton decl ref.
2745  if (!NeedsADL && R.isSingleResult() &&
2748  return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2749  R.getRepresentativeDecl(), nullptr,
2750  AcceptInvalidDecl);
2751 
2752  // We only need to check the declaration if there's exactly one
2753  // result, because in the overloaded case the results can only be
2754  // functions and function templates.
2756  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2757  return ExprError();
2758 
2759  // Otherwise, just build an unresolved lookup expression. Suppress
2760  // any lookup-related diagnostics; we'll hash these out later, when
2761  // we've picked a target.
2762  R.suppressDiagnostics();
2763 
2766  SS.getWithLocInContext(Context),
2767  R.getLookupNameInfo(),
2768  NeedsADL, R.isOverloadedResult(),
2769  R.begin(), R.end());
2770 
2771  return ULE;
2772 }
2773 
2774 static void
2776  ValueDecl *var, DeclContext *DC);
2777 
2778 /// Complete semantic analysis for a reference to the given declaration.
2780  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2781  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2782  bool AcceptInvalidDecl) {
2783  assert(D && "Cannot refer to a NULL declaration");
2784  assert(!isa<FunctionTemplateDecl>(D) &&
2785  "Cannot refer unambiguously to a function template");
2786 
2787  SourceLocation Loc = NameInfo.getLoc();
2788  if (CheckDeclInExpr(*this, Loc, D))
2789  return ExprError();
2790 
2791  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2792  // Specifically diagnose references to class templates that are missing
2793  // a template argument list.
2794  diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2795  return ExprError();
2796  }
2797 
2798  // Make sure that we're referring to a value.
2799  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2800  if (!VD) {
2801  Diag(Loc, diag::err_ref_non_value)
2802  << D << SS.getRange();
2803  Diag(D->getLocation(), diag::note_declared_at);
2804  return ExprError();
2805  }
2806 
2807  // Check whether this declaration can be used. Note that we suppress
2808  // this check when we're going to perform argument-dependent lookup
2809  // on this function name, because this might not be the function
2810  // that overload resolution actually selects.
2811  if (DiagnoseUseOfDecl(VD, Loc))
2812  return ExprError();
2813 
2814  // Only create DeclRefExpr's for valid Decl's.
2815  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2816  return ExprError();
2817 
2818  // Handle members of anonymous structs and unions. If we got here,
2819  // and the reference is to a class member indirect field, then this
2820  // must be the subject of a pointer-to-member expression.
2821  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2822  if (!indirectField->isCXXClassMember())
2823  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2824  indirectField);
2825 
2826  {
2827  QualType type = VD->getType();
2828  if (type.isNull())
2829  return ExprError();
2830  if (auto *FPT = type->getAs<FunctionProtoType>()) {
2831  // C++ [except.spec]p17:
2832  // An exception-specification is considered to be needed when:
2833  // - in an expression, the function is the unique lookup result or
2834  // the selected member of a set of overloaded functions.
2835  ResolveExceptionSpec(Loc, FPT);
2836  type = VD->getType();
2837  }
2838  ExprValueKind valueKind = VK_RValue;
2839 
2840  switch (D->getKind()) {
2841  // Ignore all the non-ValueDecl kinds.
2842 #define ABSTRACT_DECL(kind)
2843 #define VALUE(type, base)
2844 #define DECL(type, base) \
2845  case Decl::type:
2846 #include "clang/AST/DeclNodes.inc"
2847  llvm_unreachable("invalid value decl kind");
2848 
2849  // These shouldn't make it here.
2850  case Decl::ObjCAtDefsField:
2851  case Decl::ObjCIvar:
2852  llvm_unreachable("forming non-member reference to ivar?");
2853 
2854  // Enum constants are always r-values and never references.
2855  // Unresolved using declarations are dependent.
2856  case Decl::EnumConstant:
2857  case Decl::UnresolvedUsingValue:
2858  case Decl::OMPDeclareReduction:
2859  valueKind = VK_RValue;
2860  break;
2861 
2862  // Fields and indirect fields that got here must be for
2863  // pointer-to-member expressions; we just call them l-values for
2864  // internal consistency, because this subexpression doesn't really
2865  // exist in the high-level semantics.
2866  case Decl::Field:
2867  case Decl::IndirectField:
2868  assert(getLangOpts().CPlusPlus &&
2869  "building reference to field in C?");
2870 
2871  // These can't have reference type in well-formed programs, but
2872  // for internal consistency we do this anyway.
2873  type = type.getNonReferenceType();
2874  valueKind = VK_LValue;
2875  break;
2876 
2877  // Non-type template parameters are either l-values or r-values
2878  // depending on the type.
2879  case Decl::NonTypeTemplateParm: {
2880  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2881  type = reftype->getPointeeType();
2882  valueKind = VK_LValue; // even if the parameter is an r-value reference
2883  break;
2884  }
2885 
2886  // For non-references, we need to strip qualifiers just in case
2887  // the template parameter was declared as 'const int' or whatever.
2888  valueKind = VK_RValue;
2889  type = type.getUnqualifiedType();
2890  break;
2891  }
2892 
2893  case Decl::Var:
2894  case Decl::VarTemplateSpecialization:
2895  case Decl::VarTemplatePartialSpecialization:
2896  case Decl::Decomposition:
2897  case Decl::OMPCapturedExpr:
2898  // In C, "extern void blah;" is valid and is an r-value.
2899  if (!getLangOpts().CPlusPlus &&
2900  !type.hasQualifiers() &&
2901  type->isVoidType()) {
2902  valueKind = VK_RValue;
2903  break;
2904  }
2905  LLVM_FALLTHROUGH;
2906 
2907  case Decl::ImplicitParam:
2908  case Decl::ParmVar: {
2909  // These are always l-values.
2910  valueKind = VK_LValue;
2911  type = type.getNonReferenceType();
2912 
2913  // FIXME: Does the addition of const really only apply in
2914  // potentially-evaluated contexts? Since the variable isn't actually
2915  // captured in an unevaluated context, it seems that the answer is no.
2916  if (!isUnevaluatedContext()) {
2917  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2918  if (!CapturedType.isNull())
2919  type = CapturedType;
2920  }
2921 
2922  break;
2923  }
2924 
2925  case Decl::Binding: {
2926  // These are always lvalues.
2927  valueKind = VK_LValue;
2928  type = type.getNonReferenceType();
2929  // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2930  // decides how that's supposed to work.
2931  auto *BD = cast<BindingDecl>(VD);
2932  if (BD->getDeclContext()->isFunctionOrMethod() &&
2933  BD->getDeclContext() != CurContext)
2934  diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2935  break;
2936  }
2937 
2938  case Decl::Function: {
2939  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2940  if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2941  type = Context.BuiltinFnTy;
2942  valueKind = VK_RValue;
2943  break;
2944  }
2945  }
2946 
2947  const FunctionType *fty = type->castAs<FunctionType>();
2948 
2949  // If we're referring to a function with an __unknown_anytype
2950  // result type, make the entire expression __unknown_anytype.
2951  if (fty->getReturnType() == Context.UnknownAnyTy) {
2952  type = Context.UnknownAnyTy;
2953  valueKind = VK_RValue;
2954  break;
2955  }
2956 
2957  // Functions are l-values in C++.
2958  if (getLangOpts().CPlusPlus) {
2959  valueKind = VK_LValue;
2960  break;
2961  }
2962 
2963  // C99 DR 316 says that, if a function type comes from a
2964  // function definition (without a prototype), that type is only
2965  // used for checking compatibility. Therefore, when referencing
2966  // the function, we pretend that we don't have the full function
2967  // type.
2968  if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2969  isa<FunctionProtoType>(fty))
2970  type = Context.getFunctionNoProtoType(fty->getReturnType(),
2971  fty->getExtInfo());
2972 
2973  // Functions are r-values in C.
2974  valueKind = VK_RValue;
2975  break;
2976  }
2977 
2978  case Decl::CXXDeductionGuide:
2979  llvm_unreachable("building reference to deduction guide");
2980 
2981  case Decl::MSProperty:
2982  valueKind = VK_LValue;
2983  break;
2984 
2985  case Decl::CXXMethod:
2986  // If we're referring to a method with an __unknown_anytype
2987  // result type, make the entire expression __unknown_anytype.
2988  // This should only be possible with a type written directly.
2989  if (const FunctionProtoType *proto
2990  = dyn_cast<FunctionProtoType>(VD->getType()))
2991  if (proto->getReturnType() == Context.UnknownAnyTy) {
2992  type = Context.UnknownAnyTy;
2993  valueKind = VK_RValue;
2994  break;
2995  }
2996 
2997  // C++ methods are l-values if static, r-values if non-static.
2998  if (cast<CXXMethodDecl>(VD)->isStatic()) {
2999  valueKind = VK_LValue;
3000  break;
3001  }
3002  LLVM_FALLTHROUGH;
3003 
3004  case Decl::CXXConversion:
3005  case Decl::CXXDestructor:
3006  case Decl::CXXConstructor:
3007  valueKind = VK_RValue;
3008  break;
3009  }
3010 
3011  return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3012  TemplateArgs);
3013  }
3014 }
3015 
3016 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3018  Target.resize(CharByteWidth * (Source.size() + 1));
3019  char *ResultPtr = &Target[0];
3020  const llvm::UTF8 *ErrorPtr;
3021  bool success =
3022  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3023  (void)success;
3024  assert(success);
3025  Target.resize(ResultPtr - &Target[0]);
3026 }
3027 
3030  // Pick the current block, lambda, captured statement or function.
3031  Decl *currentDecl = nullptr;
3032  if (const BlockScopeInfo *BSI = getCurBlock())
3033  currentDecl = BSI->TheDecl;
3034  else if (const LambdaScopeInfo *LSI = getCurLambda())
3035  currentDecl = LSI->CallOperator;
3036  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3037  currentDecl = CSI->TheCapturedDecl;
3038  else
3039  currentDecl = getCurFunctionOrMethodDecl();
3040 
3041  if (!currentDecl) {
3042  Diag(Loc, diag::ext_predef_outside_function);
3043  currentDecl = Context.getTranslationUnitDecl();
3044  }
3045 
3046  QualType ResTy;
3047  StringLiteral *SL = nullptr;
3048  if (cast<DeclContext>(currentDecl)->isDependentContext())
3049  ResTy = Context.DependentTy;
3050  else {
3051  // Pre-defined identifiers are of type char[x], where x is the length of
3052  // the string.
3053  auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3054  unsigned Length = Str.length();
3055 
3056  llvm::APInt LengthI(32, Length + 1);
3058  ResTy =
3060  SmallString<32> RawChars;
3062  Str, RawChars);
3063  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3064  /*IndexTypeQuals*/ 0);
3065  SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3066  /*Pascal*/ false, ResTy, Loc);
3067  } else {
3068  ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3069  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3070  /*IndexTypeQuals*/ 0);
3071  SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3072  /*Pascal*/ false, ResTy, Loc);
3073  }
3074  }
3075 
3076  return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3077 }
3078 
3081 
3082  switch (Kind) {
3083  default: llvm_unreachable("Unknown simple primary expr!");
3084  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3085  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3086  case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3087  case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3088  case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS]
3089  case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS]
3090  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3091  }
3092 
3093  return BuildPredefinedExpr(Loc, IT);
3094 }
3095 
3097  SmallString<16> CharBuffer;
3098  bool Invalid = false;
3099  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3100  if (Invalid)
3101  return ExprError();
3102 
3103  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3104  PP, Tok.getKind());
3105  if (Literal.hadError())
3106  return ExprError();
3107 
3108  QualType Ty;
3109  if (Literal.isWide())
3110  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3111  else if (Literal.isUTF8() && getLangOpts().Char8)
3112  Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3113  else if (Literal.isUTF16())
3114  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3115  else if (Literal.isUTF32())
3116  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3117  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3118  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3119  else
3120  Ty = Context.CharTy; // 'x' -> char in C++
3121 
3123  if (Literal.isWide())
3125  else if (Literal.isUTF16())
3127  else if (Literal.isUTF32())
3129  else if (Literal.isUTF8())
3131 
3132  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3133  Tok.getLocation());
3134 
3135  if (Literal.getUDSuffix().empty())
3136  return Lit;
3137 
3138  // We're building a user-defined literal.
3139  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3140  SourceLocation UDSuffixLoc =
3141  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3142 
3143  // Make sure we're allowed user-defined literals here.
3144  if (!UDLScope)
3145  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3146 
3147  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3148  // operator "" X (ch)
3149  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3150  Lit, Tok.getLocation());
3151 }
3152 
3154  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3155  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3156  Context.IntTy, Loc);
3157 }
3158 
3160  QualType Ty, SourceLocation Loc) {
3161  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3162 
3163  using llvm::APFloat;
3164  APFloat Val(Format);
3165 
3166  APFloat::opStatus result = Literal.GetFloatValue(Val);
3167 
3168  // Overflow is always an error, but underflow is only an error if
3169  // we underflowed to zero (APFloat reports denormals as underflow).
3170  if ((result & APFloat::opOverflow) ||
3171  ((result & APFloat::opUnderflow) && Val.isZero())) {
3172  unsigned diagnostic;
3173  SmallString<20> buffer;
3174  if (result & APFloat::opOverflow) {
3175  diagnostic = diag::warn_float_overflow;
3176  APFloat::getLargest(Format).toString(buffer);
3177  } else {
3178  diagnostic = diag::warn_float_underflow;
3179  APFloat::getSmallest(Format).toString(buffer);
3180  }
3181 
3182  S.Diag(Loc, diagnostic)
3183  << Ty
3184  << StringRef(buffer.data(), buffer.size());
3185  }
3186 
3187  bool isExact = (result == APFloat::opOK);
3188  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3189 }
3190 
3192  assert(E && "Invalid expression");
3193 
3194  if (E->isValueDependent())
3195  return false;
3196 
3197  QualType QT = E->getType();
3198  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3199  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3200  return true;
3201  }
3202 
3203  llvm::APSInt ValueAPS;
3204  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3205 
3206  if (R.isInvalid())
3207  return true;
3208 
3209  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3210  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3211  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3212  << ValueAPS.toString(10) << ValueIsPositive;
3213  return true;
3214  }
3215 
3216  return false;
3217 }
3218 
3220  // Fast path for a single digit (which is quite common). A single digit
3221  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3222  if (Tok.getLength() == 1) {
3223  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3224  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3225  }
3226 
3227  SmallString<128> SpellingBuffer;
3228  // NumericLiteralParser wants to overread by one character. Add padding to
3229  // the buffer in case the token is copied to the buffer. If getSpelling()
3230  // returns a StringRef to the memory buffer, it should have a null char at
3231  // the EOF, so it is also safe.
3232  SpellingBuffer.resize(Tok.getLength() + 1);
3233 
3234  // Get the spelling of the token, which eliminates trigraphs, etc.
3235  bool Invalid = false;
3236  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3237  if (Invalid)
3238  return ExprError();
3239 
3240  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3241  if (Literal.hadError)
3242  return ExprError();
3243 
3244  if (Literal.hasUDSuffix()) {
3245  // We're building a user-defined literal.
3246  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3247  SourceLocation UDSuffixLoc =
3248  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3249 
3250  // Make sure we're allowed user-defined literals here.
3251  if (!UDLScope)
3252  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3253 
3254  QualType CookedTy;
3255  if (Literal.isFloatingLiteral()) {
3256  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3257  // long double, the literal is treated as a call of the form
3258  // operator "" X (f L)
3259  CookedTy = Context.LongDoubleTy;
3260  } else {
3261  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3262  // unsigned long long, the literal is treated as a call of the form
3263  // operator "" X (n ULL)
3264  CookedTy = Context.UnsignedLongLongTy;
3265  }
3266 
3267  DeclarationName OpName =
3268  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3269  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3270  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3271 
3272  SourceLocation TokLoc = Tok.getLocation();
3273 
3274  // Perform literal operator lookup to determine if we're building a raw
3275  // literal or a cooked one.
3276  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3277  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3278  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3279  /*AllowStringTemplate*/ false,
3280  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3281  case LOLR_ErrorNoDiagnostic:
3282  // Lookup failure for imaginary constants isn't fatal, there's still the
3283  // GNU extension producing _Complex types.
3284  break;
3285  case LOLR_Error:
3286  return ExprError();
3287  case LOLR_Cooked: {
3288  Expr *Lit;
3289  if (Literal.isFloatingLiteral()) {
3290  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3291  } else {
3292  llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3293  if (Literal.GetIntegerValue(ResultVal))
3294  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3295  << /* Unsigned */ 1;
3296  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3297  Tok.getLocation());
3298  }
3299  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3300  }
3301 
3302  case LOLR_Raw: {
3303  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3304  // literal is treated as a call of the form
3305  // operator "" X ("n")
3306  unsigned Length = Literal.getUDSuffixOffset();
3307  QualType StrTy = Context.getConstantArrayType(
3308  Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3309  llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3310  Expr *Lit = StringLiteral::Create(
3311  Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3312  /*Pascal*/false, StrTy, &TokLoc, 1);
3313  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3314  }
3315 
3316  case LOLR_Template: {
3317  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3318  // template), L is treated as a call fo the form
3319  // operator "" X <'c1', 'c2', ... 'ck'>()
3320  // where n is the source character sequence c1 c2 ... ck.
3321  TemplateArgumentListInfo ExplicitArgs;
3322  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3323  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3324  llvm::APSInt Value(CharBits, CharIsUnsigned);
3325  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3326  Value = TokSpelling[I];
3327  TemplateArgument Arg(Context, Value, Context.CharTy);
3328  TemplateArgumentLocInfo ArgInfo;
3329  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3330  }
3331  return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3332  &ExplicitArgs);
3333  }
3334  case LOLR_StringTemplate:
3335  llvm_unreachable("unexpected literal operator lookup result");
3336  }
3337  }
3338 
3339  Expr *Res;
3340 
3341  if (Literal.isFixedPointLiteral()) {
3342  QualType Ty;
3343 
3344  if (Literal.isAccum) {
3345  if (Literal.isHalf) {
3346  Ty = Context.ShortAccumTy;
3347  } else if (Literal.isLong) {
3348  Ty = Context.LongAccumTy;
3349  } else {
3350  Ty = Context.AccumTy;
3351  }
3352  } else if (Literal.isFract) {
3353  if (Literal.isHalf) {
3354  Ty = Context.ShortFractTy;
3355  } else if (Literal.isLong) {
3356  Ty = Context.LongFractTy;
3357  } else {
3358  Ty = Context.FractTy;
3359  }
3360  }
3361 
3362  if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3363 
3364  bool isSigned = !Literal.isUnsigned;
3365  unsigned scale = Context.getFixedPointScale(Ty);
3366  unsigned ibits = Context.getFixedPointIBits(Ty);
3367  unsigned bit_width = Context.getTypeInfo(Ty).Width;
3368 
3369  llvm::APInt Val(bit_width, 0, isSigned);
3370  bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3371 
3372  // Do not use bit_width since some types may have padding like _Fract or
3373  // unsigned _Accums if PaddingOnUnsignedFixedPoint is set.
3374  auto MaxVal = llvm::APInt::getMaxValue(ibits + scale).zextOrSelf(bit_width);
3375  if (Literal.isFract && Val == MaxVal + 1)
3376  // Clause 6.4.4 - The value of a constant shall be in the range of
3377  // representable values for its type, with exception for constants of a
3378  // fract type with a value of exactly 1; such a constant shall denote
3379  // the maximal value for the type.
3380  --Val;
3381  else if (Val.ugt(MaxVal) || Overflowed)
3382  Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3383 
3384  Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3385  Tok.getLocation(), scale);
3386  } else if (Literal.isFloatingLiteral()) {
3387  QualType Ty;
3388  if (Literal.isHalf){
3389  if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3390  Ty = Context.HalfTy;
3391  else {
3392  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3393  return ExprError();
3394  }
3395  } else if (Literal.isFloat)
3396  Ty = Context.FloatTy;
3397  else if (Literal.isLong)
3398  Ty = Context.LongDoubleTy;
3399  else if (Literal.isFloat16)
3400  Ty = Context.Float16Ty;
3401  else if (Literal.isFloat128)
3402  Ty = Context.Float128Ty;
3403  else
3404  Ty = Context.DoubleTy;
3405 
3406  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3407 
3408  if (Ty == Context.DoubleTy) {
3409  if (getLangOpts().SinglePrecisionConstants) {
3410  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3411  if (BTy->getKind() != BuiltinType::Float) {
3412  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3413  }
3414  } else if (getLangOpts().OpenCL &&
3415  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3416  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3417  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3418  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3419  }
3420  }
3421  } else if (!Literal.isIntegerLiteral()) {
3422  return ExprError();
3423  } else {
3424  QualType Ty;
3425 
3426  // 'long long' is a C99 or C++11 feature.
3427  if (!getLangOpts().C99 && Literal.isLongLong) {
3428  if (getLangOpts().CPlusPlus)
3429  Diag(Tok.getLocation(),
3430  getLangOpts().CPlusPlus11 ?
3431  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3432  else
3433  Diag(Tok.getLocation(), diag::ext_c99_longlong);
3434  }
3435 
3436  // Get the value in the widest-possible width.
3437  unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3438  llvm::APInt ResultVal(MaxWidth, 0);
3439 
3440  if (Literal.GetIntegerValue(ResultVal)) {
3441  // If this value didn't fit into uintmax_t, error and force to ull.
3442  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3443  << /* Unsigned */ 1;
3444  Ty = Context.UnsignedLongLongTy;
3445  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3446  "long long is not intmax_t?");
3447  } else {
3448  // If this value fits into a ULL, try to figure out what else it fits into
3449  // according to the rules of C99 6.4.4.1p5.
3450 
3451  // Octal, Hexadecimal, and integers with a U suffix are allowed to
3452  // be an unsigned int.
3453  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3454 
3455  // Check from smallest to largest, picking the smallest type we can.
3456  unsigned Width = 0;
3457 
3458  // Microsoft specific integer suffixes are explicitly sized.
3459  if (Literal.MicrosoftInteger) {
3460  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3461  Width = 8;
3462  Ty = Context.CharTy;
3463  } else {
3464  Width = Literal.MicrosoftInteger;
3465  Ty = Context.getIntTypeForBitwidth(Width,
3466  /*Signed=*/!Literal.isUnsigned);
3467  }
3468  }
3469 
3470  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3471  // Are int/unsigned possibilities?
3472  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3473 
3474  // Does it fit in a unsigned int?
3475  if (ResultVal.isIntN(IntSize)) {
3476  // Does it fit in a signed int?
3477  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3478  Ty = Context.IntTy;
3479  else if (AllowUnsigned)
3480  Ty = Context.UnsignedIntTy;
3481  Width = IntSize;
3482  }
3483  }
3484 
3485  // Are long/unsigned long possibilities?
3486  if (Ty.isNull() && !Literal.isLongLong) {
3487  unsigned LongSize = Context.getTargetInfo().getLongWidth();
3488 
3489  // Does it fit in a unsigned long?
3490  if (ResultVal.isIntN(LongSize)) {
3491  // Does it fit in a signed long?
3492  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3493  Ty = Context.LongTy;
3494  else if (AllowUnsigned)
3495  Ty = Context.UnsignedLongTy;
3496  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3497  // is compatible.
3498  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3499  const unsigned LongLongSize =
3500  Context.getTargetInfo().getLongLongWidth();
3501  Diag(Tok.getLocation(),
3502  getLangOpts().CPlusPlus
3503  ? Literal.isLong
3504  ? diag::warn_old_implicitly_unsigned_long_cxx
3505  : /*C++98 UB*/ diag::
3506  ext_old_implicitly_unsigned_long_cxx
3507  : diag::warn_old_implicitly_unsigned_long)
3508  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3509  : /*will be ill-formed*/ 1);
3510  Ty = Context.UnsignedLongTy;
3511  }
3512  Width = LongSize;
3513  }
3514  }
3515 
3516  // Check long long if needed.
3517  if (Ty.isNull()) {
3518  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3519 
3520  // Does it fit in a unsigned long long?
3521  if (ResultVal.isIntN(LongLongSize)) {
3522  // Does it fit in a signed long long?
3523  // To be compatible with MSVC, hex integer literals ending with the
3524  // LL or i64 suffix are always signed in Microsoft mode.
3525  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3526  (getLangOpts().MSVCCompat && Literal.isLongLong)))
3527  Ty = Context.LongLongTy;
3528  else if (AllowUnsigned)
3529  Ty = Context.UnsignedLongLongTy;
3530  Width = LongLongSize;
3531  }
3532  }
3533 
3534  // If we still couldn't decide a type, we probably have something that
3535  // does not fit in a signed long long, but has no U suffix.
3536  if (Ty.isNull()) {
3537  Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3538  Ty = Context.UnsignedLongLongTy;
3539  Width = Context.getTargetInfo().getLongLongWidth();
3540  }
3541 
3542  if (ResultVal.getBitWidth() != Width)
3543  ResultVal = ResultVal.trunc(Width);
3544  }
3545  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3546  }
3547 
3548  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3549  if (Literal.isImaginary) {
3550  Res = new (Context) ImaginaryLiteral(Res,
3551  Context.getComplexType(Res->getType()));
3552 
3553  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3554  }
3555  return Res;
3556 }
3557 
3559  assert(E && "ActOnParenExpr() missing expr");
3560  return new (Context) ParenExpr(L, R, E);
3561 }
3562 
3564  SourceLocation Loc,
3565  SourceRange ArgRange) {
3566  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3567  // scalar or vector data type argument..."
3568  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3569  // type (C99 6.2.5p18) or void.
3570  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3571  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3572  << T << ArgRange;
3573  return true;
3574  }
3575 
3576  assert((T->isVoidType() || !T->isIncompleteType()) &&
3577  "Scalar types should always be complete");
3578  return false;
3579 }
3580 
3582  SourceLocation Loc,
3583  SourceRange ArgRange,
3584  UnaryExprOrTypeTrait TraitKind) {
3585  // Invalid types must be hard errors for SFINAE in C++.
3586  if (S.LangOpts.CPlusPlus)
3587  return true;
3588 
3589  // C99 6.5.3.4p1:
3590  if (T->isFunctionType() &&
3591  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3592  // sizeof(function)/alignof(function) is allowed as an extension.
3593  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3594  << TraitKind << ArgRange;
3595  return false;
3596  }
3597 
3598  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3599  // this is an error (OpenCL v1.1 s6.3.k)
3600  if (T->isVoidType()) {
3601  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3602  : diag::ext_sizeof_alignof_void_type;
3603  S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3604  return false;
3605  }
3606 
3607  return true;
3608 }
3609 
3611  SourceLocation Loc,
3612  SourceRange ArgRange,
3613  UnaryExprOrTypeTrait TraitKind) {
3614  // Reject sizeof(interface) and sizeof(interface<proto>) if the
3615  // runtime doesn't allow it.
3617  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3618  << T << (TraitKind == UETT_SizeOf)
3619  << ArgRange;
3620  return true;
3621  }
3622 
3623  return false;
3624 }
3625 
3626 /// Check whether E is a pointer from a decayed array type (the decayed
3627 /// pointer type is equal to T) and emit a warning if it is.
3629  Expr *E) {
3630  // Don't warn if the operation changed the type.
3631  if (T != E->getType())
3632  return;
3633 
3634  // Now look for array decays.
3635  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3636  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3637  return;
3638 
3639  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3640  << ICE->getType()
3641  << ICE->getSubExpr()->getType();
3642 }
3643 
3644 /// Check the constraints on expression operands to unary type expression
3645 /// and type traits.
3646 ///
3647 /// Completes any types necessary and validates the constraints on the operand
3648 /// expression. The logic mostly mirrors the type-based overload, but may modify
3649 /// the expression as it completes the type for that expression through template
3650 /// instantiation, etc.
3652  UnaryExprOrTypeTrait ExprKind) {
3653  QualType ExprTy = E->getType();
3654  assert(!ExprTy->isReferenceType());
3655 
3656  if (ExprKind == UETT_VecStep)
3657  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3658  E->getSourceRange());
3659 
3660  // Whitelist some types as extensions
3661  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3662  E->getSourceRange(), ExprKind))
3663  return false;
3664 
3665  // 'alignof' applied to an expression only requires the base element type of
3666  // the expression to be complete. 'sizeof' requires the expression's type to
3667  // be complete (and will attempt to complete it if it's an array of unknown
3668  // bound).
3669  if (ExprKind == UETT_AlignOf) {
3670  if (RequireCompleteType(E->getExprLoc(),
3671  Context.getBaseElementType(E->getType()),
3672  diag::err_sizeof_alignof_incomplete_type, ExprKind,
3673  E->getSourceRange()))
3674  return true;
3675  } else {
3676  if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3677  ExprKind, E->getSourceRange()))
3678  return true;
3679  }
3680 
3681  // Completing the expression's type may have changed it.
3682  ExprTy = E->getType();
3683  assert(!ExprTy->isReferenceType());
3684 
3685  if (ExprTy->isFunctionType()) {
3686  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3687  << ExprKind << E->getSourceRange();
3688  return true;
3689  }
3690 
3691  // The operand for sizeof and alignof is in an unevaluated expression context,
3692  // so side effects could result in unintended consequences.
3693  if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3694  !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3695  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3696 
3697  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3698  E->getSourceRange(), ExprKind))
3699  return true;
3700 
3701  if (ExprKind == UETT_SizeOf) {
3702  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3703  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3704  QualType OType = PVD->getOriginalType();
3705  QualType Type = PVD->getType();
3706  if (Type->isPointerType() && OType->isArrayType()) {
3707  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3708  << Type << OType;
3709  Diag(PVD->getLocation(), diag::note_declared_at);
3710  }
3711  }
3712  }
3713 
3714  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3715  // decays into a pointer and returns an unintended result. This is most
3716  // likely a typo for "sizeof(array) op x".
3717  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3718  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3719  BO->getLHS());
3720  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3721  BO->getRHS());
3722  }
3723  }
3724 
3725  return false;
3726 }
3727 
3728 /// Check the constraints on operands to unary expression and type
3729 /// traits.
3730 ///
3731 /// This will complete any types necessary, and validate the various constraints
3732 /// on those operands.
3733 ///
3734 /// The UsualUnaryConversions() function is *not* called by this routine.
3735 /// C99 6.3.2.1p[2-4] all state:
3736 /// Except when it is the operand of the sizeof operator ...
3737 ///
3738 /// C++ [expr.sizeof]p4
3739 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3740 /// standard conversions are not applied to the operand of sizeof.
3741 ///
3742 /// This policy is followed for all of the unary trait expressions.
3744  SourceLocation OpLoc,
3745  SourceRange ExprRange,
3746  UnaryExprOrTypeTrait ExprKind) {
3747  if (ExprType->isDependentType())
3748  return false;
3749 
3750  // C++ [expr.sizeof]p2:
3751  // When applied to a reference or a reference type, the result
3752  // is the size of the referenced type.
3753  // C++11 [expr.alignof]p3:
3754  // When alignof is applied to a reference type, the result
3755  // shall be the alignment of the referenced type.
3756  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3757  ExprType = Ref->getPointeeType();
3758 
3759  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3760  // When alignof or _Alignof is applied to an array type, the result
3761  // is the alignment of the element type.
3762  if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3763  ExprType = Context.getBaseElementType(ExprType);
3764 
3765  if (ExprKind == UETT_VecStep)
3766  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3767 
3768  // Whitelist some types as extensions
3769  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3770  ExprKind))
3771  return false;
3772 
3773  if (RequireCompleteType(OpLoc, ExprType,
3774  diag::err_sizeof_alignof_incomplete_type,
3775  ExprKind, ExprRange))
3776  return true;
3777 
3778  if (ExprType->isFunctionType()) {
3779  Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3780  << ExprKind << ExprRange;
3781  return true;
3782  }
3783 
3784  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3785  ExprKind))
3786  return true;
3787 
3788  return false;
3789 }
3790 
3791 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3792  E = E->IgnoreParens();
3793 
3794  // Cannot know anything else if the expression is dependent.
3795  if (E->isTypeDependent())
3796  return false;
3797 
3798  if (E->getObjectKind() == OK_BitField) {
3799  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3800  << 1 << E->getSourceRange();
3801  return true;
3802  }
3803 
3804  ValueDecl *D = nullptr;
3805  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3806  D = DRE->getDecl();
3807  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3808  D = ME->getMemberDecl();
3809  }
3810 
3811  // If it's a field, require the containing struct to have a
3812  // complete definition so that we can compute the layout.
3813  //
3814  // This can happen in C++11 onwards, either by naming the member
3815  // in a way that is not transformed into a member access expression
3816  // (in an unevaluated operand, for instance), or by naming the member
3817  // in a trailing-return-type.
3818  //
3819  // For the record, since __alignof__ on expressions is a GCC
3820  // extension, GCC seems to permit this but always gives the
3821  // nonsensical answer 0.
3822  //
3823  // We don't really need the layout here --- we could instead just
3824  // directly check for all the appropriate alignment-lowing
3825  // attributes --- but that would require duplicating a lot of
3826  // logic that just isn't worth duplicating for such a marginal
3827  // use-case.
3828  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3829  // Fast path this check, since we at least know the record has a
3830  // definition if we can find a member of it.
3831  if (!FD->getParent()->isCompleteDefinition()) {
3832  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3833  << E->getSourceRange();
3834  return true;
3835  }
3836 
3837  // Otherwise, if it's a field, and the field doesn't have
3838  // reference type, then it must have a complete type (or be a
3839  // flexible array member, which we explicitly want to
3840  // white-list anyway), which makes the following checks trivial.
3841  if (!FD->getType()->isReferenceType())
3842  return false;
3843  }
3844 
3846 }
3847 
3849  E = E->IgnoreParens();
3850 
3851  // Cannot know anything else if the expression is dependent.
3852  if (E->isTypeDependent())
3853  return false;
3854 
3855  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3856 }
3857 
3859  CapturingScopeInfo *CSI) {
3860  assert(T->isVariablyModifiedType());
3861  assert(CSI != nullptr);
3862 
3863  // We're going to walk down into the type and look for VLA expressions.
3864  do {
3865  const Type *Ty = T.getTypePtr();
3866  switch (Ty->getTypeClass()) {
3867 #define TYPE(Class, Base)
3868 #define ABSTRACT_TYPE(Class, Base)
3869 #define NON_CANONICAL_TYPE(Class, Base)
3870 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3871 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3872 #include "clang/AST/TypeNodes.def"
3873  T = QualType();
3874  break;
3875  // These types are never variably-modified.
3876  case Type::Builtin:
3877  case Type::Complex:
3878  case Type::Vector:
3879  case Type::ExtVector:
3880  case Type::Record:
3881  case Type::Enum:
3882  case Type::Elaborated:
3883  case Type::TemplateSpecialization:
3884  case Type::ObjCObject:
3885  case Type::ObjCInterface:
3886  case Type::ObjCObjectPointer:
3887  case Type::ObjCTypeParam:
3888  case Type::Pipe:
3889  llvm_unreachable("type class is never variably-modified!");
3890  case Type::Adjusted:
3891  T = cast<AdjustedType>(Ty)->getOriginalType();
3892  break;
3893  case Type::Decayed:
3894  T = cast<DecayedType>(Ty)->getPointeeType();
3895  break;
3896  case Type::Pointer:
3897  T = cast<PointerType>(Ty)->getPointeeType();
3898  break;
3899  case Type::BlockPointer:
3900  T = cast<BlockPointerType>(Ty)->getPointeeType();
3901  break;
3902  case Type::LValueReference:
3903  case Type::RValueReference:
3904  T = cast<ReferenceType>(Ty)->getPointeeType();
3905  break;
3906  case Type::MemberPointer:
3907  T = cast<MemberPointerType>(Ty)->getPointeeType();
3908  break;
3909  case Type::ConstantArray:
3910  case Type::IncompleteArray:
3911  // Losing element qualification here is fine.
3912  T = cast<ArrayType>(Ty)->getElementType();
3913  break;
3914  case Type::VariableArray: {
3915  // Losing element qualification here is fine.
3916  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3917 
3918  // Unknown size indication requires no size computation.
3919  // Otherwise, evaluate and record it.
3920  if (auto Size = VAT->getSizeExpr()) {
3921  if (!CSI->isVLATypeCaptured(VAT)) {
3922  RecordDecl *CapRecord = nullptr;
3923  if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3924  CapRecord = LSI->Lambda;
3925  } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3926  CapRecord = CRSI->TheRecordDecl;
3927  }
3928  if (CapRecord) {
3929  auto ExprLoc = Size->getExprLoc();
3930  auto SizeType = Context.getSizeType();
3931  // Build the non-static data member.
3932  auto Field =
3933  FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3934  /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3935  /*BW*/ nullptr, /*Mutable*/ false,
3936  /*InitStyle*/ ICIS_NoInit);
3937  Field->setImplicit(true);
3938  Field->setAccess(AS_private);
3939  Field->setCapturedVLAType(VAT);
3940  CapRecord->addDecl(Field);
3941 
3942  CSI->addVLATypeCapture(ExprLoc, SizeType);
3943  }
3944  }
3945  }
3946  T = VAT->getElementType();
3947  break;
3948  }
3949  case Type::FunctionProto:
3950  case Type::FunctionNoProto:
3951  T = cast<FunctionType>(Ty)->getReturnType();
3952  break;
3953  case Type::Paren:
3954  case Type::TypeOf:
3955  case Type::UnaryTransform:
3956  case Type::Attributed:
3957  case Type::SubstTemplateTypeParm:
3958  case Type::PackExpansion:
3959  // Keep walking after single level desugaring.
3960  T = T.getSingleStepDesugaredType(Context);
3961  break;
3962  case Type::Typedef:
3963  T = cast<TypedefType>(Ty)->desugar();
3964  break;
3965  case Type::Decltype:
3966  T = cast<DecltypeType>(Ty)->desugar();
3967  break;
3968  case Type::Auto:
3969  case Type::DeducedTemplateSpecialization:
3970  T = cast<DeducedType>(Ty)->getDeducedType();
3971  break;
3972  case Type::TypeOfExpr:
3973  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3974  break;
3975  case Type::Atomic:
3976  T = cast<AtomicType>(Ty)->getValueType();
3977  break;
3978  }
3979  } while (!T.isNull() && T->isVariablyModifiedType());
3980 }
3981 
3982 /// Build a sizeof or alignof expression given a type operand.
3983 ExprResult
3985  SourceLocation OpLoc,
3986  UnaryExprOrTypeTrait ExprKind,
3987  SourceRange R) {
3988  if (!TInfo)
3989  return ExprError();
3990 
3991  QualType T = TInfo->getType();
3992 
3993  if (!T->isDependentType() &&
3994  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3995  return ExprError();
3996 
3997  if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3998  if (auto *TT = T->getAs<TypedefType>()) {
3999  for (auto I = FunctionScopes.rbegin(),
4000  E = std::prev(FunctionScopes.rend());
4001  I != E; ++I) {
4002  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4003  if (CSI == nullptr)
4004  break;
4005  DeclContext *DC = nullptr;
4006  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4007  DC = LSI->CallOperator;
4008  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4009  DC = CRSI->TheCapturedDecl;
4010  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4011  DC = BSI->TheDecl;
4012  if (DC) {
4013  if (DC->containsDecl(TT->getDecl()))
4014  break;
4015  captureVariablyModifiedType(Context, T, CSI);
4016  }
4017  }
4018  }
4019  }
4020 
4021  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4022  return new (Context) UnaryExprOrTypeTraitExpr(
4023  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4024 }
4025 
4026 /// Build a sizeof or alignof expression given an expression
4027 /// operand.
4028 ExprResult
4030  UnaryExprOrTypeTrait ExprKind) {
4031  ExprResult PE = CheckPlaceholderExpr(E);
4032  if (PE.isInvalid())
4033  return ExprError();
4034 
4035  E = PE.get();
4036 
4037  // Verify that the operand is valid.
4038  bool isInvalid = false;
4039  if (E->isTypeDependent()) {
4040  // Delay type-checking for type-dependent expressions.
4041  } else if (ExprKind == UETT_AlignOf) {
4042  isInvalid = CheckAlignOfExpr(*this, E);
4043  } else if (ExprKind == UETT_VecStep) {
4044  isInvalid = CheckVecStepExpr(E);
4045  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4046  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4047  isInvalid = true;
4048  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4049  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4050  isInvalid = true;
4051  } else {
4052  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4053  }
4054 
4055  if (isInvalid)
4056  return ExprError();
4057 
4058  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4059  PE = TransformToPotentiallyEvaluated(E);
4060  if (PE.isInvalid()) return ExprError();
4061  E = PE.get();
4062  }
4063 
4064  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4065  return new (Context) UnaryExprOrTypeTraitExpr(
4066  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4067 }
4068 
4069 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4070 /// expr and the same for @c alignof and @c __alignof
4071 /// Note that the ArgRange is invalid if isType is false.
4072 ExprResult
4074  UnaryExprOrTypeTrait ExprKind, bool IsType,
4075  void *TyOrEx, SourceRange ArgRange) {
4076  // If error parsing type, ignore.
4077  if (!TyOrEx) return ExprError();
4078 
4079  if (IsType) {
4080  TypeSourceInfo *TInfo;
4081  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4082  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4083  }
4084 
4085  Expr *ArgEx = (Expr *)TyOrEx;
4086  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4087  return Result;
4088 }
4089 
4091  bool IsReal) {
4092  if (V.get()->isTypeDependent())
4093  return S.Context.DependentTy;
4094 
4095  // _Real and _Imag are only l-values for normal l-values.
4096  if (V.get()->getObjectKind() != OK_Ordinary) {
4097  V = S.DefaultLvalueConversion(V.get());
4098  if (V.isInvalid())
4099  return QualType();
4100  }
4101 
4102  // These operators return the element type of a complex type.
4103  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4104  return CT->getElementType();
4105 
4106  // Otherwise they pass through real integer and floating point types here.
4107  if (V.get()->getType()->isArithmeticType())
4108  return V.get()->getType();
4109 
4110  // Test for placeholders.
4111  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4112  if (PR.isInvalid()) return QualType();
4113  if (PR.get() != V.get()) {
4114  V = PR;
4115  return CheckRealImagOperand(S, V, Loc, IsReal);
4116  }
4117 
4118  // Reject anything else.
4119  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4120  << (IsReal ? "__real" : "__imag");
4121  return QualType();
4122 }
4123 
4124 
4125 
4126 ExprResult
4128  tok::TokenKind Kind, Expr *Input) {
4129  UnaryOperatorKind Opc;
4130  switch (Kind) {
4131  default: llvm_unreachable("Unknown unary op!");
4132  case tok::plusplus: Opc = UO_PostInc; break;
4133  case tok::minusminus: Opc = UO_PostDec; break;
4134  }
4135 
4136  // Since this might is a postfix expression, get rid of ParenListExprs.
4137  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4138  if (Result.isInvalid()) return ExprError();
4139  Input = Result.get();
4140 
4141  return BuildUnaryOp(S, OpLoc, Opc, Input);
4142 }
4143 
4144 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4145 ///
4146 /// \return true on error
4148  SourceLocation opLoc,
4149  Expr *op) {
4150  assert(op->getType()->isObjCObjectPointerType());
4152  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4153  return false;
4154 
4155  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4156  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4157  << op->getSourceRange();
4158  return true;
4159 }
4160 
4162  auto *BaseNoParens = Base->IgnoreParens();
4163  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4164  return MSProp->getPropertyDecl()->getType()->isArrayType();
4165  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4166 }
4167 
4168 ExprResult
4170  Expr *idx, SourceLocation rbLoc) {
4171  if (base && !base->getType().isNull() &&
4172  base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4173  return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4174  /*Length=*/nullptr, rbLoc);
4175 
4176  // Since this might be a postfix expression, get rid of ParenListExprs.
4177  if (isa<ParenListExpr>(base)) {
4178  ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4179  if (result.isInvalid()) return ExprError();
4180  base = result.get();
4181  }
4182 
4183  // Handle any non-overload placeholder types in the base and index
4184  // expressions. We can't handle overloads here because the other
4185  // operand might be an overloadable type, in which case the overload
4186  // resolution for the operator overload should get the first crack
4187  // at the overload.
4188  bool IsMSPropertySubscript = false;
4189  if (base->getType()->isNonOverloadPlaceholderType()) {
4190  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4191  if (!IsMSPropertySubscript) {
4192  ExprResult result = CheckPlaceholderExpr(base);
4193  if (result.isInvalid())
4194  return ExprError();
4195  base = result.get();
4196  }
4197  }
4198  if (idx->getType()->isNonOverloadPlaceholderType()) {
4199  ExprResult result = CheckPlaceholderExpr(idx);
4200  if (result.isInvalid()) return ExprError();
4201  idx = result.get();
4202  }
4203 
4204  // Build an unanalyzed expression if either operand is type-dependent.
4205  if (getLangOpts().CPlusPlus &&
4206  (base->isTypeDependent() || idx->isTypeDependent())) {
4207  return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4208  VK_LValue, OK_Ordinary, rbLoc);
4209  }
4210 
4211  // MSDN, property (C++)
4212  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4213  // This attribute can also be used in the declaration of an empty array in a
4214  // class or structure definition. For example:
4215  // __declspec(property(get=GetX, put=PutX)) int x[];
4216  // The above statement indicates that x[] can be used with one or more array
4217  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4218  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4219  if (IsMSPropertySubscript) {
4220  // Build MS property subscript expression if base is MS property reference
4221  // or MS property subscript.
4222  return new (Context) MSPropertySubscriptExpr(
4223  base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4224  }
4225 
4226  // Use C++ overloaded-operator rules if either operand has record
4227  // type. The spec says to do this if either type is *overloadable*,
4228  // but enum types can't declare subscript operators or conversion
4229  // operators, so there's nothing interesting for overload resolution
4230  // to do if there aren't any record types involved.
4231  //
4232  // ObjC pointers have their own subscripting logic that is not tied
4233  // to overload resolution and so should not take this path.
4234  if (getLangOpts().CPlusPlus &&
4235  (base->getType()->isRecordType() ||
4236  (!base->getType()->isObjCObjectPointerType() &&
4237  idx->getType()->isRecordType()))) {
4238  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4239  }
4240 
4241  return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4242 }
4243 
4245  Expr *LowerBound,
4246  SourceLocation ColonLoc, Expr *Length,
4247  SourceLocation RBLoc) {
4248  if (Base->getType()->isPlaceholderType() &&
4250  BuiltinType::OMPArraySection)) {
4251  ExprResult Result = CheckPlaceholderExpr(Base);
4252  if (Result.isInvalid())
4253  return ExprError();
4254  Base = Result.get();
4255  }
4256  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4257  ExprResult Result = CheckPlaceholderExpr(LowerBound);
4258  if (Result.isInvalid())
4259  return ExprError();
4260  Result = DefaultLvalueConversion(Result.get());
4261  if (Result.isInvalid())
4262  return ExprError();
4263  LowerBound = Result.get();
4264  }
4265  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4266  ExprResult Result = CheckPlaceholderExpr(Length);
4267  if (Result.isInvalid())
4268  return ExprError();
4269  Result = DefaultLvalueConversion(Result.get());
4270  if (Result.isInvalid())
4271  return ExprError();
4272  Length = Result.get();
4273  }
4274 
4275  // Build an unanalyzed expression if either operand is type-dependent.
4276  if (Base->isTypeDependent() ||
4277  (LowerBound &&
4278  (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4279  (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4280  return new (Context)
4281  OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4282  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4283  }
4284 
4285  // Perform default conversions.
4287  QualType ResultTy;
4288  if (OriginalTy->isAnyPointerType()) {
4289  ResultTy = OriginalTy->getPointeeType();
4290  } else if (OriginalTy->isArrayType()) {
4291  ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4292  } else {
4293  return ExprError(
4294  Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4295  << Base->getSourceRange());
4296  }
4297  // C99 6.5.2.1p1
4298  if (LowerBound) {
4299  auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4300  LowerBound);
4301  if (Res.isInvalid())
4302  return ExprError(Diag(LowerBound->getExprLoc(),
4303  diag::err_omp_typecheck_section_not_integer)
4304  << 0 << LowerBound->getSourceRange());
4305  LowerBound = Res.get();
4306 
4307  if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4308  LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4309  Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4310  << 0 << LowerBound->getSourceRange();
4311  }
4312  if (Length) {
4313  auto Res =
4314  PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4315  if (Res.isInvalid())
4316  return ExprError(Diag(Length->getExprLoc(),
4317  diag::err_omp_typecheck_section_not_integer)
4318  << 1 << Length->getSourceRange());
4319  Length = Res.get();
4320 
4321  if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4322  Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4323  Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4324  << 1 << Length->getSourceRange();
4325  }
4326 
4327  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4328  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4329  // type. Note that functions are not objects, and that (in C99 parlance)
4330  // incomplete types are not object types.
4331  if (ResultTy->isFunctionType()) {
4332  Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4333  << ResultTy << Base->getSourceRange();
4334  return ExprError();
4335  }
4336 
4337  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4338  diag::err_omp_section_incomplete_type, Base))
4339  return ExprError();
4340 
4341  if (LowerBound && !OriginalTy->isAnyPointerType()) {
4342  llvm::APSInt LowerBoundValue;
4343  if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4344  // OpenMP 4.5, [2.4 Array Sections]
4345  // The array section must be a subset of the original array.
4346  if (LowerBoundValue.isNegative()) {
4347  Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4348  << LowerBound->getSourceRange();
4349  return ExprError();
4350  }
4351  }
4352  }
4353 
4354  if (Length) {
4355  llvm::APSInt LengthValue;
4356  if (Length->EvaluateAsInt(LengthValue, Context)) {
4357  // OpenMP 4.5, [2.4 Array Sections]
4358  // The length must evaluate to non-negative integers.
4359  if (LengthValue.isNegative()) {
4360  Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4361  << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4362  << Length->getSourceRange();
4363  return ExprError();
4364  }
4365  }
4366  } else if (ColonLoc.isValid() &&
4367  (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4368  !OriginalTy->isVariableArrayType()))) {
4369  // OpenMP 4.5, [2.4 Array Sections]
4370  // When the size of the array dimension is not known, the length must be
4371  // specified explicitly.
4372  Diag(ColonLoc, diag::err_omp_section_length_undefined)
4373  << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4374  return ExprError();
4375  }
4376 
4377  if (!Base->getType()->isSpecificPlaceholderType(
4378  BuiltinType::OMPArraySection)) {
4379  ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4380  if (Result.isInvalid())
4381  return ExprError();
4382  Base = Result.get();
4383  }
4384  return new (Context)
4385  OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4386  VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4387 }
4388 
4389 ExprResult
4391  Expr *Idx, SourceLocation RLoc) {
4392  Expr *LHSExp = Base;
4393  Expr *RHSExp = Idx;
4394 
4395  ExprValueKind VK = VK_LValue;
4397 
4398  // Per C++ core issue 1213, the result is an xvalue if either operand is
4399  // a non-lvalue array, and an lvalue otherwise.
4400  if (getLangOpts().CPlusPlus11) {
4401  for (auto *Op : {LHSExp, RHSExp}) {
4402  Op = Op->IgnoreImplicit();
4403  if (Op->getType()->isArrayType() && !Op->isLValue())
4404  VK = VK_XValue;
4405  }
4406  }
4407 
4408  // Perform default conversions.
4409  if (!LHSExp->getType()->getAs<VectorType>()) {
4410  ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4411  if (Result.isInvalid())
4412  return ExprError();
4413  LHSExp = Result.get();
4414  }
4415  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4416  if (Result.isInvalid())
4417  return ExprError();
4418  RHSExp = Result.get();
4419 
4420  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4421 
4422  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4423  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4424  // in the subscript position. As a result, we need to derive the array base
4425  // and index from the expression types.
4426  Expr *BaseExpr, *IndexExpr;
4427  QualType ResultType;
4428  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4429  BaseExpr = LHSExp;
4430  IndexExpr = RHSExp;
4431  ResultType = Context.DependentTy;
4432  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4433  BaseExpr = LHSExp;
4434  IndexExpr = RHSExp;
4435  ResultType = PTy->getPointeeType();
4436  } else if (const ObjCObjectPointerType *PTy =
4437  LHSTy->getAs<ObjCObjectPointerType>()) {
4438  BaseExpr = LHSExp;
4439  IndexExpr = RHSExp;
4440 
4441  // Use custom logic if this should be the pseudo-object subscript
4442  // expression.
4443  if (!LangOpts.isSubscriptPointerArithmetic())
4444  return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4445  nullptr);
4446 
4447  ResultType = PTy->getPointeeType();
4448  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4449  // Handle the uncommon case of "123[Ptr]".
4450  BaseExpr = RHSExp;
4451  IndexExpr = LHSExp;
4452  ResultType = PTy->getPointeeType();
4453  } else if (const ObjCObjectPointerType *PTy =
4454  RHSTy->getAs<ObjCObjectPointerType>()) {
4455  // Handle the uncommon case of "123[Ptr]".
4456  BaseExpr = RHSExp;
4457  IndexExpr = LHSExp;
4458  ResultType = PTy->getPointeeType();
4459  if (!LangOpts.isSubscriptPointerArithmetic()) {
4460  Diag(LLoc, diag::err_subscript_nonfragile_interface)
4461  << ResultType << BaseExpr->getSourceRange();
4462  return ExprError();
4463  }
4464  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4465  BaseExpr = LHSExp; // vectors: V[123]
4466  IndexExpr = RHSExp;
4467  // We apply C++ DR1213 to vector subscripting too.
4468  if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4469  ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4470  if (Materialized.isInvalid())
4471  return ExprError();
4472  LHSExp = Materialized.get();
4473  }
4474  VK = LHSExp->getValueKind();
4475  if (VK != VK_RValue)
4476  OK = OK_VectorComponent;
4477 
4478  ResultType = VTy->getElementType();
4479  QualType BaseType = BaseExpr->getType();
4480  Qualifiers BaseQuals = BaseType.getQualifiers();
4481  Qualifiers MemberQuals = ResultType.getQualifiers();
4482  Qualifiers Combined = BaseQuals + MemberQuals;
4483  if (Combined != MemberQuals)
4484  ResultType = Context.getQualifiedType(ResultType, Combined);
4485  } else if (LHSTy->isArrayType()) {
4486  // If we see an array that wasn't promoted by
4487  // DefaultFunctionArrayLvalueConversion, it must be an array that
4488  // wasn't promoted because of the C90 rule that doesn't
4489  // allow promoting non-lvalue arrays. Warn, then
4490  // force the promotion here.
4491  Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4492  LHSExp->getSourceRange();
4493  LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4494  CK_ArrayToPointerDecay).get();
4495  LHSTy = LHSExp->getType();
4496 
4497  BaseExpr = LHSExp;
4498  IndexExpr = RHSExp;
4499  ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4500  } else if (RHSTy->isArrayType()) {
4501  // Same as previous, except for 123[f().a] case
4502  Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4503  RHSExp->getSourceRange();
4504  RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4505  CK_ArrayToPointerDecay).get();
4506  RHSTy = RHSExp->getType();
4507 
4508  BaseExpr = RHSExp;
4509  IndexExpr = LHSExp;
4510  ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4511  } else {
4512  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4513  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4514  }
4515  // C99 6.5.2.1p1
4516  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4517  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4518  << IndexExpr->getSourceRange());
4519 
4520  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4521  IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4522  && !IndexExpr->isTypeDependent())
4523  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4524 
4525  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4526  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4527  // type. Note that Functions are not objects, and that (in C99 parlance)
4528  // incomplete types are not object types.
4529  if (ResultType->isFunctionType()) {
4530  Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4531  << ResultType << BaseExpr->getSourceRange();
4532  return ExprError();
4533  }
4534 
4535  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4536  // GNU extension: subscripting on pointer to void
4537  Diag(LLoc, diag::ext_gnu_subscript_void_type)
4538  << BaseExpr->getSourceRange();
4539 
4540  // C forbids expressions of unqualified void type from being l-values.
4541  // See IsCForbiddenLValueType.
4542  if (!ResultType.hasQualifiers()) VK = VK_RValue;
4543  } else if (!ResultType->isDependentType() &&
4544  RequireCompleteType(LLoc, ResultType,
4545  diag::err_subscript_incomplete_type, BaseExpr))
4546  return ExprError();
4547 
4548  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4549  !ResultType.isCForbiddenLValueType());
4550 
4551  return new (Context)
4552  ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4553 }
4554 
4556  ParmVarDecl *Param) {
4557  if (Param->hasUnparsedDefaultArg()) {
4558  Diag(CallLoc,
4559  diag::err_use_of_default_argument_to_function_declared_later) <<
4560  FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4561  Diag(UnparsedDefaultArgLocs[Param],
4562  diag::note_default_argument_declared_here);
4563  return true;
4564  }
4565 
4566  if (Param->hasUninstantiatedDefaultArg()) {
4567  Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4568 
4570  *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4571 
4572  // Instantiate the expression.
4573  //
4574  // FIXME: Pass in a correct Pattern argument, otherwise
4575  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4576  //
4577  // template<typename T>
4578  // struct A {
4579  // static int FooImpl();
4580  //
4581  // template<typename Tp>
4582  // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4583  // // template argument list [[T], [Tp]], should be [[Tp]].
4584  // friend A<Tp> Foo(int a);
4585  // };
4586  //
4587  // template<typename T>
4588  // A<T> Foo(int a = A<T>::FooImpl());
4589  MultiLevelTemplateArgumentList MutiLevelArgList
4590  = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4591 
4592  InstantiatingTemplate Inst(*this, CallLoc, Param,
4593  MutiLevelArgList.getInnermost());
4594  if (Inst.isInvalid())
4595  return true;
4596  if (Inst.isAlreadyInstantiating()) {
4597  Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4598  Param->setInvalidDecl();
4599  return true;
4600  }
4601 
4602  ExprResult Result;
4603  {
4604  // C++ [dcl.fct.default]p5:
4605  // The names in the [default argument] expression are bound, and
4606  // the semantic constraints are checked, at the point where the
4607  // default argument expression appears.
4608  ContextRAII SavedContext(*this, FD);
4609  LocalInstantiationScope Local(*this);
4610  Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4611  /*DirectInit*/false);
4612  }
4613  if (Result.isInvalid())
4614  return true;
4615 
4616  // Check the expression as an initializer for the parameter.
4617  InitializedEntity Entity
4618  = InitializedEntity::InitializeParameter(Context, Param);
4621  /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4622  Expr *ResultE = Result.getAs<Expr>();
4623 
4624  InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4625  Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4626  if (Result.isInvalid())
4627  return true;
4628 
4629  Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4630  Param->getOuterLocStart());
4631  if (Result.isInvalid())
4632  return true;
4633 
4634  // Remember the instantiated default argument.
4635  Param->setDefaultArg(Result.getAs<Expr>());
4636  if (ASTMutationListener *L = getASTMutationListener()) {
4637  L->DefaultArgumentInstantiated(Param);
4638  }
4639  }
4640 
4641  // If the default argument expression is not set yet, we are building it now.
4642  if (!Param->hasInit()) {
4643  Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4644  Param->setInvalidDecl();
4645  return true;
4646  }
4647 
4648  // If the default expression creates temporaries, we need to
4649  // push them to the current stack of expression temporaries so they'll
4650  // be properly destroyed.
4651  // FIXME: We should really be rebuilding the default argument with new
4652  // bound temporaries; see the comment in PR5810.
4653  // We don't need to do that with block decls, though, because
4654  // blocks in default argument expression can never capture anything.
4655  if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4656  // Set the "needs cleanups" bit regardless of whether there are
4657  // any explicit objects.
4658  Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4659 
4660  // Append all the objects to the cleanup list. Right now, this
4661  // should always be a no-op, because blocks in default argument
4662  // expressions should never be able to capture anything.
4663  assert(!Init->getNumObjects() &&
4664  "default argument expression has capturing blocks?");
4665  }
4666 
4667  // We already type-checked the argument, so we know it works.
4668  // Just mark all of the declarations in this potentially-evaluated expression
4669  // as being "referenced".
4670  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4671  /*SkipLocalVariables=*/true);
4672  return false;
4673 }
4674 
4676  FunctionDecl *FD, ParmVarDecl *Param) {
4677  if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4678  return ExprError();
4679  return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4680 }
4681 
4684  Expr *Fn) {
4685  if (Proto && Proto->isVariadic()) {
4686  if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4687  return VariadicConstructor;
4688  else if (Fn && Fn->getType()->isBlockPointerType())
4689  return VariadicBlock;
4690  else if (FDecl) {
4691  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4692  if (Method->isInstance())
4693  return VariadicMethod;
4694  } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4695  return VariadicMethod;
4696  return VariadicFunction;
4697  }
4698  return VariadicDoesNotApply;
4699 }
4700 
4701 namespace {
4702 class FunctionCallCCC : public FunctionCallFilterCCC {
4703 public:
4704  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4705  unsigned NumArgs, MemberExpr *ME)
4706  : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4707  FunctionName(FuncName) {}
4708 
4709  bool ValidateCandidate(const TypoCorrection &candidate) override {
4710  if (!candidate.getCorrectionSpecifier() ||
4711  candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4712  return false;
4713  }
4714 
4715  return FunctionCallFilterCCC::ValidateCandidate(candidate);
4716  }
4717 
4718 private:
4719  const IdentifierInfo *const FunctionName;
4720 };
4721 }
4722 
4724  FunctionDecl *FDecl,
4725  ArrayRef<Expr *> Args) {
4726  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4727  DeclarationName FuncName = FDecl->getDeclName();
4728  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4729 
4730  if (TypoCorrection Corrected = S.CorrectTypo(
4731  DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4732  S.getScopeForContext(S.CurContext), nullptr,
4733  llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4734  Args.size(), ME),
4736  if (NamedDecl *ND = Corrected.getFoundDecl()) {
4737  if (Corrected.isOverloaded()) {
4740  for (NamedDecl *CD : Corrected) {
4741  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4742  S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4743  OCS);
4744  }
4745  switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4746  case OR_Success:
4747  ND = Best->FoundDecl;
4748  Corrected.setCorrectionDecl(ND);
4749  break;
4750  default:
4751  break;
4752  }
4753  }
4754  ND = ND->getUnderlyingDecl();
4755  if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4756  return Corrected;
4757  }
4758  }
4759  return TypoCorrection();
4760 }
4761 
4762 /// ConvertArgumentsForCall - Converts the arguments specified in
4763 /// Args/NumArgs to the parameter types of the function FDecl with
4764 /// function prototype Proto. Call is the call expression itself, and
4765 /// Fn is the function expression. For a C++ member function, this
4766 /// routine does not attempt to convert the object argument. Returns
4767 /// true if the call is ill-formed.
4768 bool
4770  FunctionDecl *FDecl,
4771  const FunctionProtoType *Proto,
4772  ArrayRef<Expr *> Args,
4773  SourceLocation RParenLoc,
4774  bool IsExecConfig) {
4775  // Bail out early if calling a builtin with custom typechecking.
4776  if (FDecl)
4777  if (unsigned ID = FDecl->getBuiltinID())
4778  if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4779  return false;
4780 
4781  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4782  // assignment, to the types of the corresponding parameter, ...
4783  unsigned NumParams = Proto->getNumParams();
4784  bool Invalid = false;
4785  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4786  unsigned FnKind = Fn->getType()->isBlockPointerType()
4787  ? 1 /* block */
4788  : (IsExecConfig ? 3 /* kernel function (exec config) */
4789  : 0 /* function */);
4790 
4791  // If too few arguments are available (and we don't have default
4792  // arguments for the remaining parameters), don't make the call.
4793  if (Args.size() < NumParams) {
4794  if (Args.size() < MinArgs) {
4795  TypoCorrection TC;
4796  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4797  unsigned diag_id =
4798  MinArgs == NumParams && !Proto->isVariadic()
4799  ? diag::err_typecheck_call_too_few_args_suggest
4800  : diag::err_typecheck_call_too_few_args_at_least_suggest;
4801  diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4802  << static_cast<unsigned>(Args.size())
4803  << TC.getCorrectionRange());
4804  } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4805  Diag(RParenLoc,
4806  MinArgs == NumParams && !Proto->isVariadic()
4807  ? diag::err_typecheck_call_too_few_args_one
4808  : diag::err_typecheck_call_too_few_args_at_least_one)
4809  << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4810  else
4811  Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4812  ? diag::err_typecheck_call_too_few_args
4813  : diag::err_typecheck_call_too_few_args_at_least)
4814  << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4815  << Fn->getSourceRange();
4816 
4817  // Emit the location of the prototype.
4818  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4819  Diag(FDecl->getLocStart(), diag::note_callee_decl)
4820  << FDecl;
4821 
4822  return true;
4823  }
4824  Call->setNumArgs(Context, NumParams);
4825  }
4826 
4827  // If too many are passed and not variadic, error on the extras and drop
4828  // them.
4829  if (Args.size() > NumParams) {
4830  if (!Proto->isVariadic()) {
4831  TypoCorrection TC;
4832  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4833  unsigned diag_id =
4834  MinArgs == NumParams && !Proto->isVariadic()
4835  ? diag::err_typecheck_call_too_many_args_suggest
4836  : diag::err_typecheck_call_too_many_args_at_most_suggest;
4837  diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4838  << static_cast<unsigned>(Args.size())
4839  << TC.getCorrectionRange());
4840  } else if (NumParams == 1 && FDecl &&
4841  FDecl->getParamDecl(0)->getDeclName())
4842  Diag(Args[NumParams]->getLocStart(),
4843  MinArgs == NumParams
4844  ? diag::err_typecheck_call_too_many_args_one
4845  : diag::err_typecheck_call_too_many_args_at_most_one)
4846  << FnKind << FDecl->getParamDecl(0)
4847  << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4848  << SourceRange(Args[NumParams]->getLocStart(),
4849  Args.back()->getLocEnd());
4850  else
4851  Diag(Args[NumParams]->getLocStart(),
4852  MinArgs == NumParams
4853  ? diag::err_typecheck_call_too_many_args
4854  : diag::err_typecheck_call_too_many_args_at_most)
4855  << FnKind << NumParams << static_cast<unsigned>(Args.size())
4856  << Fn->getSourceRange()
4857  << SourceRange(Args[NumParams]->getLocStart(),
4858  Args.back()->getLocEnd());
4859 
4860  // Emit the location of the prototype.
4861  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4862  Diag(FDecl->getLocStart(), diag::note_callee_decl)
4863  << FDecl;
4864 
4865  // This deletes the extra arguments.
4866  Call->setNumArgs(Context, NumParams);
4867  return true;
4868  }
4869  }
4870  SmallVector<Expr *, 8> AllArgs;
4871  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4872 
4873  Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4874  Proto, 0, Args, AllArgs, CallType);
4875  if (Invalid)
4876  return true;
4877  unsigned TotalNumArgs = AllArgs.size();
4878  for (unsigned i = 0; i < TotalNumArgs; ++i)
4879  Call->setArg(i, AllArgs[i]);
4880 
4881  return false;
4882 }
4883 
4885  const FunctionProtoType *Proto,
4886  unsigned FirstParam, ArrayRef<Expr *> Args,
4887  SmallVectorImpl<Expr *> &AllArgs,
4888  VariadicCallType CallType, bool AllowExplicit,
4889  bool IsListInitialization) {
4890  unsigned NumParams = Proto->getNumParams();
4891  bool Invalid = false;
4892  size_t ArgIx = 0;
4893  // Continue to check argument types (even if we have too few/many args).
4894  for (unsigned i = FirstParam; i < NumParams; i++) {
4895  QualType ProtoArgType = Proto->getParamType(i);
4896 
4897  Expr *Arg;
4898  ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4899  if (ArgIx < Args.size()) {
4900  Arg = Args[ArgIx++];
4901 
4902  if (RequireCompleteType(Arg->getLocStart(),
4903  ProtoArgType,
4904  diag::err_call_incomplete_argument, Arg))
4905  return true;
4906 
4907  // Strip the unbridged-cast placeholder expression off, if applicable.
4908  bool CFAudited = false;
4909  if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4910  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4911  (!Param || !Param->hasAttr<CFConsumedAttr>()))
4912  Arg = stripARCUnbridgedCast(Arg);
4913  else if (getLangOpts().ObjCAutoRefCount &&
4914  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4915  (!Param || !Param->hasAttr<CFConsumedAttr>()))
4916  CFAudited = true;
4917 
4918  if (Proto->getExtParameterInfo(i).isNoEscape())
4919  if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4920  BE->getBlockDecl()->setDoesNotEscape();
4921 
4922  InitializedEntity Entity =
4923  Param ? InitializedEntity::InitializeParameter(Context, Param,
4924  ProtoArgType)
4926  Context, ProtoArgType, Proto->isParamConsumed(i));
4927 
4928  // Remember that parameter belongs to a CF audited API.
4929  if (CFAudited)
4930  Entity.setParameterCFAudited();
4931 
4932  ExprResult ArgE = PerformCopyInitialization(
4933  Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4934  if (ArgE.isInvalid())
4935  return true;
4936 
4937  Arg = ArgE.getAs<Expr>();
4938  } else {
4939  assert(Param && "can't use default arguments without a known callee");
4940 
4941  ExprResult ArgExpr =
4942  BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4943  if (ArgExpr.isInvalid())
4944  return true;
4945 
4946  Arg = ArgExpr.getAs<Expr>();
4947  }
4948 
4949  // Check for array bounds violations for each argument to the call. This
4950  // check only triggers warnings when the argument isn't a more complex Expr
4951  // with its own checking, such as a BinaryOperator.
4952  CheckArrayAccess(Arg);
4953 
4954  // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4955  CheckStaticArrayArgument(CallLoc, Param, Arg);
4956 
4957  AllArgs.push_back(Arg);
4958  }
4959 
4960  // If this is a variadic call, handle args passed through "...".
4961  if (CallType != VariadicDoesNotApply) {
4962  // Assume that extern "C" functions with variadic arguments that
4963  // return __unknown_anytype aren't *really* variadic.
4964  if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4965  FDecl->isExternC()) {
4966  for (Expr *A : Args.slice(ArgIx)) {
4967  QualType paramType; // ignored
4968  ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4969  Invalid |= arg.isInvalid();
4970  AllArgs.push_back(arg.get());
4971  }
4972 
4973  // Otherwise do argument promotion, (C99 6.5.2.2p7).
4974  } else {
4975  for (Expr *A : Args.slice(ArgIx)) {
4976  ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4977  Invalid |= Arg.isInvalid();
4978  AllArgs.push_back(Arg.get());
4979  }
4980  }
4981 
4982  // Check for array bounds violations.
4983  for (Expr *A : Args.slice(ArgIx))
4984  CheckArrayAccess(A);
4985  }
4986  return Invalid;
4987 }
4988 
4990  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4991  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4992  TL = DTL.getOriginalLoc();
4993  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4994  S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4995  << ATL.getLocalSourceRange();
4996 }
4997 
4998 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4999 /// array parameter, check that it is non-null, and that if it is formed by
5000 /// array-to-pointer decay, the underlying array is sufficiently large.
5001 ///
5002 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5003 /// array type derivation, then for each call to the function, the value of the
5004 /// corresponding actual argument shall provide access to the first element of
5005 /// an array with at least as many elements as specified by the size expression.
5006 void
5008  ParmVarDecl *Param,
5009  const Expr *ArgExpr) {
5010  // Static array parameters are not supported in C++.
5011  if (!Param || getLangOpts().CPlusPlus)
5012  return;
5013 
5014  QualType OrigTy = Param->getOriginalType();
5015 
5016  const ArrayType *AT = Context.getAsArrayType(OrigTy);
5017  if (!AT || AT->getSizeModifier() != ArrayType::Static)
5018  return;
5019 
5020  if (ArgExpr->isNullPointerConstant(Context,
5022  Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5023  DiagnoseCalleeStaticArrayParam(*this, Param);
5024  return;
5025  }
5026 
5027  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5028  if (!CAT)
5029  return;
5030 
5031  const ConstantArrayType *ArgCAT =
5032  Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5033  if (!ArgCAT)
5034  return;
5035 
5036  if (ArgCAT->getSize().ult(CAT->getSize())) {
5037  Diag(CallLoc, diag::warn_static_array_too_small)
5038  << ArgExpr->getSourceRange()
5039  << (unsigned) ArgCAT->getSize().getZExtValue()
5040  << (unsigned) CAT->getSize().getZExtValue();
5041  DiagnoseCalleeStaticArrayParam(*this, Param);
5042  }
5043 }
5044 
5045 /// Given a function expression of unknown-any type, try to rebuild it
5046 /// to have a function type.
5048 
5049 /// Is the given type a placeholder that we need to lower out
5050 /// immediately during argument processing?
5052  // Placeholders are never sugared.
5053  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5054  if (!placeholder) return false;
5055 
5056  switch (placeholder->getKind()) {
5057  // Ignore all the non-placeholder types.
5058 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5059  case BuiltinType::Id:
5060 #include "clang/Basic/OpenCLImageTypes.def"
5061 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5062 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5063 #include "clang/AST/BuiltinTypes.def"
5064  return false;
5065 
5066  // We cannot lower out overload sets; they might validly be resolved
5067  // by the call machinery.
5068  case BuiltinType::Overload:
5069  return false;
5070 
5071  // Unbridged casts in ARC can be handled in some call positions and
5072  // should be left in place.
5073  case BuiltinType::ARCUnbridgedCast:
5074  return false;
5075 
5076  // Pseudo-objects should be converted as soon as possible.
5077  case BuiltinType::PseudoObject:
5078  return true;
5079 
5080  // The debugger mode could theoretically but currently does not try
5081  // to resolve unknown-typed arguments based on known parameter types.
5082  case BuiltinType::UnknownAny:
5083  return true;
5084 
5085  // These are always invalid as call arguments and should be reported.
5086  case BuiltinType::BoundMember:
5087  case BuiltinType::BuiltinFn:
5088  case BuiltinType::OMPArraySection:
5089  return true;
5090 
5091  }
5092  llvm_unreachable("bad builtin type kind");
5093 }
5094 
5095 /// Check an argument list for placeholders that we won't try to
5096 /// handle later.
5098  // Apply this processing to all the arguments at once instead of
5099  // dying at the first failure.
5100  bool hasInvalid = false;
5101  for (size_t i = 0, e = args.size(); i != e; i++) {
5102  if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5103  ExprResult result = S.CheckPlaceholderExpr(args[i]);
5104  if (result.isInvalid()) hasInvalid = true;
5105  else args[i] = result.get();
5106  } else if (hasInvalid) {
5107  (void)S.CorrectDelayedTyposInExpr(args[i]);
5108  }
5109  }
5110  return hasInvalid;
5111 }
5112 
5113 /// If a builtin function has a pointer argument with no explicit address
5114 /// space, then it should be able to accept a pointer to any address
5115 /// space as input. In order to do this, we need to replace the
5116 /// standard builtin declaration with one that uses the same address space
5117 /// as the call.
5118 ///
5119 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5120 /// it does not contain any pointer arguments without
5121 /// an address space qualifer. Otherwise the rewritten
5122 /// FunctionDecl is returned.
5123 /// TODO: Handle pointer return types.
5125  const FunctionDecl *FDecl,
5126  MultiExprArg ArgExprs) {
5127 
5128  QualType DeclType = FDecl->getType();
5129  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5130 
5131  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5132  !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5133  return nullptr;
5134 
5135  bool NeedsNewDecl = false;
5136  unsigned i = 0;
5137  SmallVector<QualType, 8> OverloadParams;
5138 
5139  for (QualType ParamType : FT->param_types()) {
5140 
5141  // Convert array arguments to pointer to simplify type lookup.
5142  ExprResult ArgRes =
5143  Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5144  if (ArgRes.isInvalid())
5145  return nullptr;
5146  Expr *Arg = ArgRes.get();
5147  QualType ArgType = Arg->getType();
5148  if (!ParamType->isPointerType() ||
5149  ParamType.getQualifiers().hasAddressSpace() ||
5150  !ArgType->isPointerType() ||
5151  !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5152  OverloadParams.push_back(ParamType);
5153  continue;
5154  }
5155 
5156  NeedsNewDecl = true;
5157  LangAS AS = ArgType->getPointeeType().getAddressSpace();
5158 
5159  QualType PointeeType = ParamType->getPointeeType();
5160  PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5161  OverloadParams.push_back(Context.getPointerType(PointeeType));
5162  }
5163 
5164  if (!NeedsNewDecl)
5165  return nullptr;
5166 
5168  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5169  OverloadParams, EPI);
5171  FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5172  FDecl->getLocation(),
5173  FDecl->getLocation(),
5174  FDecl->getIdentifier(),
5175  OverloadTy,
5176  /*TInfo=*/nullptr,
5177  SC_Extern, false,
5178  /*hasPrototype=*/true);
5180  FT = cast<FunctionProtoType>(OverloadTy);
5181  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5182  QualType ParamType = FT->getParamType(i);
5183  ParmVarDecl *Parm =
5184  ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5185  SourceLocation(), nullptr, ParamType,
5186  /*TInfo=*/nullptr, SC_None, nullptr);
5187  Parm->setScopeInfo(0, i);
5188  Params.push_back(Parm);
5189  }
5190  OverloadDecl->setParams(Params);
5191  return OverloadDecl;
5192 }
5193 
5194 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5195  FunctionDecl *Callee,
5196  MultiExprArg ArgExprs) {
5197  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5198  // similar attributes) really don't like it when functions are called with an
5199  // invalid number of args.
5200  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5201  /*PartialOverloading=*/false) &&
5202  !Callee->isVariadic())
5203  return;
5204  if (Callee->getMinRequiredArguments() > ArgExprs.size())
5205  return;
5206 
5207  if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5208  S.Diag(Fn->getLocStart(),
5209  isa<CXXMethodDecl>(Callee)
5210  ? diag::err_ovl_no_viable_member_function_in_call
5211  : diag::err_ovl_no_viable_function_in_call)
5212  << Callee << Callee->getSourceRange();
5213  S.Diag(Callee->getLocation(),
5214  diag::note_ovl_candidate_disabled_by_function_cond_attr)
5215  << Attr->getCond()->getSourceRange() << Attr->getMessage();
5216  return;
5217  }
5218 }
5219 
5221  const UnresolvedMemberExpr *const UME, Sema &S) {
5222 
5223  const auto GetFunctionLevelDCIfCXXClass =
5224  [](Sema &S) -> const CXXRecordDecl * {
5225  const DeclContext *const DC = S.getFunctionLevelDeclContext();
5226  if (!DC || !DC->getParent())
5227  return nullptr;
5228 
5229  // If the call to some member function was made from within a member
5230  // function body 'M' return return 'M's parent.
5231  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5232  return MD->getParent()->getCanonicalDecl();
5233  // else the call was made from within a default member initializer of a
5234  // class, so return the class.
5235  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5236  return RD->getCanonicalDecl();
5237  return nullptr;
5238  };
5239  // If our DeclContext is neither a member function nor a class (in the
5240  // case of a lambda in a default member initializer), we can't have an
5241  // enclosing 'this'.
5242 
5243  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5244  if (!CurParentClass)
5245  return false;
5246 
5247  // The naming class for implicit member functions call is the class in which
5248  // name lookup starts.
5249  const CXXRecordDecl *const NamingClass =
5250  UME->getNamingClass()->getCanonicalDecl();
5251  assert(NamingClass && "Must have naming class even for implicit access");
5252 
5253  // If the unresolved member functions were found in a 'naming class' that is
5254  // related (either the same or derived from) to the class that contains the
5255  // member function that itself contained the implicit member access.
5256 
5257  return CurParentClass == NamingClass ||
5258  CurParentClass->isDerivedFrom(NamingClass);
5259 }
5260 
5261 static void
5263  Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5264 
5265  if (!UME)
5266  return;
5267 
5268  LambdaScopeInfo *const CurLSI = S.getCurLambda();
5269  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5270  // already been captured, or if this is an implicit member function call (if
5271  // it isn't, an attempt to capture 'this' should already have been made).
5272  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5273  !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5274  return;
5275 
5276  // Check if the naming class in which the unresolved members were found is
5277  // related (same as or is a base of) to the enclosing class.
5278 
5280  return;
5281 
5282 
5283  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5284  // If the enclosing function is not dependent, then this lambda is
5285  // capture ready, so if we can capture this, do so.
5286  if (!EnclosingFunctionCtx->isDependentContext()) {
5287  // If the current lambda and all enclosing lambdas can capture 'this' -
5288  // then go ahead and capture 'this' (since our unresolved overload set
5289  // contains at least one non-static member function).
5290  if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5291  S.CheckCXXThisCapture(CallLoc);
5292  } else if (S.CurContext->isDependentContext()) {
5293  // ... since this is an implicit member reference, that might potentially
5294  // involve a 'this' capture, mark 'this' for potential capture in
5295  // enclosing lambdas.
5296  if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5297  CurLSI->addPotentialThisCapture(CallLoc);
5298  }
5299 }
5300 
5301 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5302 /// This provides the location of the left/right parens and a list of comma
5303 /// locations.
5305  MultiExprArg ArgExprs, SourceLocation RParenLoc,
5306  Expr *ExecConfig, bool IsExecConfig) {
5307  // Since this might be a postfix expression, get rid of ParenListExprs.
5308  ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5309  if (Result.isInvalid()) return ExprError();
5310  Fn = Result.get();
5311 
5312  if (checkArgsForPlaceholders(*this, ArgExprs))
5313  return ExprError();
5314 
5315  if (getLangOpts().CPlusPlus) {
5316  // If this is a pseudo-destructor expression, build the call immediately.
5317  if (isa<CXXPseudoDestructorExpr>(Fn)) {
5318  if (!ArgExprs.empty()) {
5319  // Pseudo-destructor calls should not have any arguments.
5320  Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5322  SourceRange(ArgExprs.front()->getLocStart(),
5323  ArgExprs.back()->getLocEnd()));
5324  }
5325 
5326  return new (Context)
5327  CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5328  }
5329  if (Fn->getType() == Context.PseudoObjectTy) {
5330  ExprResult result = CheckPlaceholderExpr(Fn);
5331  if (result.isInvalid()) return ExprError();
5332  Fn = result.get();
5333  }
5334 
5335  // Determine whether this is a dependent call inside a C++ template,
5336  // in which case we won't do any semantic analysis now.
5337  bool Dependent = false;
5338  if (Fn->isTypeDependent())
5339  Dependent = true;
5340  else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5341  Dependent = true;
5342 
5343  if (Dependent) {
5344  if (ExecConfig) {
5345  return new (Context) CUDAKernelCallExpr(
5346  Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5347  Context.DependentTy, VK_RValue, RParenLoc);
5348  } else {
5349 
5351  *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5352  Fn->getLocStart());
5353 
5354  return new (Context) CallExpr(
5355  Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5356  }
5357  }
5358 
5359  // Determine whether this is a call to an object (C++ [over.call.object]).
5360  if (Fn->getType()->isRecordType())
5361  return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5362  RParenLoc);
5363 
5364  if (Fn->getType() == Context.UnknownAnyTy) {
5365  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5366  if (result.isInvalid()) return ExprError();
5367  Fn = result.get();
5368  }
5369 
5370  if (Fn->getType() == Context.BoundMemberTy) {
5371  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5372  RParenLoc);
5373  }
5374  }
5375 
5376  // Check for overloaded calls. This can happen even in C due to extensions.
5377  if (Fn->getType() == Context.OverloadTy) {
5379 
5380  // We aren't supposed to apply this logic if there's an '&' involved.
5381  if (!find.HasFormOfMemberPointer) {
5382  if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5383  return new (Context) CallExpr(
5384  Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5385  OverloadExpr *ovl = find.Expression;
5386  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5387  return BuildOverloadedCallExpr(
5388  Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5389  /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5390  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5391  RParenLoc);
5392  }
5393  }
5394 
5395  // If we're directly calling a function, get the appropriate declaration.
5396  if (Fn->getType() == Context.UnknownAnyTy) {
5397  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5398  if (result.isInvalid()) return ExprError();
5399  Fn = result.get();
5400  }
5401 
5402  Expr *NakedFn = Fn->IgnoreParens();
5403 
5404  bool CallingNDeclIndirectly = false;
5405  NamedDecl *NDecl = nullptr;
5406  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5407  if (UnOp->getOpcode() == UO_AddrOf) {
5408  CallingNDeclIndirectly = true;
5409  NakedFn = UnOp->getSubExpr()->IgnoreParens();
5410  }
5411  }
5412 
5413  if (isa<DeclRefExpr>(NakedFn)) {
5414  NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5415 
5416  FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5417  if (FDecl && FDecl->getBuiltinID()) {
5418  // Rewrite the function decl for this builtin by replacing parameters
5419  // with no explicit address space with the address space of the arguments
5420  // in ArgExprs.
5421  if ((FDecl =
5422  rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5423  NDecl = FDecl;
5424  Fn = DeclRefExpr::Create(
5425  Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5426  SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5427  }
5428  }
5429  } else if (isa<MemberExpr>(NakedFn))
5430  NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5431 
5432  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5433  if (CallingNDeclIndirectly &&
5434  !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5435  Fn->getLocStart()))
5436  return ExprError();
5437 
5438  if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5439  return ExprError();
5440 
5441  checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5442  }
5443 
5444  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5445  ExecConfig, IsExecConfig);
5446 }
5447 
5448 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5449 ///
5450 /// __builtin_astype( value, dst type )
5451 ///
5453  SourceLocation BuiltinLoc,
5454  SourceLocation RParenLoc) {
5455  ExprValueKind VK = VK_RValue;
5457  QualType DstTy = GetTypeFromParser(ParsedDestTy);
5458  QualType SrcTy = E->getType();
5459  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5460  return ExprError(Diag(BuiltinLoc,
5461  diag::err_invalid_astype_of_different_size)
5462  << DstTy
5463  << SrcTy
5464  << E->getSourceRange());
5465  return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5466 }
5467 
5468 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5469 /// provided arguments.
5470 ///
5471 /// __builtin_convertvector( value, dst type )
5472 ///
5474  SourceLocation BuiltinLoc,
5475  SourceLocation RParenLoc) {
5476  TypeSourceInfo *TInfo;
5477  GetTypeFromParser(ParsedDestTy, &TInfo);
5478  return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5479 }
5480 
5481 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5482 /// i.e. an expression not of \p OverloadTy. The expression should
5483 /// unary-convert to an expression of function-pointer or
5484 /// block-pointer type.
5485 ///
5486 /// \param NDecl the declaration being called, if available
5487 ExprResult
5489  SourceLocation LParenLoc,
5490  ArrayRef<Expr *> Args,
5491  SourceLocation RParenLoc,
5492  Expr *Config, bool IsExecConfig) {
5493  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5494  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5495 
5496  // Functions with 'interrupt' attribute cannot be called directly.
5497  if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5498  Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5499  return ExprError();
5500  }
5501 
5502  // Interrupt handlers don't save off the VFP regs automatically on ARM,
5503  // so there's some risk when calling out to non-interrupt handler functions
5504  // that the callee might not preserve them. This is easy to diagnose here,
5505  // but can be very challenging to debug.
5506  if (auto *Caller = getCurFunctionDecl())
5507  if (Caller->hasAttr<ARMInterruptAttr>()) {
5508  bool VFP = Context.getTargetInfo().hasFeature("vfp");
5509  if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5510  Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5511  }
5512 
5513  // Promote the function operand.
5514  // We special-case function promotion here because we only allow promoting
5515  // builtin functions to function pointers in the callee of a call.
5516  ExprResult Result;
5517  if (BuiltinID &&
5518  Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5519  Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5520  CK_BuiltinFnToFnPtr).get();
5521  } else {
5522  Result = CallExprUnaryConversions(Fn);
5523  }
5524  if (Result.isInvalid())
5525  return ExprError();
5526  Fn = Result.get();
5527 
5528  // Make the call expr early, before semantic checks. This guarantees cleanup
5529  // of arguments and function on error.
5530  CallExpr *TheCall;
5531  if (Config)
5532  TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5533  cast<CallExpr>(Config), Args,
5534  Context.BoolTy, VK_RValue,
5535  RParenLoc);
5536  else
5537  TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5538  VK_RValue, RParenLoc);
5539 
5540  if (!getLangOpts().CPlusPlus) {
5541  // C cannot always handle TypoExpr nodes in builtin calls and direct
5542  // function calls as their argument checking don't necessarily handle
5543  // dependent types properly, so make sure any TypoExprs have been
5544  // dealt with.
5545  ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5546  if (!Result.isUsable()) return ExprError();
5547  TheCall = dyn_cast<CallExpr>(Result.get());
5548  if (!TheCall) return Result;
5549  Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5550  }
5551 
5552  // Bail out early if calling a builtin with custom typechecking.
5553  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5554  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5555 
5556  retry:
5557  const FunctionType *FuncT;
5558  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5559  // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5560  // have type pointer to function".
5561  FuncT = PT->getPointeeType()->getAs<FunctionType>();
5562  if (!FuncT)
5563  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5564  << Fn->getType() << Fn->getSourceRange());
5565  } else if (const BlockPointerType *BPT =
5566  Fn->getType()->getAs<BlockPointerType>()) {
5567  FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5568  } else {
5569  // Handle calls to expressions of unknown-any type.
5570  if (Fn->getType() == Context.UnknownAnyTy) {
5571  ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5572  if (rewrite.isInvalid()) return ExprError();
5573  Fn = rewrite.get();
5574  TheCall->setCallee(Fn);
5575  goto retry;
5576  }
5577 
5578  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5579  << Fn->getType() << Fn->getSourceRange());
5580  }
5581 
5582  if (getLangOpts().CUDA) {
5583  if (Config) {
5584  // CUDA: Kernel calls must be to global functions
5585  if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5586  return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5587  << FDecl << Fn->getSourceRange());
5588 
5589  // CUDA: Kernel function must have 'void' return type
5590  if (!FuncT->getReturnType()->isVoidType())
5591  return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5592  << Fn->getType() << Fn->getSourceRange());
5593  } else {
5594  // CUDA: Calls to global functions must be configured
5595  if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5596  return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5597  << FDecl << Fn->getSourceRange());
5598  }
5599  }
5600 
5601  // Check for a valid return type
5602  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5603  FDecl))
5604  return ExprError();
5605 
5606  // We know the result type of the call, set it.
5607  TheCall->setType(FuncT->getCallResultType(Context));
5609 
5610  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5611  if (Proto) {
5612  if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5613  IsExecConfig))
5614  return ExprError();
5615  } else {
5616  assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5617 
5618  if (FDecl) {
5619  // Check if we have too few/too many template arguments, based
5620  // on our knowledge of the function definition.
5621  const FunctionDecl *Def = nullptr;
5622  if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5623  Proto = Def->getType()->getAs<FunctionProtoType>();
5624  if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5625  Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5626  << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5627  }
5628 
5629  // If the function we're calling isn't a function prototype, but we have
5630  // a function prototype from a prior declaratiom, use that prototype.
5631  if (!FDecl->hasPrototype())
5632  Proto = FDecl->getType()->getAs<FunctionProtoType>();
5633  }
5634 
5635  // Promote the arguments (C99 6.5.2.2p6).
5636  for (unsigned i = 0, e = Args.size(); i != e; i++) {
5637  Expr *Arg = Args[i];
5638 
5639  if (Proto && i < Proto->getNumParams()) {
5641  Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5642  ExprResult ArgE =
5643  PerformCopyInitialization(Entity, SourceLocation(), Arg);
5644  if (ArgE.isInvalid())
5645  return true;
5646 
5647  Arg = ArgE.getAs<Expr>();
5648 
5649  } else {
5650  ExprResult ArgE = DefaultArgumentPromotion(Arg);
5651 
5652  if (ArgE.isInvalid())
5653  return true;
5654 
5655  Arg = ArgE.getAs<Expr>();
5656  }
5657 
5658  if (RequireCompleteType(Arg->getLocStart(),
5659  Arg->getType(),
5660  diag::err_call_incomplete_argument, Arg))
5661  return ExprError();
5662 
5663  TheCall->setArg(i, Arg);
5664  }
5665  }
5666 
5667  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5668  if (!Method->isStatic())
5669  return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5670  << Fn->getSourceRange());
5671 
5672  // Check for sentinels
5673  if (NDecl)
5674  DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5675 
5676  // Do special checking on direct calls to functions.
5677  if (FDecl) {
5678  if (CheckFunctionCall(FDecl, TheCall, Proto))
5679  return ExprError();
5680 
5681  if (BuiltinID)
5682  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5683  } else if (NDecl) {
5684  if (CheckPointerCall(NDecl, TheCall, Proto))
5685  return ExprError();
5686  } else {
5687  if (CheckOtherCall(TheCall, Proto))
5688  return ExprError();
5689  }
5690 
5691  return MaybeBindToTemporary(TheCall);
5692 }
5693 
5694 ExprResult
5696  SourceLocation RParenLoc, Expr *InitExpr) {
5697  assert(Ty && "ActOnCompoundLiteral(): missing type");
5698  assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5699 
5700  TypeSourceInfo *TInfo;
5701  QualType literalType = GetTypeFromParser(Ty, &TInfo);
5702  if (!TInfo)
5703  TInfo = Context.getTrivialTypeSourceInfo(literalType);
5704 
5705  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5706 }
5707 
5708 ExprResult
5710  SourceLocation RParenLoc, Expr *LiteralExpr) {
5711  QualType literalType = TInfo->getType();
5712 
5713  if (literalType->isArrayType()) {
5714  if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5715  diag::err_illegal_decl_array_incomplete_type,
5716  SourceRange(LParenLoc,
5717  LiteralExpr->getSourceRange().getEnd())))
5718  return ExprError();
5719  if (literalType->isVariableArrayType())
5720  return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5721  << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5722  } else if (!literalType->isDependentType() &&
5723  RequireCompleteType(LParenLoc, literalType,
5724  diag::err_typecheck_decl_incomplete_type,
5725  SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5726  return ExprError();
5727 
5728  InitializedEntity Entity
5732  SourceRange(LParenLoc, RParenLoc),
5733  /*InitList=*/true);
5734  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5735  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5736  &literalType);
5737  if (Result.isInvalid())
5738  return ExprError();
5739  LiteralExpr = Result.get();
5740 
5741  bool isFileScope = !CurContext->isFunctionOrMethod();
5742  if (isFileScope &&
5743  !LiteralExpr->isTypeDependent() &&
5744  !LiteralExpr->isValueDependent() &&
5745  !literalType->isDependentType()) { // 6.5.2.5p3
5746  if (CheckForConstantInitializer(LiteralExpr, literalType))
5747  return ExprError();
5748  }
5749 
5750  // In C, compound literals are l-values for some reason.
5751  // For GCC compatibility, in C++, file-scope array compound literals with
5752  // constant initializers are also l-values, and compound literals are
5753  // otherwise prvalues.
5754  //
5755  // (GCC also treats C++ list-initialized file-scope array prvalues with
5756  // constant initializers as l-values, but that's non-conforming, so we don't
5757  // follow it there.)
5758  //
5759  // FIXME: It would be better to handle the lvalue cases as materializing and
5760  // lifetime-extending a temporary object, but our materialized temporaries
5761  // representation only supports lifetime extension from a variable, not "out
5762  // of thin air".
5763  // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5764  // is bound to the result of applying array-to-pointer decay to the compound
5765  // literal.
5766  // FIXME: GCC supports compound literals of reference type, which should
5767  // obviously have a value kind derived from the kind of reference involved.
5768  ExprValueKind VK =
5769  (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5770  ? VK_RValue
5771  : VK_LValue;
5772 
5773  return MaybeBindToTemporary(
5774  new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5775  VK, LiteralExpr, isFileScope));
5776 }
5777 
5778 ExprResult
5780  SourceLocation RBraceLoc) {
5781  // Immediately handle non-overload placeholders. Overloads can be
5782  // resolved contextually, but everything else here can't.
5783  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5784  if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5785  ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5786 
5787  // Ignore failures; dropping the entire initializer list because
5788  // of one failure would be terrible for indexing/etc.
5789  if (result.isInvalid()) continue;
5790 
5791  InitArgList[I] = result.get();
5792  }
5793  }
5794 
5795  // Semantic analysis for initializers is done by ActOnDeclarator() and
5796  // CheckInitializer() - it requires knowledge of the object being initialized.
5797 
5798  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5799  RBraceLoc);
5800  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5801  return E;
5802 }
5803 
5804 /// Do an explicit extend of the given block pointer if we're in ARC.
5806  assert(E.get()->getType()->isBlockPointerType());
5807  assert(E.get()->isRValue());
5808 
5809  // Only do this in an r-value context.
5810  if (!getLangOpts().ObjCAutoRefCount) return;
5811 
5812  E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5813  CK_ARCExtendBlockObject, E.get(),
5814  /*base path*/ nullptr, VK_RValue);
5815  Cleanup.setExprNeedsCleanups(true);
5816 }
5817 
5818 /// Prepare a conversion of the given expression to an ObjC object
5819 /// pointer type.
5821  QualType type = E.get()->getType();
5822  if (type->isObjCObjectPointerType()) {
5823  return CK_BitCast;
5824  } else if (type->isBlockPointerType()) {
5825  maybeExtendBlockObject(E);
5826  return CK_BlockPointerToObjCPointerCast;
5827  } else {
5828  assert(type->isPointerType());
5829  return CK_CPointerToObjCPointerCast;
5830  }
5831 }
5832 
5833 /// Prepares for a scalar cast, performing all the necessary stages
5834 /// except the final cast and returning the kind required.
5836  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5837  // Also, callers should have filtered out the invalid cases with
5838  // pointers. Everything else should be possible.
5839 
5840  QualType SrcTy = Src.get()->getType();
5841  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5842  return CK_NoOp;
5843 
5844  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5846  llvm_unreachable("member pointer type in C");
5847 
5848  case Type::STK_CPointer:
5851  switch (DestTy->getScalarTypeKind()) {
5852  case Type::STK_CPointer: {
5853  LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5854  LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5855  if (SrcAS != DestAS)
5856  return CK_AddressSpaceConversion;
5857  return CK_BitCast;
5858  }
5860  return (SrcKind == Type::STK_BlockPointer
5861  ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5863  if (SrcKind == Type::STK_ObjCObjectPointer)
5864  return CK_BitCast;
5865  if (SrcKind == Type::STK_CPointer)
5866  return CK_CPointerToObjCPointerCast;
5867  maybeExtendBlockObject(Src);
5868  return CK_BlockPointerToObjCPointerCast;
5869  case Type::STK_Bool:
5870  return CK_PointerToBoolean;
5871  case Type::STK_Integral:
5872  return CK_PointerToIntegral;
5873  case Type::STK_Floating:
5877  llvm_unreachable("illegal cast from pointer");
5878  }
5879  llvm_unreachable("Should have returned before this");
5880 
5881  case Type::STK_Bool: // casting from bool is like casting from an integer
5882  case Type::STK_Integral:
5883  switch (DestTy->getScalarTypeKind()) {
5884  case Type::STK_CPointer:
5887  if (Src.get()->isNullPointerConstant(Context,
5889  return CK_NullToPointer;
5890  return CK_IntegralToPointer;
5891  case Type::STK_Bool:
5892  return CK_IntegralToBoolean;
5893  case Type::STK_Integral:
5894  return CK_IntegralCast;
5895  case Type::STK_Floating:
5896  return CK_IntegralToFloating;
5898  Src = ImpCastExprToType(Src.get(),
5899  DestTy->castAs<ComplexType>()->getElementType(),
5900  CK_IntegralCast);
5901  return CK_IntegralRealToComplex;
5903  Src = ImpCastExprToType(Src.get(),
5904  DestTy->castAs<ComplexType>()->getElementType(),
5905  CK_IntegralToFloating);
5906  return CK_FloatingRealToComplex;
5908  llvm_unreachable("member pointer type in C");
5909  }
5910  llvm_unreachable("Should have returned before this");
5911 
5912  case Type::STK_Floating:
5913  switch (DestTy->getScalarTypeKind()) {
5914  case Type::STK_Floating:
5915  return CK_FloatingCast;
5916  case Type::STK_Bool:
5917  return CK_FloatingToBoolean;
5918  case Type::STK_Integral:
5919  return CK_FloatingToIntegral;
5921  Src = ImpCastExprToType(Src.get(),
5922  DestTy->castAs<ComplexType>()->getElementType(),
5923  CK_FloatingCast);
5924  return CK_FloatingRealToComplex;
5926  Src = ImpCastExprToType(Src.get(),
5927  DestTy->castAs<ComplexType>()->getElementType(),
5928  CK_FloatingToIntegral);
5929  return CK_IntegralRealToComplex;
5930  case Type::STK_CPointer:
5933  llvm_unreachable("valid float->pointer cast?");
5935  llvm_unreachable("member pointer type in C");
5936  }
5937  llvm_unreachable("Should have returned before this");
5938 
5940  switch (DestTy->getScalarTypeKind()) {
5942  return CK_FloatingComplexCast;
5944  return CK_FloatingComplexToIntegralComplex;
5945  case Type::STK_Floating: {
5946  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5947  if (Context.hasSameType(ET, DestTy))
5948  return CK_FloatingComplexToReal;
5949  Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5950  return CK_FloatingCast;
5951  }
5952  case Type::STK_Bool:
5953  return CK_FloatingComplexToBoolean;
5954  case Type::STK_Integral:
5955  Src = ImpCastExprToType(Src.get(),
5956  SrcTy->castAs<ComplexType>()->getElementType(),
5957  CK_FloatingComplexToReal);
5958  return CK_FloatingToIntegral;
5959  case Type::STK_CPointer:
5962  llvm_unreachable("valid complex float->pointer cast?");
5964  llvm_unreachable("member pointer type in C");
5965  }
5966  llvm_unreachable("Should have returned before this");
5967 
5969  switch (DestTy->getScalarTypeKind()) {
5971  return CK_IntegralComplexToFloatingComplex;
5973  return CK_IntegralComplexCast;
5974  case Type::STK_Integral: {
5975  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5976  if (Context.hasSameType(ET, DestTy))
5977  return CK_IntegralComplexToReal;
5978  Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5979  return CK_IntegralCast;
5980  }
5981  case Type::STK_Bool:
5982  return CK_IntegralComplexToBoolean;
5983  case Type::STK_Floating:
5984  Src = ImpCastExprToType(Src.get(),
5985  SrcTy->castAs<ComplexType>()->getElementType(),
5986  CK_IntegralComplexToReal);
5987  return CK_IntegralToFloating;
5988  case Type::STK_CPointer:
5991  llvm_unreachable("valid complex int->pointer cast?");
5993  llvm_unreachable("member pointer type in C");
5994  }
5995  llvm_unreachable("Should have returned before this");
5996  }
5997 
5998  llvm_unreachable("Unhandled scalar cast");
5999 }
6000 
6001 static bool breakDownVectorType(QualType type, uint64_t &len,
6002  QualType &eltType) {
6003  // Vectors are simple.
6004  if (const VectorType *vecType = type->getAs<VectorType>()) {
6005  len = vecType->getNumElements();
6006  eltType = vecType->getElementType();
6007  assert(eltType->isScalarType());
6008  return true;
6009  }
6010 
6011  // We allow lax conversion to and from non-vector types, but only if
6012  // they're real types (i.e. non-complex, non-pointer scalar types).
6013  if (!type->isRealType()) return false;
6014 
6015  len = 1;
6016  eltType = type;
6017  return true;
6018 }
6019 
6020 /// Are the two types lax-compatible vector types? That is, given
6021 /// that one of them is a vector, do they have equal storage sizes,
6022 /// where the storage size is the number of elements times the element
6023 /// size?
6024 ///
6025 /// This will also return false if either of the types is neither a
6026 /// vector nor a real type.
6028  assert(destTy->isVectorType() || srcTy->isVectorType());
6029 
6030  // Disallow lax conversions between scalars and ExtVectors (these
6031  // conversions are allowed for other vector types because common headers
6032  // depend on them). Most scalar OP ExtVector cases are handled by the
6033  // splat path anyway, which does what we want (convert, not bitcast).
6034  // What this rules out for ExtVectors is crazy things like char4*float.
6035  if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6036  if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6037 
6038  uint64_t srcLen, destLen;
6039  QualType srcEltTy, destEltTy;
6040  if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6041  if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6042 
6043  // ASTContext::getTypeSize will return the size rounded up to a
6044  // power of 2, so instead of using that, we need to use the raw
6045  // element size multiplied by the element count.
6046  uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6047  uint64_t destEltSize = Context.getTypeSize(destEltTy);
6048 
6049  return (srcLen * srcEltSize == destLen * destEltSize);
6050 }
6051 
6052 /// Is this a legal conversion between two types, one of which is
6053 /// known to be a vector type?
6055  assert(destTy->isVectorType() || srcTy->isVectorType());
6056 
6057  if (!Context.getLangOpts().LaxVectorConversions)
6058  return false;
6059  return areLaxCompatibleVectorTypes(srcTy, destTy);
6060 }
6061 
6063  CastKind &Kind) {
6064  assert(VectorTy->isVectorType() && "Not a vector type!");
6065 
6066  if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6067  if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6068  return Diag(R.getBegin(),
6069  Ty->isVectorType() ?
6070  diag::err_invalid_conversion_between_vectors :
6071  diag::err_invalid_conversion_between_vector_and_integer)
6072  << VectorTy << Ty << R;
6073  } else
6074  return Diag(R.getBegin(),
6075  diag::err_invalid_conversion_between_vector_and_scalar)
6076  << VectorTy << Ty << R;
6077 
6078  Kind = CK_BitCast;
6079  return false;
6080 }
6081 
6083  QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6084 
6085  if (DestElemTy == SplattedExpr->getType())
6086  return SplattedExpr;
6087 
6088  assert(DestElemTy->isFloatingType() ||
6089  DestElemTy->isIntegralOrEnumerationType());
6090 
6091  CastKind CK;
6092  if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6093  // OpenCL requires that we convert `true` boolean expressions to -1, but
6094  // only when splatting vectors.
6095  if (DestElemTy->isFloatingType()) {
6096  // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6097  // in two steps: boolean to signed integral, then to floating.
6098  ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6099  CK_BooleanToSignedIntegral);
6100  SplattedExpr = CastExprRes.get();
6101  CK = CK_IntegralToFloating;
6102  } else {
6103  CK = CK_BooleanToSignedIntegral;
6104  }
6105  } else {
6106  ExprResult CastExprRes = SplattedExpr;
6107  CK = PrepareScalarCast(CastExprRes, DestElemTy);
6108  if (CastExprRes.isInvalid())
6109  return ExprError();
6110  SplattedExpr = CastExprRes.get();
6111  }
6112  return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6113 }
6114 
6116  Expr *CastExpr, CastKind &Kind) {
6117  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6118 
6119  QualType SrcTy = CastExpr->getType();
6120 
6121  // If SrcTy is a VectorType, the total size must match to explicitly cast to
6122  // an ExtVectorType.
6123  // In OpenCL, casts between vectors of different types are not allowed.
6124  // (See OpenCL 6.2).
6125  if (SrcTy->isVectorType()) {
6126  if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6127  (getLangOpts().OpenCL &&
6128  !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6129  Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6130  << DestTy << SrcTy << R;
6131  return ExprError();
6132  }
6133  Kind = CK_BitCast;
6134  return CastExpr;
6135  }
6136 
6137  // All non-pointer scalars can be cast to ExtVector type. The appropriate
6138  // conversion will take place first from scalar to elt type, and then
6139  // splat from elt type to vector.
6140  if (SrcTy->isPointerType())
6141  return Diag(R.getBegin(),
6142  diag::err_invalid_conversion_between_vector_and_scalar)
6143  << DestTy << SrcTy << R;
6144 
6145  Kind = CK_VectorSplat;
6146  return prepareVectorSplat(DestTy, CastExpr);
6147 }
6148 
6149 ExprResult
6151  Declarator &D, ParsedType &Ty,
6152  SourceLocation RParenLoc, Expr *CastExpr) {
6153  assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6154  "ActOnCastExpr(): missing type or expr");
6155 
6156  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6157  if (D.isInvalidType())
6158  return ExprError();
6159 
6160  if (getLangOpts().CPlusPlus) {
6161  // Check that there are no default arguments (C++ only).
6162  CheckExtraCXXDefaultArguments(D);
6163  } else {
6164  // Make sure any TypoExprs have been dealt with.
6165  ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6166  if (!Res.isUsable())
6167  return ExprError();
6168  CastExpr = Res.get();
6169  }
6170 
6172 
6173  QualType castType = castTInfo->getType();
6174  Ty = CreateParsedType(castType, castTInfo);
6175 
6176  bool isVectorLiteral = false;
6177 
6178  // Check for an altivec or OpenCL literal,
6179  // i.e. all the elements are integer constants.
6180  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6181  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6182  if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6183  && castType->isVectorType() && (PE || PLE)) {
6184  if (PLE && PLE->getNumExprs() == 0) {
6185  Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6186  return ExprError();
6187  }
6188  if (PE || PLE->getNumExprs() == 1) {
6189  Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6190  if (!E->getType()->isVectorType())
6191  isVectorLiteral = true;
6192  }
6193  else
6194  isVectorLiteral = true;
6195  }
6196 
6197  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6198  // then handle it as such.
6199  if (isVectorLiteral)
6200  return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6201 
6202  // If the Expr being casted is a ParenListExpr, handle it specially.
6203  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6204  // sequence of BinOp comma operators.
6205  if (isa<ParenListExpr>(CastExpr)) {
6206  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6207  if (Result.isInvalid()) return ExprError();
6208  CastExpr = Result.get();
6209  }
6210 
6211  if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6212  !getSourceManager().isInSystemMacro(LParenLoc))
6213  Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6214 
6215  CheckTollFreeBridgeCast(castType, CastExpr);
6216 
6217  CheckObjCBridgeRelatedCast(castType, CastExpr);
6218 
6219  DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6220 
6221  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6222 }
6223 
6225  SourceLocation RParenLoc, Expr *E,
6226  TypeSourceInfo *TInfo) {
6227  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6228  "Expected paren or paren list expression");
6229 
6230  Expr **exprs;
6231  unsigned numExprs;
6232  Expr *subExpr;
6233  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6234  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6235  LiteralLParenLoc = PE->getLParenLoc();
6236  LiteralRParenLoc = PE->getRParenLoc();
6237  exprs = PE->getExprs();
6238  numExprs = PE->getNumExprs();
6239  } else { // isa<ParenExpr> by assertion at function entrance
6240  LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6241  LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6242  subExpr = cast<ParenExpr>(E)->getSubExpr();
6243  exprs = &subExpr;
6244  numExprs = 1;
6245  }
6246 
6247  QualType Ty = TInfo->getType();
6248  assert(Ty->isVectorType() && "Expected vector type");
6249 
6250  SmallVector<Expr *, 8> initExprs;
6251  const VectorType *VTy = Ty->getAs<VectorType>();
6252  unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6253 
6254  // '(...)' form of vector initialization in AltiVec: the number of
6255  // initializers must be one or must match the size of the vector.
6256  // If a single value is specified in the initializer then it will be
6257  // replicated to all the components of the vector
6258  if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6259  // The number of initializers must be one or must match the size of the
6260  // vector. If a single value is specified in the initializer then it will
6261  // be replicated to all the components of the vector
6262  if (numExprs == 1) {
6263  QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6264  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6265  if (Literal.isInvalid())
6266  return ExprError();
6267  Literal = ImpCastExprToType(Literal.get(), ElemTy,
6268  PrepareScalarCast(Literal, ElemTy));
6269  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6270  }
6271  else if (numExprs < numElems) {
6272  Diag(E->getExprLoc(),
6273  diag::err_incorrect_number_of_vector_initializers);
6274  return ExprError();
6275  }
6276  else
6277  initExprs.append(exprs, exprs + numExprs);
6278  }
6279  else {
6280  // For OpenCL, when the number of initializers is a single value,
6281  // it will be replicated to all components of the vector.
6282  if (getLangOpts().OpenCL &&
6284  numExprs == 1) {
6285  QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6286  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6287  if (Literal.isInvalid())
6288  return ExprError();
6289  Literal = ImpCastExprToType(Literal.get(), ElemTy,
6290  PrepareScalarCast(Literal, ElemTy));
6291  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6292  }
6293 
6294  initExprs.append(exprs, exprs + numExprs);
6295  }
6296  // FIXME: This means that pretty-printing the final AST will produce curly
6297  // braces instead of the original commas.
6298  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6299  initExprs, LiteralRParenLoc);
6300  initE->setType(Ty);
6301  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6302 }
6303 
6304 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6305 /// the ParenListExpr into a sequence of comma binary operators.
6306 ExprResult
6308  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6309  if (!E)
6310  return OrigExpr;
6311 
6312  ExprResult Result(E->getExpr(0));
6313 
6314  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6315  Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6316  E->getExpr(i));
6317 
6318  if (Result.isInvalid()) return ExprError();
6319 
6320  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6321 }
6322 
6324  SourceLocation R,
6325  MultiExprArg Val) {
6326  Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6327  return expr;
6328 }
6329 
6330 /// Emit a specialized diagnostic when one expression is a null pointer
6331 /// constant and the other is not a pointer. Returns true if a diagnostic is
6332 /// emitted.
6334  SourceLocation QuestionLoc) {
6335  Expr *NullExpr = LHSExpr;
6336  Expr *NonPointerExpr = RHSExpr;
6338  NullExpr->isNullPointerConstant(Context,
6340 
6341  if (NullKind == Expr::NPCK_NotNull) {
6342  NullExpr = RHSExpr;
6343  NonPointerExpr = LHSExpr;
6344  NullKind =
6345  NullExpr->isNullPointerConstant(Context,
6347  }
6348 
6349  if (NullKind == Expr::NPCK_NotNull)
6350  return false;
6351 
6352  if (NullKind == Expr::NPCK_ZeroExpression)
6353  return false;
6354 
6355  if (NullKind == Expr::NPCK_ZeroLiteral) {
6356  // In this case, check to make sure that we got here from a "NULL"
6357  // string in the source code.
6358  NullExpr = NullExpr->IgnoreParenImpCasts();
6359  SourceLocation loc = NullExpr->getExprLoc();
6360  if (!findMacroSpelling(loc, "NULL"))
6361  return false;
6362  }
6363 
6364  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6365  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6366  << NonPointerExpr->getType() << DiagType
6367  << NonPointerExpr->getSourceRange();
6368  return true;
6369 }
6370 
6371 /// Return false if the condition expression is valid, true otherwise.
6372 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6373  QualType CondTy = Cond->getType();
6374 
6375  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6376  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6377  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6378  << CondTy << Cond->getSourceRange();
6379  return true;
6380  }
6381 
6382  // C99 6.5.15p2
6383  if (CondTy->isScalarType()) return false;
6384 
6385  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6386  << CondTy << Cond->getSourceRange();
6387  return true;
6388 }
6389 
6390 /// Handle when one or both operands are void type.
6392  ExprResult &RHS) {
6393  Expr *LHSExpr = LHS.get();
6394  Expr *RHSExpr = RHS.get();
6395 
6396  if (!LHSExpr->getType()->isVoidType())
6397  S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6398  << RHSExpr->getSourceRange();
6399  if (!RHSExpr->getType()->isVoidType())
6400  S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6401  << LHSExpr->getSourceRange();
6402  LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6403  RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6404  return S.Context.VoidTy;
6405 }
6406 
6407 /// Return false if the NullExpr can be promoted to PointerTy,
6408 /// true otherwise.
6409 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6410  QualType PointerTy) {
6411  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6412  !NullExpr.get()->isNullPointerConstant(S.Context,
6414  return true;
6415 
6416  NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6417  return false;
6418 }
6419 
6420 /// Checks compatibility between two pointers and return the resulting
6421 /// type.
6423  ExprResult &RHS,
6424  SourceLocation Loc) {
6425  QualType LHSTy = LHS.get()->getType();
6426  QualType RHSTy = RHS.get()->getType();
6427 
6428  if (S.Context.hasSameType(LHSTy, RHSTy)) {
6429  // Two identical pointers types are always compatible.
6430  return LHSTy;
6431  }
6432 
6433  QualType lhptee, rhptee;
6434 
6435  // Get the pointee types.
6436  bool IsBlockPointer = false;
6437  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6438  lhptee = LHSBTy->getPointeeType();
6439  rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6440  IsBlockPointer = true;
6441  } else {
6442  lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6443  rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6444  }
6445 
6446  // C99 6.5.15p6: If both operands are pointers to compatible types or to
6447  // differently qualified versions of compatible types, the result type is
6448  // a pointer to an appropriately qualified version of the composite
6449  // type.
6450 
6451  // Only CVR-qualifiers exist in the standard, and the differently-qualified
6452  // clause doesn't make sense for our extensions. E.g. address space 2 should
6453  // be incompatible with address space 3: they may live on different devices or
6454  // anything.
6455  Qualifiers lhQual = lhptee.getQualifiers();
6456  Qualifiers rhQual = rhptee.getQualifiers();
6457 
6458  LangAS ResultAddrSpace = LangAS::Default;
6459  LangAS LAddrSpace = lhQual.getAddressSpace();
6460  LangAS RAddrSpace = rhQual.getAddressSpace();
6461  if (S.getLangOpts().OpenCL) {
6462  // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6463  // spaces is disallowed.
6464  if (lhQual.isAddressSpaceSupersetOf(rhQual))
6465  ResultAddrSpace = LAddrSpace;
6466  else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6467  ResultAddrSpace = RAddrSpace;
6468  else {
6469  S.Diag(Loc,
6470  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6471  << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6472  << RHS.get()->getSourceRange();
6473  return QualType();
6474  }
6475  }
6476 
6477  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6478  auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6479  lhQual.removeCVRQualifiers();
6480  rhQual.removeCVRQualifiers();
6481 
6482  // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6483  // (C99 6.7.3) for address spaces. We assume that the check should behave in
6484  // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6485  // qual types are compatible iff
6486  // * corresponded types are compatible
6487  // * CVR qualifiers are equal
6488  // * address spaces are equal
6489  // Thus for conditional operator we merge CVR and address space unqualified
6490  // pointees and if there is a composite type we return a pointer to it with
6491  // merged qualifiers.
6492  if (S.getLangOpts().OpenCL) {
6493  LHSCastKind = LAddrSpace == ResultAddrSpace
6494  ? CK_BitCast
6495  : CK_AddressSpaceConversion;
6496  RHSCastKind = RAddrSpace == ResultAddrSpace
6497  ? CK_BitCast
6498  : CK_AddressSpaceConversion;
6499  lhQual.removeAddressSpace();
6500  rhQual.removeAddressSpace();
6501  }
6502 
6503  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6504  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6505 
6506  QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6507 
6508  if (CompositeTy.isNull()) {
6509  // In this situation, we assume void* type. No especially good
6510  // reason, but this is what gcc does, and we do have to pick
6511  // to get a consistent AST.
6512  QualType incompatTy;
6513  incompatTy = S.Context.getPointerType(
6514  S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6515  LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6516  RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6517  // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6518  // for casts between types with incompatible address space qualifiers.
6519  // For the following code the compiler produces casts between global and
6520  // local address spaces of the corresponded innermost pointees:
6521  // local int *global *a;
6522  // global int *global *b;
6523  // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6524  S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6525  << LHSTy << RHSTy << LHS.get()->getSourceRange()
6526  << RHS.get()->getSourceRange();
6527  return incompatTy;
6528  }
6529 
6530  // The pointer types are compatible.
6531  // In case of OpenCL ResultTy should have the address space qualifier
6532  // which is a superset of address spaces of both the 2nd and the 3rd
6533  // operands of the conditional operator.
6534  QualType ResultTy = [&, ResultAddrSpace]() {
6535  if (S.getLangOpts().OpenCL) {
6536  Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6537  CompositeQuals.setAddressSpace(ResultAddrSpace);
6538  return S.Context
6539  .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6540  .withCVRQualifiers(MergedCVRQual);
6541  }
6542  return CompositeTy.withCVRQualifiers(MergedCVRQual);
6543  }();
6544  if (IsBlockPointer)
6545  ResultTy = S.Context.getBlockPointerType(ResultTy);
6546  else
6547  ResultTy = S.Context.getPointerType(ResultTy);
6548 
6549  LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6550  RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6551  return ResultTy;
6552 }
6553 
6554 /// Return the resulting type when the operands are both block pointers.
6556  ExprResult &LHS,
6557  ExprResult &RHS,
6558  SourceLocation Loc) {
6559  QualType LHSTy = LHS.get()->getType();
6560  QualType RHSTy = RHS.get()->getType();
6561 
6562  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6563  if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6564  QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6565  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6566  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6567  return destType;
6568  }
6569  S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6570  << LHSTy << RHSTy << LHS.get()->getSourceRange()
6571  << RHS.get()->getSourceRange();
6572  return QualType();
6573  }
6574 
6575  // We have 2 block pointer types.
6576  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6577 }
6578 
6579 /// Return the resulting type when the operands are both pointers.
6580 static QualType
6582  ExprResult &RHS,
6583  SourceLocation Loc) {
6584  // get the pointer types
6585  QualType LHSTy = LHS.get()->getType();
6586  QualType RHSTy = RHS.get()->getType();
6587 
6588  // get the "pointed to" types
6589  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6590  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6591 
6592  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6593  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6594  // Figure out necessary qualifiers (C99 6.5.15p6)
6595  QualType destPointee
6596  = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6597  QualType destType = S.Context.getPointerType(destPointee);
6598  // Add qualifiers if necessary.
6599  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6600  // Promote to void*.
6601  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6602  return destType;
6603  }
6604  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6605  QualType destPointee
6606  = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6607  QualType destType = S.Context.getPointerType(destPointee);
6608  // Add qualifiers if necessary.
6609  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6610  // Promote to void*.
6611  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6612  return destType;
6613  }
6614 
6615  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6616 }
6617 
6618 /// Return false if the first expression is not an integer and the second
6619 /// expression is not a pointer, true otherwise.
6621  Expr* PointerExpr, SourceLocation Loc,
6622  bool IsIntFirstExpr) {
6623  if (!PointerExpr->getType()->isPointerType() ||
6624  !Int.get()->getType()->isIntegerType())
6625  return false;
6626 
6627  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6628  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6629 
6630  S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6631  << Expr1->getType() << Expr2->getType()
6632  << Expr1->getSourceRange() << Expr2->getSourceRange();
6633  Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6634  CK_IntegralToPointer);
6635  return true;
6636 }
6637 
6638 /// Simple conversion between integer and floating point types.
6639 ///
6640 /// Used when handling the OpenCL conditional operator where the
6641 /// condition is a vector while the other operands are scalar.
6642 ///
6643 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6644 /// types are either integer or floating type. Between the two
6645 /// operands, the type with the higher rank is defined as the "result
6646 /// type". The other operand needs to be promoted to the same type. No
6647 /// other type promotion is allowed. We cannot use
6648 /// UsualArithmeticConversions() for this purpose, since it always
6649 /// promotes promotable types.
6651  ExprResult &RHS,
6652  SourceLocation QuestionLoc) {
6654  if (LHS.isInvalid())
6655  return QualType();
6657  if (RHS.isInvalid())
6658  return QualType();
6659 
6660  // For conversion purposes, we ignore any qualifiers.
6661  // For example, "const float" and "float" are equivalent.
6662  QualType LHSType =
6663  S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6664  QualType RHSType =
6665  S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6666 
6667  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6668  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6669  << LHSType << LHS.get()->getSourceRange();
6670  return QualType();
6671  }
6672 
6673  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6674  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6675  << RHSType << RHS.get()->getSourceRange();
6676  return QualType();
6677  }
6678 
6679  // If both types are identical, no conversion is needed.
6680  if (LHSType == RHSType)
6681  return LHSType;
6682 
6683  // Now handle "real" floating types (i.e. float, double, long double).
6684  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6685  return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6686  /*IsCompAssign = */ false);
6687 
6688  // Finally, we have two differing integer types.
6689  return handleIntegerConversion<doIntegralCast, doIntegralCast>
6690  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6691 }
6692 
6693 /// Convert scalar operands to a vector that matches the
6694 /// condition in length.
6695 ///
6696 /// Used when handling the OpenCL conditional operator where the
6697 /// condition is a vector while the other operands are scalar.
6698 ///
6699 /// We first compute the "result type" for the scalar operands
6700 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6701 /// into a vector of that type where the length matches the condition
6702 /// vector type. s6.11.6 requires that the element types of the result
6703 /// and the condition must have the same number of bits.
6704 static QualType
6706  QualType CondTy, SourceLocation QuestionLoc) {
6707  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6708  if (ResTy.isNull()) return QualType();
6709 
6710  const VectorType *CV = CondTy->getAs<VectorType>();
6711  assert(CV);
6712 
6713  // Determine the vector result type
6714  unsigned NumElements = CV->getNumElements();
6715  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6716 
6717  // Ensure that all types have the same number of bits
6718  if (S.Context.getTypeSize(CV->getElementType())
6719  != S.Context.getTypeSize(ResTy)) {
6720  // Since VectorTy is created internally, it does not pretty print
6721  // with an OpenCL name. Instead, we just print a description.
6722  std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6723  SmallString<64> Str;
6724  llvm::raw_svector_ostream OS(Str);
6725  OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6726  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6727  << CondTy << OS.str();
6728  return QualType();
6729  }
6730 
6731  // Convert operands to the vector result type
6732  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6733  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6734 
6735  return VectorTy;
6736 }
6737 
6738 /// Return false if this is a valid OpenCL condition vector
6739 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6740  SourceLocation QuestionLoc) {
6741  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6742  // integral type.
6743  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6744  assert(CondTy);
6745  QualType EleTy = CondTy->getElementType();
6746  if (EleTy->isIntegerType()) return false;
6747 
6748  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6749  << Cond->getType() << Cond->getSourceRange();
6750  return true;
6751 }
6752 
6753 /// Return false if the vector condition type and the vector
6754 /// result type are compatible.
6755 ///
6756 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6757 /// number of elements, and their element types have the same number
6758 /// of bits.
6759 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6760  SourceLocation QuestionLoc) {
6761  const VectorType *CV = CondTy->getAs<VectorType>();
6762  const VectorType *RV = VecResTy->getAs<VectorType>();
6763  assert(CV && RV);
6764 
6765  if (CV->getNumElements() != RV->getNumElements()) {
6766  S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6767  << CondTy << VecResTy;
6768  return true;
6769  }
6770 
6771  QualType CVE = CV->getElementType();
6772  QualType RVE = RV->getElementType();
6773 
6774  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6775  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6776  << CondTy << VecResTy;
6777  return true;
6778  }
6779 
6780  return false;
6781 }
6782 
6783 /// Return the resulting type for the conditional operator in
6784 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6785 /// s6.3.i) when the condition is a vector type.
6786 static QualType
6788  ExprResult &LHS, ExprResult &RHS,
6789  SourceLocation QuestionLoc) {
6790  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6791  if (Cond.isInvalid())
6792  return QualType();
6793  QualType CondTy = Cond.get()->getType();
6794 
6795  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6796  return QualType();
6797 
6798  // If either operand is a vector then find the vector type of the
6799  // result as specified in OpenCL v1.1 s6.3.i.
6800  if (LHS.get()->getType()->isVectorType() ||
6801  RHS.get()->getType()->isVectorType()) {
6802  QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6803  /*isCompAssign*/false,
6804  /*AllowBothBool*/true,
6805  /*AllowBoolConversions*/false);
6806  if (VecResTy.isNull()) return QualType();
6807  // The result type must match the condition type as specified in
6808  // OpenCL v1.1 s6.11.6.
6809  if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6810  return QualType();
6811  return VecResTy;
6812  }
6813 
6814  // Both operands are scalar.
6815  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6816 }
6817 
6818 /// Return true if the Expr is block type
6819 static bool checkBlockType(Sema &S, const Expr *E) {
6820  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6821  QualType Ty = CE->getCallee()->getType();
6822  if (Ty->isBlockPointerType()) {
6823  S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6824  return true;
6825  }
6826  }
6827  return false;
6828 }
6829 
6830 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6831 /// In that case, LHS = cond.
6832 /// C99 6.5.15
6834  ExprResult &RHS, ExprValueKind &VK,
6835  ExprObjectKind &OK,
6836  SourceLocation QuestionLoc) {
6837 
6838  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6839  if (!LHSResult.isUsable()) return QualType();
6840  LHS = LHSResult;
6841 
6842  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6843  if (!RHSResult.isUsable()) return QualType();
6844  RHS = RHSResult;
6845 
6846  // C++ is sufficiently different to merit its own checker.
6847  if (getLangOpts().CPlusPlus)
6848  return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6849 
6850  VK = VK_RValue;
6851  OK = OK_Ordinary;
6852 
6853  // The OpenCL operator with a vector condition is sufficiently
6854  // different to merit its own checker.
6855  if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6856  return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6857 
6858  // First, check the condition.
6859  Cond = UsualUnaryConversions(Cond.get());
6860  if (Cond.isInvalid())
6861  return QualType();
6862  if (checkCondition(*this, Cond.get(), QuestionLoc))
6863  return QualType();
6864 
6865  // Now check the two expressions.
6866  if (LHS.get()->getType()->isVectorType() ||
6867  RHS.get()->getType()->isVectorType())
6868  return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6869  /*AllowBothBool*/true,
6870  /*AllowBoolConversions*/false);
6871 
6872  QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6873  if (LHS.isInvalid() || RHS.isInvalid())
6874  return QualType();
6875 
6876  QualType LHSTy = LHS.get()->getType();
6877  QualType RHSTy = RHS.get()->getType();
6878 
6879  // Diagnose attempts to convert between __float128 and long double where
6880  // such conversions currently can't be handled.
6881  if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6882  Diag(QuestionLoc,
6883  diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6884  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6885  return QualType();
6886  }
6887 
6888  // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6889  // selection operator (?:).
6890  if (getLangOpts().OpenCL &&
6891  (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6892  return QualType();
6893  }
6894 
6895  // If both operands have arithmetic type, do the usual arithmetic conversions
6896  // to find a common type: C99 6.5.15p3,5.
6897  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6898  LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6899  RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6900 
6901  return ResTy;
6902  }
6903 
6904  // If both operands are the same structure or union type, the result is that
6905  // type.
6906  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6907  if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6908  if (LHSRT->getDecl() == RHSRT->getDecl())
6909  // "If both the operands have structure or union type, the result has
6910  // that type." This implies that CV qualifiers are dropped.
6911  return LHSTy.getUnqualifiedType();
6912  // FIXME: Type of conditional expression must be complete in C mode.
6913  }
6914 
6915  // C99 6.5.15p5: "If both operands have void type, the result has void type."
6916  // The following || allows only one side to be void (a GCC-ism).
6917  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6918  return checkConditionalVoidType(*this, LHS, RHS);
6919  }
6920 
6921  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6922  // the type of the other operand."
6923  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6924  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6925 
6926  // All objective-c pointer type analysis is done here.
6927  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6928  QuestionLoc);
6929  if (LHS.isInvalid() || RHS.isInvalid())
6930  return QualType();
6931  if (!compositeType.isNull())
6932  return compositeType;
6933 
6934 
6935  // Handle block pointer types.
6936  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6937  return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6938  QuestionLoc);
6939 
6940  // Check constraints for C object pointers types (C99 6.5.15p3,6).
6941  if (LHSTy->isPointerType() && RHSTy->isPointerType())
6942  return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6943  QuestionLoc);
6944 
6945  // GCC compatibility: soften pointer/integer mismatch. Note that
6946  // null pointers have been filtered out by this point.
6947  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6948  /*isIntFirstExpr=*/true))
6949  return RHSTy;
6950  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6951  /*isIntFirstExpr=*/false))
6952  return LHSTy;
6953 
6954  // Emit a better diagnostic if one of the expressions is a null pointer
6955  // constant and the other is not a pointer type. In this case, the user most
6956  // likely forgot to take the address of the other expression.
6957  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6958  return QualType();
6959 
6960  // Otherwise, the operands are not compatible.
6961  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6962  << LHSTy << RHSTy << LHS.get()->getSourceRange()
6963  << RHS.get()->getSourceRange();
6964  return QualType();
6965 }
6966 
6967 /// FindCompositeObjCPointerType - Helper method to find composite type of
6968 /// two objective-c pointer types of the two input expressions.
6970  SourceLocation QuestionLoc) {
6971  QualType LHSTy = LHS.get()->getType();
6972  QualType RHSTy = RHS.get()->getType();
6973 
6974  // Handle things like Class and struct objc_class*. Here we case the result
6975  // to the pseudo-builtin, because that will be implicitly cast back to the
6976  // redefinition type if an attempt is made to access its fields.
6977  if (LHSTy->isObjCClassType() &&
6978  (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6979  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6980  return LHSTy;
6981  }
6982  if (RHSTy->isObjCClassType() &&
6983  (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6984  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6985  return RHSTy;
6986  }
6987  // And the same for struct objc_object* / id
6988  if (LHSTy->isObjCIdType() &&
6989  (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6990  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6991  return LHSTy;
6992  }
6993  if (RHSTy->isObjCIdType() &&
6994  (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6995  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6996  return RHSTy;
6997  }
6998  // And the same for struct objc_selector* / SEL
6999  if (Context.isObjCSelType(LHSTy) &&
7000  (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7001  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7002  return LHSTy;
7003  }
7004  if (Context.isObjCSelType(RHSTy) &&
7005  (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7006  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7007  return RHSTy;
7008  }
7009  // Check constraints for Objective-C object pointers types.
7010  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7011 
7012  if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7013  // Two identical object pointer types are always compatible.
7014  return LHSTy;
7015  }
7016  const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7017  const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7018  QualType compositeType = LHSTy;
7019 
7020  // If both operands are interfaces and either operand can be
7021  // assigned to the other, use that type as the composite
7022  // type. This allows
7023  // xxx ? (A*) a : (B*) b
7024  // where B is a subclass of A.
7025  //
7026  // Additionally, as for assignment, if either type is 'id'
7027  // allow silent coercion. Finally, if the types are
7028  // incompatible then make sure to use 'id' as the composite
7029  // type so the result is acceptable for sending messages to.
7030 
7031  // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7032  // It could return the composite type.
7033  if (!(compositeType =
7034  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7035  // Nothing more to do.
7036  } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7037  compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7038  } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7039  compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7040  } else if ((LHSTy->isObjCQualifiedIdType() ||
7041  RHSTy->isObjCQualifiedIdType()) &&
7042  Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7043  // Need to handle "id<xx>" explicitly.
7044  // GCC allows qualified id and any Objective-C type to devolve to
7045  // id. Currently localizing to here until clear this should be
7046  // part of ObjCQualifiedIdTypesAreCompatible.
7047  compositeType = Context.getObjCIdType();
7048  } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7049  compositeType = Context.getObjCIdType();
7050  } else {
7051  Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7052  << LHSTy << RHSTy
7053  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7054  QualType incompatTy = Context.getObjCIdType();
7055  LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7056  RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7057  return incompatTy;
7058  }
7059  // The object pointer types are compatible.
7060  LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7061  RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7062  return compositeType;
7063  }
7064  // Check Objective-C object pointer types and 'void *'
7065  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7066  if (getLangOpts().ObjCAutoRefCount) {
7067  // ARC forbids the implicit conversion of object pointers to 'void *',
7068  // so these types are not compatible.
7069  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7070  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7071  LHS = RHS = true;
7072  return QualType();
7073  }
7074  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7075  QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7076  QualType destPointee
7077  = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7078  QualType destType = Context.getPointerType(destPointee);
7079  // Add qualifiers if necessary.
7080  LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7081  // Promote to void*.
7082  RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7083  return destType;
7084  }
7085  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7086  if (getLangOpts().ObjCAutoRefCount) {
7087  // ARC forbids the implicit conversion of object pointers to 'void *',
7088  // so these types are not compatible.
7089  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7090  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7091  LHS = RHS = true;
7092  return QualType();
7093  }
7094  QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7095  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7096  QualType destPointee
7097  = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7098  QualType destType = Context.getPointerType(destPointee);
7099  // Add qualifiers if necessary.
7100  RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7101  // Promote to void*.
7102  LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7103  return destType;
7104  }
7105  return QualType();
7106 }
7107 
7108 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7109 /// ParenRange in parentheses.
7110 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7111  const PartialDiagnostic &Note,
7112  SourceRange ParenRange) {
7113  SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7114  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7115  EndLoc.isValid()) {
7116  Self.Diag(Loc, Note)
7117  << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7118  << FixItHint::CreateInsertion(EndLoc, ")");
7119  } else {
7120  // We can't display the parentheses, so just show the bare note.
7121  Self.Diag(Loc, Note) << ParenRange;
7122  }
7123 }
7124 
7126  return BinaryOperator::isAdditiveOp(Opc) ||
7129 }
7130 
7131 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7132 /// expression, either using a built-in or overloaded operator,
7133 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7134 /// expression.
7136  Expr **RHSExprs) {
7137  // Don't strip parenthesis: we should not warn if E is in parenthesis.
7138  E = E->IgnoreImpCasts();
7139  E = E->IgnoreConversionOperator();
7140  E = E->IgnoreImpCasts();
7141  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7142  E = MTE->GetTemporaryExpr();
7143  E = E->IgnoreImpCasts();
7144  }
7145 
7146  // Built-in binary operator.
7147  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7148  if (IsArithmeticOp(OP->getOpcode())) {
7149  *Opcode = OP->getOpcode();
7150  *RHSExprs = OP->getRHS();
7151  return true;
7152  }
7153  }
7154 
7155  // Overloaded operator.
7156  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7157  if (Call->getNumArgs() != 2)
7158  return false;
7159 
7160  // Make sure this is really a binary operator that is safe to pass into
7161  // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7162  OverloadedOperatorKind OO = Call->getOperator();
7163  if (OO < OO_Plus || OO > OO_Arrow ||
7164  OO == OO_PlusPlus || OO == OO_MinusMinus)
7165  return false;
7166 
7168  if (IsArithmeticOp(OpKind)) {
7169  *Opcode = OpKind;
7170  *RHSExprs = Call->getArg(1);
7171  return true;
7172  }
7173  }
7174 
7175  return false;
7176 }
7177 
7178 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7179 /// or is a logical expression such as (x==y) which has int type, but is
7180 /// commonly interpreted as boolean.
7181 static bool ExprLooksBoolean(Expr *E) {
7182  E = E->IgnoreParenImpCasts();
7183 
7184  if (E->getType()->isBooleanType())
7185  return true;
7186  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7187  return OP->isComparisonOp() || OP->isLogicalOp();
7188  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7189  return OP->getOpcode() == UO_LNot;
7190  if (E->getType()->isPointerType())
7191  return true;
7192  // FIXME: What about overloaded operator calls returning "unspecified boolean
7193  // type"s (commonly pointer-to-members)?
7194 
7195  return false;
7196 }
7197 
7198 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7199 /// and binary operator are mixed in a way that suggests the programmer assumed
7200 /// the conditional operator has higher precedence, for example:
7201 /// "int x = a + someBinaryCondition ? 1 : 2".
7203  SourceLocation OpLoc,
7204  Expr *Condition,
7205  Expr *LHSExpr,
7206  Expr *RHSExpr) {
7207  BinaryOperatorKind CondOpcode;
7208  Expr *CondRHS;
7209 
7210  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7211  return;
7212  if (!ExprLooksBoolean(CondRHS))
7213  return;
7214 
7215  // The condition is an arithmetic binary expression, with a right-
7216  // hand side that looks boolean, so warn.
7217 
7218  Self.Diag(OpLoc, diag::warn_precedence_conditional)
7219  << Condition->getSourceRange()
7220  << BinaryOperator::getOpcodeStr(CondOpcode);
7221 
7222  SuggestParentheses(Self, OpLoc,
7223  Self.PDiag(diag::note_precedence_silence)
7224  << BinaryOperator::getOpcodeStr(CondOpcode),
7225  SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7226 
7227  SuggestParentheses(Self, OpLoc,
7228  Self.PDiag(diag::note_precedence_conditional_first),
7229  SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7230 }
7231 
7232 /// Compute the nullability of a conditional expression.
7234  QualType LHSTy, QualType RHSTy,
7235  ASTContext &Ctx) {
7236  if (!ResTy->isAnyPointerType())
7237  return ResTy;
7238 
7239  auto GetNullability = [&Ctx](QualType Ty) {
7240  Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7241  if (Kind)
7242  return *Kind;
7244  };
7245 
7246  auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7247  NullabilityKind MergedKind;
7248 
7249  // Compute nullability of a binary conditional expression.
7250  if (IsBin) {
7251  if (LHSKind == NullabilityKind::NonNull)
7252  MergedKind = NullabilityKind::NonNull;
7253  else
7254  MergedKind = RHSKind;
7255  // Compute nullability of a normal conditional expression.
7256  } else {
7257  if (LHSKind == NullabilityKind::Nullable ||
7258  RHSKind == NullabilityKind::Nullable)
7259  MergedKind = NullabilityKind::Nullable;
7260  else if (LHSKind == NullabilityKind::NonNull)
7261  MergedKind = RHSKind;
7262  else if (RHSKind == NullabilityKind::NonNull)
7263  MergedKind = LHSKind;
7264  else
7265  MergedKind = NullabilityKind::Unspecified;
7266  }
7267 
7268  // Return if ResTy already has the correct nullability.
7269  if (GetNullability(ResTy) == MergedKind)
7270  return ResTy;
7271 
7272  // Strip all nullability from ResTy.
7273  while (ResTy->getNullability(Ctx))
7274  ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7275 
7276  // Create a new AttributedType with the new nullability kind.
7277  auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7278  return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7279 }
7280 
7281 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7282 /// in the case of a the GNU conditional expr extension.
7285  Expr *CondExpr, Expr *LHSExpr,
7286  Expr *RHSExpr) {
7287  if (!getLangOpts().CPlusPlus) {
7288  // C cannot handle TypoExpr nodes in the condition because it
7289  // doesn't handle dependent types properly, so make sure any TypoExprs have
7290  // been dealt with before checking the operands.
7291  ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7292  ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7293  ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7294 
7295  if (!CondResult.isUsable())
7296  return ExprError();
7297 
7298  if (LHSExpr) {
7299  if (!LHSResult.isUsable())
7300  return ExprError();
7301  }
7302 
7303  if (!RHSResult.isUsable())
7304  return ExprError();
7305 
7306  CondExpr = CondResult.get();
7307  LHSExpr = LHSResult.get();
7308  RHSExpr = RHSResult.get();
7309  }
7310 
7311  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7312  // was the condition.
7313  OpaqueValueExpr *opaqueValue = nullptr;
7314  Expr *commonExpr = nullptr;
7315  if (!LHSExpr) {
7316  commonExpr = CondExpr;
7317  // Lower out placeholder types first. This is important so that we don't
7318  // try to capture a placeholder. This happens in few cases in C++; such
7319  // as Objective-C++'s dictionary subscripting syntax.
7320  if (commonExpr->hasPlaceholderType()) {
7321  ExprResult result = CheckPlaceholderExpr(commonExpr);
7322  if (!result.isUsable()) return ExprError();
7323  commonExpr = result.get();
7324  }
7325  // We usually want to apply unary conversions *before* saving, except
7326  // in the special case of a C++ l-value conditional.
7327  if (!(getLangOpts().CPlusPlus
7328  && !commonExpr->isTypeDependent()
7329  && commonExpr->getValueKind() == RHSExpr->getValueKind()
7330  && commonExpr->isGLValue()
7331  && commonExpr->isOrdinaryOrBitFieldObject()
7332  && RHSExpr->isOrdinaryOrBitFieldObject()
7333  && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7334  ExprResult commonRes = UsualUnaryConversions(commonExpr);
7335  if (commonRes.isInvalid())
7336  return ExprError();
7337  commonExpr = commonRes.get();
7338  }
7339 
7340  // If the common expression is a class or array prvalue, materialize it
7341  // so that we can safely refer to it multiple times.
7342  if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7343  commonExpr->getType()->isArrayType())) {
7344  ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7345  if (MatExpr.isInvalid())
7346  return ExprError();
7347  commonExpr = MatExpr.get();
7348  }
7349 
7350  opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7351  commonExpr->getType(),
7352  commonExpr->getValueKind(),
7353  commonExpr->getObjectKind(),
7354  commonExpr);
7355  LHSExpr = CondExpr = opaqueValue;
7356  }
7357 
7358  QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7359  ExprValueKind VK = VK_RValue;
7361  ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7362  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7363  VK, OK, QuestionLoc);
7364  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7365  RHS.isInvalid())
7366  return ExprError();
7367 
7368  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7369  RHS.get());
7370 
7371  CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7372 
7373  result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7374  Context);
7375 
7376  if (!commonExpr)
7377  return new (Context)
7378  ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7379  RHS.get(), result, VK, OK);
7380 
7381  return new (Context) BinaryConditionalOperator(
7382  commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7383  ColonLoc, result, VK, OK);
7384 }
7385 
7386 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7387 // being closely modeled after the C99 spec:-). The odd characteristic of this
7388 // routine is it effectively iqnores the qualifiers on the top level pointee.
7389 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7390 // FIXME: add a couple examples in this comment.
7393  assert(LHSType.isCanonical() && "LHS not canonicalized!");
7394  assert(RHSType.isCanonical() && "RHS not canonicalized!");
7395 
7396  // get the "pointed to" type (ignoring qualifiers at the top level)
7397  const Type *lhptee, *rhptee;
7398  Qualifiers lhq, rhq;
7399  std::tie(lhptee, lhq) =
7400  cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7401  std::tie(rhptee, rhq) =
7402  cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7403 
7405 
7406  // C99 6.5.16.1p1: This following citation is common to constraints
7407  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7408  // qualifiers of the type *pointed to* by the right;
7409 
7410  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7411  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7412  lhq.compatiblyIncludesObjCLifetime(rhq)) {
7413  // Ignore lifetime for further calculation.
7414  lhq.removeObjCLifetime();
7415  rhq.removeObjCLifetime();
7416  }
7417 
7418  if (!lhq.compatiblyIncludes(rhq)) {
7419  // Treat address-space mismatches as fatal. TODO: address subspaces
7420  if (!lhq.isAddressSpaceSupersetOf(rhq))
7422 
7423  // It's okay to add or remove GC or lifetime qualifiers when converting to
7424  // and from void*.
7425  else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7428  && (lhptee->isVoidType() || rhptee->isVoidType()))
7429  ; // keep old
7430 
7431  // Treat lifetime mismatches as fatal.
7432  else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7434 
7435  // For GCC/MS compatibility, other qualifier mismatches are treated
7436  // as still compatible in C.
7438  }
7439 
7440  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7441  // incomplete type and the other is a pointer to a qualified or unqualified
7442  // version of void...
7443  if (lhptee->isVoidType()) {
7444  if (rhptee->isIncompleteOrObjectType())
7445  return ConvTy;
7446 
7447  // As an extension, we allow cast to/from void* to function pointer.
7448  assert(rhptee->isFunctionType());
7450  }
7451 
7452  if (rhptee->isVoidType()) {
7453  if (lhptee->isIncompleteOrObjectType())
7454  return ConvTy;
7455 
7456  // As an extension, we allow cast to/from void* to function pointer.
7457  assert(lhptee->isFunctionType());
7459  }
7460 
7461  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7462  // unqualified versions of compatible types, ...
7463  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7464  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7465  // Check if the pointee types are compatible ignoring the sign.
7466  // We explicitly check for char so that we catch "char" vs
7467  // "unsigned char" on systems where "char" is unsigned.
7468  if (lhptee->isCharType())
7469  ltrans = S.Context.UnsignedCharTy;
7470  else if (lhptee->hasSignedIntegerRepresentation())
7471  ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7472 
7473  if (rhptee->isCharType())
7474  rtrans = S.Context.UnsignedCharTy;
7475  else if (rhptee->hasSignedIntegerRepresentation())
7476  rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7477 
7478  if (ltrans == rtrans) {
7479  // Types are compatible ignoring the sign. Qualifier incompatibility
7480  // takes priority over sign incompatibility because the sign
7481  // warning can be disabled.
7482  if (ConvTy != Sema::Compatible)
7483  return ConvTy;
7484 
7486  }
7487 
7488  // If we are a multi-level pointer, it's possible that our issue is simply
7489  // one of qualification - e.g. char ** -> const char ** is not allowed. If
7490  // the eventual target type is the same and the pointers have the same
7491  // level of indirection, this must be the issue.
7492  if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7493  do {
7494  lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7495  rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7496  } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7497 
7498  if (lhptee == rhptee)
7500  }
7501 
7502  // General pointer incompatibility takes priority over qualifiers.
7504  }
7505  if (!S.getLangOpts().CPlusPlus &&
7506  S.IsFunctionConversion(ltrans, rtrans, ltrans))
7508  return ConvTy;
7509 }
7510 
7511 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7512 /// block pointer types are compatible or whether a block and normal pointer
7513 /// are compatible. It is more restrict than comparing two function pointer
7514 // types.
7517  QualType RHSType) {
7518  assert(LHSType.isCanonical() && "LHS not canonicalized!");
7519  assert(RHSType.isCanonical() && "RHS not canonicalized!");
7520 
7521  QualType lhptee, rhptee;
7522 
7523  // get the "pointed to" type (ignoring qualifiers at the top level)
7524  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7525  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7526 
7527  // In C++, the types have to match exactly.
7528  if (S.getLangOpts().CPlusPlus)
7530 
7532 
7533  // For blocks we enforce that qualifiers are identical.
7534  Qualifiers LQuals = lhptee.getLocalQualifiers();
7535  Qualifiers RQuals = rhptee.getLocalQualifiers();
7536  if (S.getLangOpts().OpenCL) {
7537  LQuals.removeAddressSpace();
7538  RQuals.removeAddressSpace();
7539  }
7540  if (LQuals != RQuals)
7542 
7543  // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7544  // assignment.
7545  // The current behavior is similar to C++ lambdas. A block might be
7546  // assigned to a variable iff its return type and parameters are compatible
7547  // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7548  // an assignment. Presumably it should behave in way that a function pointer
7549  // assignment does in C, so for each parameter and return type:
7550  // * CVR and address space of LHS should be a superset of CVR and address
7551  // space of RHS.
7552  // * unqualified types should be compatible.
7553  if (S.getLangOpts().OpenCL) {
7555  S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7556  S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7558  } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7560 
7561  return ConvTy;
7562 }
7563 
7564 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7565 /// for assignment compatibility.
7568  QualType RHSType) {
7569  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7570  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7571 
7572  if (LHSType->isObjCBuiltinType()) {
7573  // Class is not compatible with ObjC object pointers.
7574  if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7575  !RHSType->isObjCQualifiedClassType())
7577  return Sema::Compatible;
7578  }
7579  if (RHSType->isObjCBuiltinType()) {
7580  if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7581  !LHSType->isObjCQualifiedClassType())
7583  return Sema::Compatible;
7584  }
7585  QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7586  QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7587 
7588  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7589  // make an exception for id<P>
7590  !LHSType->isObjCQualifiedIdType())
7592 
7593  if (S.Context.typesAreCompatible(LHSType, RHSType))
7594  return Sema::Compatible;
7595  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7598 }
7599 
7602  QualType LHSType, QualType RHSType) {
7603  // Fake up an opaque expression. We don't actually care about what
7604  // cast operations are required, so if CheckAssignmentConstraints
7605  // adds casts to this they'll be wasted, but fortunately that doesn't
7606  // usually happen on valid code.
7607  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7608  ExprResult RHSPtr = &RHSExpr;
7609  CastKind K;
7610 
7611  return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7612 }
7613 
7614 /// This helper function returns true if QT is a vector type that has element
7615 /// type ElementType.
7616 static bool isVector(QualType QT, QualType ElementType) {
7617  if (const VectorType *VT = QT->getAs<VectorType>())
7618  return VT->getElementType() == ElementType;
7619  return false;
7620 }
7621 
7622 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7623 /// has code to accommodate several GCC extensions when type checking
7624 /// pointers. Here are some objectionable examples that GCC considers warnings:
7625 ///
7626 /// int a, *pint;
7627 /// short *pshort;
7628 /// struct foo *pfoo;
7629 ///
7630 /// pint = pshort; // warning: assignment from incompatible pointer type
7631 /// a = pint; // warning: assignment makes integer from pointer without a cast
7632 /// pint = a; // warning: assignment makes pointer from integer without a cast
7633 /// pint = pfoo; // warning: assignment from incompatible pointer type
7634 ///
7635 /// As a result, the code for dealing with pointers is more complex than the
7636 /// C99 spec dictates.
7637 ///
7638 /// Sets 'Kind' for any result kind except Incompatible.
7641  CastKind &Kind, bool ConvertRHS) {
7642  QualType RHSType = RHS.get()->getType();
7643  QualType OrigLHSType = LHSType;
7644 
7645  // Get canonical types. We're not formatting these types, just comparing
7646  // them.
7647  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7648  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7649 
7650  // Common case: no conversion required.
7651  if (LHSType == RHSType) {
7652  Kind = CK_NoOp;
7653  return Compatible;
7654  }
7655 
7656  // If we have an atomic type, try a non-atomic assignment, then just add an
7657  // atomic qualification step.
7658  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7659  Sema::AssignConvertType result =
7660  CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7661  if (result != Compatible)
7662  return result;
7663  if (Kind != CK_NoOp && ConvertRHS)
7664  RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7665  Kind = CK_NonAtomicToAtomic;
7666  return Compatible;
7667  }
7668 
7669  // If the left-hand side is a reference type, then we are in a
7670  // (rare!) case where we've allowed the use of references in C,
7671  // e.g., as a parameter type in a built-in function. In this case,
7672  // just make sure that the type referenced is compatible with the
7673  // right-hand side type. The caller is responsible for adjusting
7674  // LHSType so that the resulting expression does not have reference
7675  // type.
7676  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7677  if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7678  Kind = CK_LValueBitCast;
7679  return Compatible;
7680  }
7681  return Incompatible;
7682  }
7683 
7684  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7685  // to the same ExtVector type.
7686  if (LHSType->isExtVectorType()) {
7687  if (RHSType->isExtVectorType())
7688  return Incompatible;
7689  if (RHSType->isArithmeticType()) {
7690  // CK_VectorSplat does T -> vector T, so first cast to the element type.
7691  if (ConvertRHS)
7692  RHS = prepareVectorSplat(LHSType, RHS.get());
7693  Kind = CK_VectorSplat;
7694  return Compatible;
7695  }
7696  }
7697 
7698  // Conversions to or from vector type.
7699  if (LHSType->isVectorType() || RHSType->isVectorType()) {
7700  if (LHSType->isVectorType() && RHSType->isVectorType()) {
7701  // Allow assignments of an AltiVec vector type to an equivalent GCC
7702  // vector type and vice versa
7703  if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7704  Kind = CK_BitCast;
7705  return Compatible;
7706  }
7707 
7708  // If we are allowing lax vector conversions, and LHS and RHS are both
7709  // vectors, the total size only needs to be the same. This is a bitcast;
7710  // no bits are changed but the result type is different.
7711  if (isLaxVectorConversion(RHSType, LHSType)) {
7712  Kind = CK_BitCast;
7713  return IncompatibleVectors;
7714  }
7715  }
7716 
7717  // When the RHS comes from another lax conversion (e.g. binops between
7718  // scalars and vectors) the result is canonicalized as a vector. When the
7719  // LHS is also a vector, the lax is allowed by the condition above. Handle
7720  // the case where LHS is a scalar.
7721  if (LHSType->isScalarType()) {
7722  const VectorType *VecType = RHSType->getAs<VectorType>();
7723  if (VecType && VecType->getNumElements() == 1 &&
7724  isLaxVectorConversion(RHSType, LHSType)) {
7725  ExprResult *VecExpr = &RHS;
7726  *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7727  Kind = CK_BitCast;
7728  return Compatible;
7729  }
7730  }
7731 
7732  return Incompatible;
7733  }
7734 
7735  // Diagnose attempts to convert between __float128 and long double where
7736  // such conversions currently can't be handled.
7737  if (unsupportedTypeConversion(*this, LHSType, RHSType))
7738  return Incompatible;
7739 
7740  // Disallow assigning a _Complex to a real type in C++ mode since it simply
7741  // discards the imaginary part.
7742  if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7743  !LHSType->getAs<ComplexType>())
7744  return Incompatible;
7745 
7746  // Arithmetic conversions.
7747  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7748  !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7749  if (ConvertRHS)
7750  Kind = PrepareScalarCast(RHS, LHSType);
7751  return Compatible;
7752  }
7753 
7754  // Conversions to normal pointers.
7755  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7756  // U* -> T*
7757  if (isa<PointerType>(RHSType)) {
7758  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7759  LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7760  Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7761  return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7762  }
7763 
7764  // int -> T*
7765  if (RHSType->isIntegerType()) {
7766  Kind = CK_IntegralToPointer; // FIXME: null?
7767  return IntToPointer;
7768  }
7769 
7770  // C pointers are not compatible with ObjC object pointers,
7771  // with two exceptions:
7772  if (isa<ObjCObjectPointerType>(RHSType)) {
7773  // - conversions to void*
7774  if (LHSPointer->getPointeeType()->isVoidType()) {
7775  Kind = CK_BitCast;
7776  return Compatible;
7777  }
7778 
7779  // - conversions from 'Class' to the redefinition type
7780  if (RHSType->isObjCClassType() &&
7781  Context.hasSameType(LHSType,
7782  Context.getObjCClassRedefinitionType())) {
7783  Kind = CK_BitCast;
7784  return Compatible;
7785  }
7786 
7787  Kind = CK_BitCast;
7788  return IncompatiblePointer;
7789  }
7790 
7791  // U^ -> void*
7792  if (RHSType->getAs<BlockPointerType>()) {
7793  if (LHSPointer->getPointeeType()->isVoidType()) {
7794  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7795  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7796  ->getPointeeType()
7797  .getAddressSpace();
7798  Kind =
7799  AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7800  return Compatible;
7801  }
7802  }
7803 
7804  return Incompatible;
7805  }
7806 
7807  // Conversions to block pointers.
7808  if (isa<BlockPointerType>(LHSType)) {
7809  // U^ -> T^
7810  if (RHSType->isBlockPointerType()) {
7811  LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7812  ->getPointeeType()
7813  .getAddressSpace();
7814  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7815  ->getPointeeType()
7816  .getAddressSpace();
7817  Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7818  return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7819  }
7820 
7821  // int or null -> T^
7822  if (RHSType->isIntegerType()) {
7823  Kind = CK_IntegralToPointer; // FIXME: null
7824  return IntToBlockPointer;
7825  }
7826 
7827  // id -> T^
7828  if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7829  Kind = CK_AnyPointerToBlockPointerCast;
7830  return Compatible;
7831  }
7832 
7833  // void* -> T^
7834  if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7835  if (RHSPT->getPointeeType()->isVoidType()) {
7836  Kind = CK_AnyPointerToBlockPointerCast;
7837  return Compatible;
7838  }
7839 
7840  return Incompatible;
7841  }
7842 
7843  // Conversions to Objective-C pointers.
7844  if (isa<ObjCObjectPointerType>(LHSType)) {
7845  // A* -> B*
7846  if (RHSType->isObjCObjectPointerType()) {
7847  Kind = CK_BitCast;
7848  Sema::AssignConvertType result =
7849  checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7850  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7851  result == Compatible &&
7852  !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7853  result = IncompatibleObjCWeakRef;
7854  return result;
7855  }
7856 
7857  // int or null -> A*
7858  if (RHSType->isIntegerType()) {
7859  Kind = CK_IntegralToPointer; // FIXME: null
7860  return IntToPointer;
7861  }
7862 
7863  // In general, C pointers are not compatible with ObjC object pointers,
7864  // with two exceptions:
7865  if (isa<PointerType>(RHSType)) {
7866  Kind = CK_CPointerToObjCPointerCast;
7867 
7868  // - conversions from 'void*'
7869  if (RHSType->isVoidPointerType()) {
7870  return Compatible;
7871  }
7872 
7873  // - conversions to 'Class' from its redefinition type
7874  if (LHSType->isObjCClassType() &&
7875  Context.hasSameType(RHSType,
7876  Context.getObjCClassRedefinitionType())) {
7877  return Compatible;
7878  }
7879 
7880  return IncompatiblePointer;
7881  }
7882 
7883  // Only under strict condition T^ is compatible with an Objective-C pointer.
7884  if (RHSType->isBlockPointerType() &&
7885  LHSType->isBlockCompatibleObjCPointerType(Context)) {
7886  if (ConvertRHS)
7887  maybeExtendBlockObject(RHS);
7888  Kind = CK_BlockPointerToObjCPointerCast;
7889  return Compatible;
7890  }
7891 
7892  return Incompatible;
7893  }
7894 
7895  // Conversions from pointers that are not covered by the above.
7896  if (isa<PointerType>(RHSType)) {
7897  // T* -> _Bool
7898  if (LHSType == Context.BoolTy) {
7899  Kind = CK_PointerToBoolean;
7900  return Compatible;
7901  }
7902 
7903  // T* -> int
7904  if (LHSType->isIntegerType()) {
7905  Kind = CK_PointerToIntegral;
7906  return PointerToInt;
7907  }
7908 
7909  return Incompatible;
7910  }
7911 
7912  // Conversions from Objective-C pointers that are not covered by the above.
7913  if (isa<ObjCObjectPointerType>(RHSType)) {
7914  // T* -> _Bool
7915  if (LHSType == Context.BoolTy) {
7916  Kind = CK_PointerToBoolean;
7917  return Compatible;
7918  }
7919 
7920  // T* -> int
7921  if (LHSType->isIntegerType()) {
7922  Kind = CK_PointerToIntegral;
7923  return PointerToInt;
7924  }
7925 
7926  return Incompatible;
7927  }
7928 
7929  // struct A -> struct B
7930  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7931  if (Context.typesAreCompatible(LHSType, RHSType)) {
7932  Kind = CK_NoOp;
7933  return Compatible;
7934  }
7935  }
7936 
7937  if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7938  Kind = CK_IntToOCLSampler;
7939  return Compatible;
7940  }
7941 
7942  return Incompatible;
7943 }
7944 
7945 /// Constructs a transparent union from an expression that is
7946 /// used to initialize the transparent union.
7948  ExprResult &EResult, QualType UnionType,
7949  FieldDecl *Field) {
7950  // Build an initializer list that designates the appropriate member
7951  // of the transparent union.
7952  Expr *E = EResult.get();
7953  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7954  E, SourceLocation());
7955  Initializer->setType(UnionType);
7956  Initializer->setInitializedFieldInUnion(Field);
7957 
7958  // Build a compound literal constructing a value of the transparent
7959  // union type from this initializer list.
7960  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7961  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7962  VK_RValue, Initializer, false);
7963 }
7964 
7967  ExprResult &RHS) {
7968  QualType RHSType = RHS.get()->getType();
7969 
7970  // If the ArgType is a Union type, we want to handle a potential
7971  // transparent_union GCC extension.
7972  const RecordType *UT = ArgType->getAsUnionType();
7973  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7974  return Incompatible;
7975 
7976  // The field to initialize within the transparent union.
7977  RecordDecl *UD = UT->getDecl();
7978  FieldDecl *InitField = nullptr;
7979  // It's compatible if the expression matches any of the fields.
7980  for (auto *it : UD->fields()) {
7981  if (it->getType()->isPointerType()) {
7982  // If the transparent union contains a pointer type, we allow:
7983  // 1) void pointer
7984  // 2) null pointer constant
7985  if (RHSType->isPointerType())
7986  if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7987  RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7988  InitField = it;
7989  break;
7990  }
7991 
7992  if (RHS.get()->isNullPointerConstant(Context,
7994  RHS = ImpCastExprToType(RHS.get(), it->getType(),
7995  CK_NullToPointer);
7996  InitField = it;
7997  break;
7998  }
7999  }
8000 
8001  CastKind Kind;
8002  if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8003  == Compatible) {
8004  RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8005  InitField = it;
8006  break;
8007  }
8008  }
8009 
8010  if (!InitField)
8011  return Incompatible;
8012 
8013  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8014  return Compatible;
8015 }
8016 
8019  bool Diagnose,
8020  bool DiagnoseCFAudited,
8021  bool ConvertRHS) {
8022  // We need to be able to tell the caller whether we diagnosed a problem, if
8023  // they ask us to issue diagnostics.
8024  assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8025 
8026  // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8027  // we can't avoid *all* modifications at the moment, so we need some somewhere
8028  // to put the updated value.
8029  ExprResult LocalRHS = CallerRHS;
8030  ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8031 
8032  if (getLangOpts().CPlusPlus) {
8033  if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8034  // C++ 5.17p3: If the left operand is not of class type, the
8035  // expression is implicitly converted (C++ 4) to the
8036  // cv-unqualified type of the left operand.
8037  QualType RHSType = RHS.get()->getType();
8038  if (Diagnose) {
8039  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8040  AA_Assigning);
8041  } else {
8043  TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8044  /*SuppressUserConversions=*/false,
8045  /*AllowExplicit=*/false,
8046  /*InOverloadResolution=*/false,
8047  /*CStyle=*/false,
8048  /*AllowObjCWritebackConversion=*/false);
8049  if (ICS.isFailure())
8050  return Incompatible;
8051  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8052  ICS, AA_Assigning);
8053  }
8054  if (RHS.isInvalid())
8055  return Incompatible;
8056  Sema::AssignConvertType result = Compatible;
8057  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8058  !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8059  result = IncompatibleObjCWeakRef;
8060  return result;
8061  }
8062 
8063  // FIXME: Currently, we fall through and treat C++ classes like C
8064  // structures.
8065  // FIXME: We also fall through for atomics; not sure what should
8066  // happen there, though.
8067  } else if (RHS.get()->getType() == Context.OverloadTy) {
8068  // As a set of extensions to C, we support overloading on functions. These
8069  // functions need to be resolved here.
8070  DeclAccessPair DAP;
8071  if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8072  RHS.get(), LHSType, /*Complain=*/false, DAP))
8073  RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8074  else
8075  return Incompatible;
8076  }
8077 
8078  // C99 6.5.16.1p1: the left operand is a pointer and the right is
8079  // a null pointer constant.
8080  if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8081  LHSType->isBlockPointerType()) &&
8082  RHS.get()->isNullPointerConstant(Context,
8084  if (Diagnose || ConvertRHS) {
8085  CastKind Kind;
8086  CXXCastPath Path;
8087  CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8088  /*IgnoreBaseAccess=*/false, Diagnose);
8089  if (ConvertRHS)
8090  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8091  }
8092  return Compatible;
8093  }
8094 
8095  // This check seems unnatural, however it is necessary to ensure the proper
8096  // conversion of functions/arrays. If the conversion were done for all
8097  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8098  // expressions that suppress this implicit conversion (&, sizeof).
8099  //
8100  // Suppress this for references: C++ 8.5.3p5.
8101  if (!LHSType->isReferenceType()) {
8102  // FIXME: We potentially allocate here even if ConvertRHS is false.
8103  RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8104  if (RHS.isInvalid())
8105  return Incompatible;
8106  }
8107 
8108  Expr *PRE = RHS.get()->IgnoreParenCasts();
8109  if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8110  ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8111  if (PDecl && !PDecl->hasDefinition()) {
8112  Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8113  Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8114  }
8115  }
8116 
8117  CastKind Kind;
8118  Sema::AssignConvertType result =
8119  CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8120 
8121  // C99 6.5.16.1p2: The value of the right operand is converted to the
8122  // type of the assignment expression.
8123  // CheckAssignmentConstraints allows the left-hand side to be a reference,
8124  // so that we can use references in built-in functions even in C.
8125  // The getNonReferenceType() call makes sure that the resulting expression
8126  // does not have reference type.
8127  if (result != Incompatible && RHS.get()->getType() != LHSType) {
8128  QualType Ty = LHSType.getNonLValueExprType(Context);
8129  Expr *E = RHS.get();
8130 
8131  // Check for various Objective-C errors. If we are not reporting
8132  // diagnostics and just checking for errors, e.g., during overload
8133  // resolution, return Incompatible to indicate the failure.
8134  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8135  CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8136  Diagnose, DiagnoseCFAudited) != ACR_okay) {
8137  if (!Diagnose)
8138  return Incompatible;
8139  }
8140  if (getLangOpts().ObjC1 &&
8141  (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8142  E->getType(), E, Diagnose) ||
8143  ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8144  if (!Diagnose)
8145  return Incompatible;
8146  // Replace the expression with a corrected version and continue so we
8147  // can find further errors.
8148  RHS = E;
8149  return Compatible;
8150  }
8151 
8152  if (ConvertRHS)
8153  RHS = ImpCastExprToType(E, Ty, Kind);
8154  }
8155  return result;
8156 }
8157 
8158 namespace {
8159 /// The original operand to an operator, prior to the application of the usual
8160 /// arithmetic conversions and converting the arguments of a builtin operator
8161 /// candidate.
8162 struct OriginalOperand {
8163  explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8164  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8165  Op = MTE->GetTemporaryExpr();
8166  if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8167  Op = BTE->getSubExpr();
8168  if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8169  Orig = ICE->getSubExprAsWritten();
8170  Conversion = ICE->getConversionFunction();
8171  }
8172  }
8173 
8174  QualType getType() const { return Orig->getType(); }
8175 
8176  Expr *Orig;
8177  NamedDecl *Conversion;
8178 };
8179 }
8180 
8182  ExprResult &RHS) {
8183  OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8184 
8185  Diag(Loc, diag::err_typecheck_invalid_operands)
8186  << OrigLHS.getType() << OrigRHS.getType()
8187  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8188 
8189  // If a user-defined conversion was applied to either of the operands prior
8190  // to applying the built-in operator rules, tell the user about it.
8191  if (OrigLHS.Conversion) {
8192  Diag(OrigLHS.Conversion->getLocation(),
8193  diag::note_typecheck_invalid_operands_converted)
8194  << 0 << LHS.get()->getType();
8195  }
8196  if (OrigRHS.Conversion) {
8197  Diag(OrigRHS.Conversion->getLocation(),
8198  diag::note_typecheck_invalid_operands_converted)
8199  << 1 << RHS.get()->getType();
8200  }
8201 
8202  return QualType();
8203 }
8204 
8205 // Diagnose cases where a scalar was implicitly converted to a vector and
8206 // diagnose the underlying types. Otherwise, diagnose the error
8207 // as invalid vector logical operands for non-C++ cases.
8209  ExprResult &RHS) {
8210  QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8211  QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8212 
8213  bool LHSNatVec = LHSType->isVectorType();
8214  bool RHSNatVec = RHSType->isVectorType();
8215 
8216  if (!(LHSNatVec && RHSNatVec)) {
8217  Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8218  Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8219  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8220  << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8221  << Vector->getSourceRange();
8222  return QualType();
8223  }
8224 
8225  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8226  << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8227  << RHS.get()->getSourceRange();
8228 
8229  return QualType();
8230 }
8231 
8232 /// Try to convert a value of non-vector type to a vector type by converting
8233 /// the type to the element type of the vector and then performing a splat.
8234 /// If the language is OpenCL, we only use conversions that promote scalar
8235 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8236 /// for float->int.
8237 ///
8238 /// OpenCL V2.0 6.2.6.p2:
8239 /// An error shall occur if any scalar operand type has greater rank
8240 /// than the type of the vector element.
8241 ///
8242 /// \param scalar - if non-null, actually perform the conversions
8243 /// \return true if the operation fails (but without diagnosing the failure)
8244 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8245  QualType scalarTy,
8246  QualType vectorEltTy,
8247  QualType vectorTy,
8248  unsigned &DiagID) {
8249  // The conversion to apply to the scalar before splatting it,
8250  // if necessary.
8251  CastKind scalarCast = CK_NoOp;
8252 
8253  if (vectorEltTy->isIntegralType(S.Context)) {
8254  if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8255  (scalarTy->isIntegerType() &&
8256  S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8257  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8258  return true;
8259  }
8260  if (!scalarTy->isIntegralType(S.Context))
8261  return true;
8262  scalarCast = CK_IntegralCast;
8263  } else if (vectorEltTy->isRealFloatingType()) {
8264  if (scalarTy->isRealFloatingType()) {
8265  if (S.getLangOpts().OpenCL &&
8266  S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8267  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8268  return true;
8269  }
8270  scalarCast = CK_FloatingCast;
8271  }
8272  else if (scalarTy->isIntegralType(S.Context))
8273  scalarCast = CK_IntegralToFloating;
8274  else
8275  return true;
8276  } else {
8277  return true;
8278  }
8279 
8280  // Adjust scalar if desired.
8281  if (scalar) {
8282  if (scalarCast != CK_NoOp)
8283  *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8284  *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8285  }
8286  return false;
8287 }
8288 
8289 /// Convert vector E to a vector with the same number of elements but different
8290 /// element type.
8291 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8292  const auto *VecTy = E->getType()->getAs<VectorType>();
8293  assert(VecTy && "Expression E must be a vector");
8294  QualType NewVecTy = S.Context.getVectorType(ElementType,
8295  VecTy->getNumElements(),
8296  VecTy->getVectorKind());
8297 
8298  // Look through the implicit cast. Return the subexpression if its type is
8299  // NewVecTy.
8300  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8301  if (ICE->getSubExpr()->getType() == NewVecTy)
8302  return ICE->getSubExpr();
8303 
8304  auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8305  return S.ImpCastExprToType(E, NewVecTy, Cast);
8306 }
8307 
8308 /// Test if a (constant) integer Int can be casted to another integer type
8309 /// IntTy without losing precision.
8311  QualType OtherIntTy) {
8312  QualType IntTy = Int->get()->getType().getUnqualifiedType();
8313 
8314  // Reject cases where the value of the Int is unknown as that would
8315  // possibly cause truncation, but accept cases where the scalar can be
8316  // demoted without loss of precision.
8317  llvm::APSInt Result;
8318  bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8319  int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8320  bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8321  bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8322 
8323  if (CstInt) {
8324  // If the scalar is constant and is of a higher order and has more active
8325  // bits that the vector element type, reject it.
8326  unsigned NumBits = IntSigned
8327  ? (Result.isNegative() ? Result.getMinSignedBits()
8328  : Result.getActiveBits())
8329  : Result.getActiveBits();
8330  if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8331  return true;
8332 
8333  // If the signedness of the scalar type and the vector element type
8334  // differs and the number of bits is greater than that of the vector
8335  // element reject it.
8336  return (IntSigned != OtherIntSigned &&
8337  NumBits > S.Context.getIntWidth(OtherIntTy));
8338  }
8339 
8340  // Reject cases where the value of the scalar is not constant and it's
8341  // order is greater than that of the vector element type.
8342  return (Order < 0);
8343 }
8344 
8345 /// Test if a (constant) integer Int can be casted to floating point type
8346 /// FloatTy without losing precision.
8348  QualType FloatTy) {
8349  QualType IntTy = Int->get()->getType().getUnqualifiedType();
8350 
8351  // Determine if the integer constant can be expressed as a floating point
8352  // number of the appropriate type.
8353  llvm::APSInt Result;
8354  bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8355  uint64_t Bits = 0;
8356  if (CstInt) {
8357  // Reject constants that would be truncated if they were converted to
8358  // the floating point type. Test by simple to/from conversion.
8359  // FIXME: Ideally the conversion to an APFloat and from an APFloat
8360  // could be avoided if there was a convertFromAPInt method
8361  // which could signal back if implicit truncation occurred.
8362  llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8363  Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8364  llvm::APFloat::rmTowardZero);
8365  llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8366  !IntTy->hasSignedIntegerRepresentation());
8367  bool Ignored = false;
8368  Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8369  &Ignored);
8370  if (Result != ConvertBack)
8371  return true;
8372  } else {
8373  // Reject types that cannot be fully encoded into the mantissa of
8374  // the float.
8375  Bits = S.Context.getTypeSize(IntTy);
8376  unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8377  S.Context.getFloatTypeSemantics(FloatTy));
8378  if (Bits > FloatPrec)
8379  return true;
8380  }
8381 
8382  return false;
8383 }
8384 
8385 /// Attempt to convert and splat Scalar into a vector whose types matches
8386 /// Vector following GCC conversion rules. The rule is that implicit
8387 /// conversion can occur when Scalar can be casted to match Vector's element
8388 /// type without causing truncation of Scalar.
8390  ExprResult *Vector) {
8391  QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8392  QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8393  const VectorType *VT = VectorTy->getAs<VectorType>();
8394 
8395  assert(!isa<ExtVectorType>(VT) &&
8396  "ExtVectorTypes should not be handled here!");
8397 
8398  QualType VectorEltTy = VT->getElementType();
8399 
8400  // Reject cases where the vector element type or the scalar element type are
8401  // not integral or floating point types.
8402  if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8403  return true;
8404 
8405  // The conversion to apply to the scalar before splatting it,
8406  // if necessary.
8407  CastKind ScalarCast = CK_NoOp;
8408 
8409  // Accept cases where the vector elements are integers and the scalar is
8410  // an integer.
8411  // FIXME: Notionally if the scalar was a floating point value with a precise
8412  // integral representation, we could cast it to an appropriate integer
8413  // type and then perform the rest of the checks here. GCC will perform
8414  // this conversion in some cases as determined by the input language.
8415  // We should accept it on a language independent basis.
8416  if (VectorEltTy->isIntegralType(S.Context) &&
8417  ScalarTy->isIntegralType(S.Context) &&
8418  S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8419 
8420  if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8421  return true;
8422 
8423  ScalarCast = CK_IntegralCast;
8424  } else if (VectorEltTy->isRealFloatingType()) {
8425  if (ScalarTy->isRealFloatingType()) {
8426 
8427  // Reject cases where the scalar type is not a constant and has a higher
8428  // Order than the vector element type.
8429  llvm::APFloat Result(0.0);
8430  bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8431  int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8432  if (!CstScalar && Order < 0)
8433  return true;
8434 
8435  // If the scalar cannot be safely casted to the vector element type,
8436  // reject it.
8437  if (CstScalar) {
8438  bool Truncated = false;
8439  Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8440  llvm::APFloat::rmNearestTiesToEven, &Truncated);
8441  if (Truncated)
8442  return true;
8443  }
8444 
8445  ScalarCast = CK_FloatingCast;
8446  } else if (ScalarTy->isIntegralType(S.Context)) {
8447  if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8448  return true;
8449 
8450  ScalarCast = CK_IntegralToFloating;
8451  } else
8452  return true;
8453  }
8454 
8455  // Adjust scalar if desired.
8456  if (Scalar) {
8457  if (ScalarCast != CK_NoOp)
8458  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8459  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8460  }
8461  return false;
8462 }
8463 
8465  SourceLocation Loc, bool IsCompAssign,
8466  bool AllowBothBool,
8467  bool AllowBoolConversions) {
8468  if (!IsCompAssign) {
8469  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8470  if (LHS.isInvalid())
8471  return QualType();
8472  }
8473  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8474  if (RHS.isInvalid())
8475  return QualType();
8476 
8477  // For conversion purposes, we ignore any qualifiers.
8478  // For example, "const float" and "float" are equivalent.
8479  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8480  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8481 
8482  const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8483  const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8484  assert(LHSVecType || RHSVecType);
8485 
8486  // AltiVec-style "vector bool op vector bool" combinations are allowed
8487  // for some operators but not others.
8488  if (!AllowBothBool &&
8489  LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8490  RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8491  return InvalidOperands(Loc, LHS, RHS);
8492 
8493  // If the vector types are identical, return.
8494  if (Context.hasSameType(LHSType, RHSType))
8495  return LHSType;
8496 
8497  // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8498  if (LHSVecType && RHSVecType &&
8499  Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8500  if (isa<ExtVectorType>(LHSVecType)) {
8501  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8502  return LHSType;
8503  }
8504 
8505  if (!IsCompAssign)
8506  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8507  return RHSType;
8508  }
8509 
8510  // AllowBoolConversions says that bool and non-bool AltiVec vectors
8511  // can be mixed, with the result being the non-bool type. The non-bool
8512  // operand must have integer element type.
8513  if (AllowBoolConversions && LHSVecType && RHSVecType &&
8514  LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8515  (Context.getTypeSize(LHSVecType->getElementType()) ==
8516  Context.getTypeSize(RHSVecType->getElementType()))) {
8517  if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8518  LHSVecType->getElementType()->isIntegerType() &&
8519  RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8520  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8521  return LHSType;
8522  }
8523  if (!IsCompAssign &&
8524  LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8525  RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8526  RHSVecType->getElementType()->isIntegerType()) {
8527  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8528  return RHSType;
8529  }
8530  }
8531 
8532  // If there's a vector type and a scalar, try to convert the scalar to
8533  // the vector element type and splat.
8534  unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8535  if (!RHSVecType) {
8536  if (isa<ExtVectorType>(LHSVecType)) {
8537  if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8538  LHSVecType->getElementType(), LHSType,
8539  DiagID))
8540  return LHSType;
8541  } else {
8542  if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8543  return LHSType;
8544  }
8545  }
8546  if (!LHSVecType) {
8547  if (isa<ExtVectorType>(RHSVecType)) {
8548  if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8549  LHSType, RHSVecType->getElementType(),
8550  RHSType, DiagID))
8551  return RHSType;
8552  } else {
8553  if (LHS.get()->getValueKind() == VK_LValue ||
8554  !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8555  return RHSType;
8556  }
8557  }
8558 
8559  // FIXME: The code below also handles conversion between vectors and
8560  // non-scalars, we should break this down into fine grained specific checks
8561  // and emit proper diagnostics.
8562  QualType VecType = LHSVecType ? LHSType : RHSType;
8563  const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8564  QualType OtherType = LHSVecType ? RHSType : LHSType;
8565  ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8566  if (isLaxVectorConversion(OtherType, VecType)) {
8567  // If we're allowing lax vector conversions, only the total (data) size
8568  // needs to be the same. For non compound assignment, if one of the types is
8569  // scalar, the result is always the vector type.
8570  if (!IsCompAssign) {
8571  *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8572  return VecType;
8573  // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8574  // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8575  // type. Note that this is already done by non-compound assignments in
8576  // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8577  // <1 x T> -> T. The result is also a vector type.
8578  } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8579  (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8580  ExprResult *RHSExpr = &RHS;
8581  *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8582  return VecType;
8583  }
8584  }
8585 
8586  // Okay, the expression is invalid.
8587 
8588  // If there's a non-vector, non-real operand, diagnose that.
8589  if ((!RHSVecType && !RHSType->isRealType()) ||
8590  (!LHSVecType && !LHSType->isRealType())) {
8591  Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8592  << LHSType << RHSType
8593  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8594  return QualType();
8595  }
8596 
8597  // OpenCL V1.1 6.2.6.p1:
8598  // If the operands are of more than one vector type, then an error shall
8599  // occur. Implicit conversions between vector types are not permitted, per
8600  // section 6.2.1.
8601  if (getLangOpts().OpenCL &&
8602  RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8603  LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8604  Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8605  << RHSType;
8606  return QualType();
8607  }
8608 
8609 
8610  // If there is a vector type that is not a ExtVector and a scalar, we reach
8611  // this point if scalar could not be converted to the vector's element type
8612  // without truncation.
8613  if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8614  (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8615  QualType Scalar = LHSVecType ? RHSType : LHSType;
8616  QualType Vector = LHSVecType ? LHSType : RHSType;
8617  unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8618  Diag(Loc,
8619  diag::err_typecheck_vector_not_convertable_implict_truncation)
8620  << ScalarOrVector << Scalar << Vector;
8621 
8622  return QualType();
8623  }
8624 
8625  // Otherwise, use the generic diagnostic.
8626  Diag(Loc, DiagID)
8627  << LHSType << RHSType
8628  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8629  return QualType();
8630 }
8631 
8632 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8633 // expression. These are mainly cases where the null pointer is used as an
8634 // integer instead of a pointer.
8635 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8636  SourceLocation Loc, bool IsCompare) {
8637  // The canonical way to check for a GNU null is with isNullPointerConstant,
8638  // but we use a bit of a hack here for speed; this is a relatively
8639  // hot path, and isNullPointerConstant is slow.
8640  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8641  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8642 
8643  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8644 
8645  // Avoid analyzing cases where the result will either be invalid (and
8646  // diagnosed as such) or entirely valid and not something to warn about.
8647  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8648  NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8649  return;
8650 
8651  // Comparison operations would not make sense with a null pointer no matter
8652  // what the other expression is.
8653  if (!IsCompare) {
8654  S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8655  << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8656  << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8657  return;
8658  }
8659 
8660  // The rest of the operations only make sense with a null pointer
8661  // if the other expression is a pointer.
8662  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8663  NonNullType->canDecayToPointerType())
8664  return;
8665 
8666  S.Diag(Loc, diag::warn_null_in_comparison_operation)
8667  << LHSNull /* LHS is NULL */ << NonNullType
8668  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8669 }
8670 
8672  ExprResult &RHS,
8673  SourceLocation Loc, bool IsDiv) {
8674  // Check for division/remainder by zero.
8675  llvm::APSInt RHSValue;
8676  if (!RHS.get()->isValueDependent() &&
8677  RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8678  S.DiagRuntimeBehavior(Loc, RHS.get(),
8679  S.PDiag(diag::warn_remainder_division_by_zero)
8680  << IsDiv << RHS.get()->getSourceRange());
8681 }
8682 
8684  SourceLocation Loc,
8685  bool IsCompAssign, bool IsDiv) {
8686  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8687 
8688  if (LHS.get()->getType()->isVectorType() ||
8689  RHS.get()->getType()->isVectorType())
8690  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8691  /*AllowBothBool*/getLangOpts().AltiVec,
8692  /*AllowBoolConversions*/false);
8693 
8694  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8695  if (LHS.isInvalid() || RHS.isInvalid())
8696  return QualType();
8697 
8698 
8699  if (compType.isNull() || !compType->isArithmeticType())
8700  return InvalidOperands(Loc, LHS, RHS);
8701  if (IsDiv)
8702  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8703  return compType;
8704 }
8705 
8707  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8708  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8709 
8710  if (LHS.get()->getType()->isVectorType() ||
8711  RHS.get()->getType()->isVectorType()) {
8712  if (LHS.get()->getType()->hasIntegerRepresentation() &&
8713  RHS.get()->getType()->hasIntegerRepresentation())
8714  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8715  /*AllowBothBool*/getLangOpts().AltiVec,
8716  /*AllowBoolConversions*/false);
8717  return InvalidOperands(Loc, LHS, RHS);
8718  }
8719 
8720  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8721  if (LHS.isInvalid() || RHS.isInvalid())
8722  return QualType();
8723 
8724  if (compType.isNull() || !compType->isIntegerType())
8725  return InvalidOperands(Loc, LHS, RHS);
8726  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8727  return compType;
8728 }
8729 
8730 /// Diagnose invalid arithmetic on two void pointers.
8732  Expr *LHSExpr, Expr *RHSExpr) {
8733  S.Diag(Loc, S.getLangOpts().CPlusPlus
8734  ? diag::err_typecheck_pointer_arith_void_type
8735  : diag::ext_gnu_void_ptr)
8736  << 1 /* two pointers */ << LHSExpr->getSourceRange()
8737  << RHSExpr->getSourceRange();
8738 }
8739 
8740 /// Diagnose invalid arithmetic on a void pointer.
8742  Expr *Pointer) {
8743  S.Diag(Loc, S.getLangOpts().CPlusPlus
8744  ? diag::err_typecheck_pointer_arith_void_type
8745  : diag::ext_gnu_void_ptr)
8746  << 0 /* one pointer */ << Pointer->getSourceRange();
8747 }
8748 
8749 /// Diagnose invalid arithmetic on a null pointer.
8750 ///
8751 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8752 /// idiom, which we recognize as a GNU extension.
8753 ///
8755  Expr *Pointer, bool IsGNUIdiom) {
8756  if (IsGNUIdiom)
8757  S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8758  << Pointer->getSourceRange();
8759  else
8760  S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8761  << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8762 }
8763 
8764 /// Diagnose invalid arithmetic on two function pointers.
8766  Expr *LHS, Expr *RHS) {
8767  assert(LHS->getType()->isAnyPointerType());
8768  assert(RHS->getType()->isAnyPointerType());
8769  S.Diag(Loc, S.getLangOpts().CPlusPlus
8770  ? diag::err_typecheck_pointer_arith_function_type
8771  : diag::ext_gnu_ptr_func_arith)
8772  << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8773  // We only show the second type if it differs from the first.
8774  << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8775  RHS->getType())
8776  << RHS->getType()->getPointeeType()
8777  << LHS->getSourceRange() << RHS->getSourceRange();
8778 }
8779 
8780 /// Diagnose invalid arithmetic on a function pointer.
8782  Expr *Pointer) {
8783  assert(Pointer->getType()->isAnyPointerType());
8784  S.Diag(Loc, S.getLangOpts().CPlusPlus
8785  ? diag::err_typecheck_pointer_arith_function_type
8786  : diag::ext_gnu_ptr_func_arith)
8787  << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8788  << 0 /* one pointer, so only one type */
8789  << Pointer->getSourceRange();
8790 }
8791 
8792 /// Emit error if Operand is incomplete pointer type
8793 ///
8794 /// \returns True if pointer has incomplete type
8796  Expr *Operand) {
8797  QualType ResType = Operand->getType();
8798  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8799  ResType = ResAtomicType->getValueType();
8800 
8801  assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8802  QualType PointeeTy = ResType->getPointeeType();
8803  return S.RequireCompleteType(Loc, PointeeTy,
8804  diag::err_typecheck_arithmetic_incomplete_type,
8805  PointeeTy, Operand->getSourceRange());
8806 }
8807 
8808 /// Check the validity of an arithmetic pointer operand.
8809 ///
8810 /// If the operand has pointer type, this code will check for pointer types
8811 /// which are invalid in arithmetic operations. These will be diagnosed
8812 /// appropriately, including whether or not the use is supported as an
8813 /// extension.
8814 ///
8815 /// \returns True when the operand is valid to use (even if as an extension).
8817  Expr *Operand) {
8818  QualType ResType = Operand->getType();
8819  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8820  ResType = ResAtomicType->getValueType();
8821 
8822  if (!ResType->isAnyPointerType()) return true;
8823 
8824  QualType PointeeTy = ResType->getPointeeType();
8825  if (PointeeTy->isVoidType()) {
8826  diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8827  return !S.getLangOpts().CPlusPlus;
8828  }
8829  if (PointeeTy->isFunctionType()) {
8830  diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8831  return !S.getLangOpts().CPlusPlus;
8832  }
8833 
8834  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8835 
8836  return true;
8837 }
8838 
8839 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8840 /// operands.
8841 ///
8842 /// This routine will diagnose any invalid arithmetic on pointer operands much
8843 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8844 /// for emitting a single diagnostic even for operations where both LHS and RHS
8845 /// are (potentially problematic) pointers.
8846 ///
8847 /// \returns True when the operand is valid to use (even if as an extension).
8849  Expr *LHSExpr, Expr *RHSExpr) {
8850  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8851  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8852  if (!isLHSPointer && !isRHSPointer) return true;
8853 
8854  QualType LHSPointeeTy, RHSPointeeTy;
8855  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8856  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8857 
8858  // if both are pointers check if operation is valid wrt address spaces
8859  if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8860  const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8861  const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8862  if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8863  S.Diag(Loc,
8864  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8865  << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8866  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8867  return false;
8868  }
8869  }
8870 
8871  // Check for arithmetic on pointers to incomplete types.
8872  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8873  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8874  if (isLHSVoidPtr || isRHSVoidPtr) {
8875  if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8876  else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8877  else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8878 
8879  return !S.getLangOpts().CPlusPlus;
8880  }
8881 
8882  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8883  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8884  if (isLHSFuncPtr || isRHSFuncPtr) {
8885  if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8886  else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8887  RHSExpr);
8888  else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8889 
8890  return !S.getLangOpts().CPlusPlus;
8891  }
8892 
8893  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8894  return false;
8895  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8896  return false;
8897 
8898  return true;
8899 }
8900 
8901 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8902 /// literal.
8903 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8904  Expr *LHSExpr, Expr *RHSExpr) {
8905  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8906  Expr* IndexExpr = RHSExpr;
8907  if (!StrExpr) {
8908  StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8909  IndexExpr = LHSExpr;
8910  }
8911 
8912  bool IsStringPlusInt = StrExpr &&
8914  if (!IsStringPlusInt || IndexExpr->isValueDependent())
8915  return;
8916 
8917  llvm::APSInt index;
8918  if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8919  unsigned StrLenWithNull = StrExpr->getLength() + 1;
8920  if (index.isNonNegative() &&
8921  index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8922  index.isUnsigned()))
8923  return;
8924  }
8925 
8926  SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8927  Self.Diag(OpLoc, diag::warn_string_plus_int)
8928  << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8929 
8930  // Only print a fixit for "str" + int, not for int + "str".
8931  if (IndexExpr == RHSExpr) {
8932  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8933  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8934  << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8936  << FixItHint::CreateInsertion(EndLoc, "]");
8937  } else
8938  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8939 }
8940 
8941 /// Emit a warning when adding a char literal to a string.
8942 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8943  Expr *LHSExpr, Expr *RHSExpr) {
8944  const Expr *StringRefExpr = LHSExpr;
8945  const CharacterLiteral *CharExpr =
8946  dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8947 
8948  if (!CharExpr) {
8949  CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8950  StringRefExpr = RHSExpr;
8951  }
8952 
8953  if (!CharExpr || !StringRefExpr)
8954  return;
8955 
8956  const QualType StringType = StringRefExpr->getType();
8957 
8958  // Return if not a PointerType.
8959  if (!StringType->isAnyPointerType())
8960  return;
8961 
8962  // Return if not a CharacterType.
8963  if (!StringType->getPointeeType()->isAnyCharacterType())
8964  return;
8965 
8966  ASTContext &Ctx = Self.getASTContext();
8967  SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8968 
8969  const QualType CharType = CharExpr->getType();
8970  if (!CharType->isAnyCharacterType() &&
8971  CharType->isIntegerType() &&
8972  llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8973  Self.Diag(OpLoc, diag::warn_string_plus_char)
8974  << DiagRange << Ctx.CharTy;
8975  } else {
8976  Self.Diag(OpLoc, diag::warn_string_plus_char)
8977  << DiagRange << CharExpr->getType();
8978  }
8979 
8980  // Only print a fixit for str + char, not for char + str.
8981  if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8982  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8983  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8984  << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8986  << FixItHint::CreateInsertion(EndLoc, "]");
8987  } else {
8988  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8989  }
8990 }
8991 
8992 /// Emit error when two pointers are incompatible.
8994  Expr *LHSExpr, Expr *RHSExpr) {
8995  assert(LHSExpr->getType()->isAnyPointerType());
8996  assert(RHSExpr->getType()->isAnyPointerType());
8997  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8998  << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8999  << RHSExpr->getSourceRange();
9000 }
9001 
9002 // C99 6.5.6
9005  QualType* CompLHSTy) {
9006  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9007 
9008  if (LHS.get()->getType()->isVectorType() ||
9009  RHS.get()->getType()->isVectorType()) {
9010  QualType compType = CheckVectorOperands(
9011  LHS, RHS, Loc, CompLHSTy,
9012  /*AllowBothBool*/getLangOpts().AltiVec,
9013  /*AllowBoolConversions*/getLangOpts().ZVector);
9014  if (CompLHSTy) *CompLHSTy = compType;
9015  return compType;
9016  }
9017 
9018  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9019  if (LHS.isInvalid() || RHS.isInvalid())
9020  return QualType();
9021 
9022  // Diagnose "string literal" '+' int and string '+' "char literal".
9023  if (Opc == BO_Add) {
9024  diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9025  diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9026  }
9027 
9028  // handle the common case first (both operands are arithmetic).
9029  if (!compType.isNull() && compType->isArithmeticType()) {
9030  if (CompLHSTy) *CompLHSTy = compType;
9031  return compType;
9032  }
9033 
9034  // Type-checking. Ultimately the pointer's going to be in PExp;
9035  // note that we bias towards the LHS being the pointer.
9036  Expr *PExp = LHS.get(), *IExp = RHS.get();
9037 
9038  bool isObjCPointer;
9039  if (PExp->getType()->isPointerType()) {
9040  isObjCPointer = false;
9041  } else if (PExp->getType()->isObjCObjectPointerType()) {
9042  isObjCPointer = true;
9043  } else {
9044  std::swap(PExp, IExp);
9045  if (PExp->getType()->isPointerType()) {
9046  isObjCPointer = false;
9047  } else if (PExp->getType()->isObjCObjectPointerType()) {
9048  isObjCPointer = true;
9049  } else {
9050  return InvalidOperands(Loc, LHS, RHS);
9051  }
9052  }
9053  assert(PExp->getType()->isAnyPointerType());
9054 
9055  if (!IExp->getType()->isIntegerType())
9056  return InvalidOperands(Loc, LHS, RHS);
9057 
9058  // Adding to a null pointer results in undefined behavior.
9061  // In C++ adding zero to a null pointer is defined.
9062  llvm::APSInt KnownVal;
9063  if (!getLangOpts().CPlusPlus ||
9064  (!IExp->isValueDependent() &&
9065  (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9066  // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9068  Context, BO_Add, PExp, IExp);
9069  diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9070  }
9071  }
9072 
9073  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9074  return QualType();
9075 
9076  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9077  return QualType();
9078 
9079  // Check array bounds for pointer arithemtic
9080  CheckArrayAccess(PExp, IExp);
9081 
9082  if (CompLHSTy) {
9083  QualType LHSTy = Context.isPromotableBitField(LHS.get());
9084  if (LHSTy.isNull()) {
9085  LHSTy = LHS.get()->getType();
9086  if (LHSTy->isPromotableIntegerType())
9087  LHSTy = Context.getPromotedIntegerType(LHSTy);
9088  }
9089  *CompLHSTy = LHSTy;
9090  }
9091 
9092  return PExp->getType();
9093 }
9094 
9095 // C99 6.5.6
9097  SourceLocation Loc,
9098  QualType* CompLHSTy) {
9099  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9100 
9101  if (LHS.get()->getType()->isVectorType() ||
9102  RHS.get()->getType()->isVectorType()) {
9103  QualType compType = CheckVectorOperands(
9104  LHS, RHS, Loc, CompLHSTy,
9105  /*AllowBothBool*/getLangOpts().AltiVec,
9106  /*AllowBoolConversions*/getLangOpts().ZVector);
9107  if (CompLHSTy) *CompLHSTy = compType;
9108  return compType;
9109  }
9110 
9111  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9112  if (LHS.isInvalid() || RHS.isInvalid())
9113  return QualType();
9114 
9115  // Enforce type constraints: C99 6.5.6p3.
9116 
9117  // Handle the common case first (both operands are arithmetic).
9118  if (!compType.isNull() && compType->isArithmeticType()) {
9119  if (CompLHSTy) *CompLHSTy = compType;
9120  return compType;
9121  }
9122 
9123  // Either ptr - int or ptr - ptr.
9124  if (LHS.get()->getType()->isAnyPointerType()) {
9125  QualType lpointee = LHS.get()->getType()->getPointeeType();
9126 
9127  // Diagnose bad cases where we step over interface counts.
9128  if (LHS.get()->getType()->isObjCObjectPointerType() &&
9129  checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9130  return QualType();
9131 
9132  // The result type of a pointer-int computation is the pointer type.
9133  if (RHS.get()->getType()->isIntegerType()) {
9134  // Subtracting from a null pointer should produce a warning.
9135  // The last argument to the diagnose call says this doesn't match the
9136  // GNU int-to-pointer idiom.
9137  if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9139  // In C++ adding zero to a null pointer is defined.
9140  llvm::APSInt KnownVal;
9141  if (!getLangOpts().CPlusPlus ||
9142  (!RHS.get()->isValueDependent() &&
9143  (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9144  diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9145  }
9146  }
9147 
9148  if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9149  return QualType();
9150 
9151  // Check array bounds for pointer arithemtic
9152  CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9153  /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9154 
9155  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9156  return LHS.get()->getType();
9157  }
9158 
9159  // Handle pointer-pointer subtractions.
9160  if (const PointerType *RHSPTy
9161  = RHS.get()->getType()->getAs<PointerType>()) {
9162  QualType rpointee = RHSPTy->getPointeeType();
9163 
9164  if (getLangOpts().CPlusPlus) {
9165  // Pointee types must be the same: C++ [expr.add]
9166  if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9167  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9168  }
9169  } else {
9170  // Pointee types must be compatible C99 6.5.6p3
9171  if (!Context.typesAreCompatible(
9172  Context.getCanonicalType(lpointee).getUnqualifiedType(),
9173  Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9174  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9175  return QualType();
9176  }
9177  }
9178 
9179  if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9180  LHS.get(), RHS.get()))
9181  return QualType();
9182 
9183  // FIXME: Add warnings for nullptr - ptr.
9184 
9185  // The pointee type may have zero size. As an extension, a structure or
9186  // union may have zero size or an array may have zero length. In this
9187  // case subtraction does not make sense.
9188  if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9189  CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9190  if (ElementSize.isZero()) {
9191  Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9192  << rpointee.getUnqualifiedType()
9193  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9194  }
9195  }
9196 
9197  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9198  return Context.getPointerDiffType();
9199  }
9200  }
9201 
9202  return InvalidOperands(Loc, LHS, RHS);
9203 }
9204 
9206  if (const EnumType *ET = T->getAs<EnumType>())
9207  return ET->getDecl()->isScoped();
9208  return false;
9209 }
9210 
9213  QualType LHSType) {
9214  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9215  // so skip remaining warnings as we don't want to modify values within Sema.
9216  if (S.getLangOpts().OpenCL)
9217  return;
9218 
9219  llvm::APSInt Right;
9220  // Check right/shifter operand
9221  if (RHS.get()->isValueDependent() ||
9222  !RHS.get()->EvaluateAsInt(Right, S.Context))
9223  return;
9224 
9225  if (Right.isNegative()) {
9226  S.DiagRuntimeBehavior(Loc, RHS.get(),
9227  S.PDiag(diag::warn_shift_negative)
9228  << RHS.get()->getSourceRange());
9229  return;
9230  }
9231  llvm::APInt LeftBits(Right.getBitWidth(),
9232  S.Context.getTypeSize(LHS.get()->getType()));
9233  if (Right.uge(LeftBits)) {
9234  S.DiagRuntimeBehavior(Loc, RHS.get(),
9235  S.PDiag(diag::warn_shift_gt_typewidth)
9236  << RHS.get()->getSourceRange());
9237  return;
9238  }
9239  if (Opc != BO_Shl)
9240  return;
9241 
9242  // When left shifting an ICE which is signed, we can check for overflow which
9243  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9244  // integers have defined behavior modulo one more than the maximum value
9245  // representable in the result type, so never warn for those.
9246  llvm::APSInt Left;
9247  if (LHS.get()->isValueDependent() ||
9248  LHSType->hasUnsignedIntegerRepresentation() ||
9249  !LHS.get()->EvaluateAsInt(Left, S.Context))
9250  return;
9251 
9252  // If LHS does not have a signed type and non-negative value
9253  // then, the behavior is undefined. Warn about it.
9254  if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9255  S.DiagRuntimeBehavior(Loc, LHS.get(),
9256  S.PDiag(diag::warn_shift_lhs_negative)
9257  << LHS.get()->getSourceRange());
9258  return;
9259  }
9260 
9261  llvm::APInt ResultBits =
9262  static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9263  if (LeftBits.uge(ResultBits))
9264  return;
9265  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9266  Result = Result.shl(Right);
9267 
9268  // Print the bit representation of the signed integer as an unsigned
9269  // hexadecimal number.
9270  SmallString<40> HexResult;
9271  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9272 
9273  // If we are only missing a sign bit, this is less likely to result in actual
9274  // bugs -- if the result is cast back to an unsigned type, it will have the
9275  // expected value. Thus we place this behind a different warning that can be
9276  // turned off separately if needed.
9277  if (LeftBits == ResultBits - 1) {
9278  S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9279  << HexResult << LHSType
9280  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9281  return;
9282  }
9283 
9284  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9285  << HexResult.str() << Result.getMinSignedBits() << LHSType
9286  << Left.getBitWidth() << LHS.get()->getSourceRange()
9287  << RHS.get()->getSourceRange();
9288 }
9289 
9290 /// Return the resulting type when a vector is shifted
9291 /// by a scalar or vector shift amount.
9293  SourceLocation Loc, bool IsCompAssign) {
9294  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9295  if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9296  !LHS.get()->getType()->isVectorType()) {
9297  S.Diag(Loc, diag::err_shift_rhs_only_vector)
9298  << RHS.get()->getType() << LHS.get()->getType()
9299  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9300  return QualType();
9301  }
9302 
9303  if (!IsCompAssign) {
9304  LHS = S.UsualUnaryConversions(LHS.get());
9305  if (LHS.isInvalid()) return QualType();
9306  }
9307 
9308  RHS = S.UsualUnaryConversions(RHS.get());
9309  if (RHS.isInvalid()) return QualType();
9310 
9311  QualType LHSType = LHS.get()->getType();
9312  // Note that LHS might be a scalar because the routine calls not only in
9313  // OpenCL case.
9314  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9315  QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9316 
9317  // Note that RHS might not be a vector.
9318  QualType RHSType = RHS.get()->getType();
9319  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9320  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9321 
9322  // The operands need to be integers.
9323  if (!LHSEleType->isIntegerType()) {
9324  S.Diag(Loc, diag::err_typecheck_expect_int)
9325  << LHS.get()->getType() << LHS.get()->getSourceRange();
9326  return QualType();
9327  }
9328 
9329  if (!RHSEleType->isIntegerType()) {
9330  S.Diag(Loc, diag::err_typecheck_expect_int)
9331  << RHS.get()->getType() << RHS.get()->getSourceRange();
9332  return QualType();
9333  }
9334 
9335  if (!LHSVecTy) {
9336  assert(RHSVecTy);
9337  if (IsCompAssign)
9338  return RHSType;
9339  if (LHSEleType != RHSEleType) {
9340  LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9341  LHSEleType = RHSEleType;
9342  }
9343  QualType VecTy =
9344  S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9345  LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9346  LHSType = VecTy;
9347  } else if (RHSVecTy) {
9348  // OpenCL v1.1 s6.3.j says that for vector types, the operators
9349  // are applied component-wise. So if RHS is a vector, then ensure
9350  // that the number of elements is the same as LHS...
9351  if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9352  S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9353  << LHS.get()->getType() << RHS.get()->getType()
9354  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9355  return QualType();
9356  }
9357  if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9358  const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9359  const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9360  if (LHSBT != RHSBT &&
9361  S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9362  S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9363  << LHS.get()->getType() << RHS.get()->getType()
9364  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9365  }
9366  }
9367  } else {
9368  // ...else expand RHS to match the number of elements in LHS.
9369  QualType VecTy =
9370  S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9371  RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9372  }
9373 
9374  return LHSType;
9375 }
9376 
9377 // C99 6.5.7
9380  bool IsCompAssign) {
9381  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9382 
9383  // Vector shifts promote their scalar inputs to vector type.
9384  if (LHS.get()->getType()->isVectorType() ||
9385  RHS.get()->getType()->isVectorType()) {
9386  if (LangOpts.ZVector) {
9387  // The shift operators for the z vector extensions work basically
9388  // like general shifts, except that neither the LHS nor the RHS is
9389  // allowed to be a "vector bool".
9390  if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9391  if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9392  return InvalidOperands(Loc, LHS, RHS);
9393  if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9394  if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9395  return InvalidOperands(Loc, LHS, RHS);
9396  }
9397  return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9398  }
9399 
9400  // Shifts don't perform usual arithmetic conversions, they just do integer
9401  // promotions on each operand. C99 6.5.7p3
9402 
9403  // For the LHS, do usual unary conversions, but then reset them away
9404  // if this is a compound assignment.
9405  ExprResult OldLHS = LHS;
9406  LHS = UsualUnaryConversions(LHS.get());
9407  if (LHS.isInvalid())
9408  return QualType();
9409  QualType LHSType = LHS.get()->getType();
9410  if (IsCompAssign) LHS = OldLHS;
9411 
9412  // The RHS is simpler.
9413  RHS = UsualUnaryConversions(RHS.get());
9414  if (RHS.isInvalid())
9415  return QualType();
9416  QualType RHSType = RHS.get()->getType();
9417 
9418  // C99 6.5.7p2: Each of the operands shall have integer type.
9419  if (!LHSType->hasIntegerRepresentation() ||
9420  !RHSType->hasIntegerRepresentation())
9421  return InvalidOperands(Loc, LHS, RHS);
9422 
9423  // C++0x: Don't allow scoped enums. FIXME: Use something better than
9424  // hasIntegerRepresentation() above instead of this.
9425  if (isScopedEnumerationType(LHSType) ||
9426  isScopedEnumerationType(RHSType)) {
9427  return InvalidOperands(Loc, LHS, RHS);
9428  }
9429  // Sanity-check shift operands
9430  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9431 
9432  // "The type of the result is that of the promoted left operand."
9433  return LHSType;
9434 }
9435 
9436 /// If two different enums are compared, raise a warning.
9437 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9438  Expr *RHS) {
9439  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9440  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9441 
9442  const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9443  if (!LHSEnumType)
9444  return;
9445  const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9446  if (!RHSEnumType)
9447  return;
9448 
9449  // Ignore anonymous enums.
9450  if (!LHSEnumType->getDecl()->getIdentifier() &&
9451  !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9452  return;
9453  if (!RHSEnumType->getDecl()->getIdentifier() &&
9454  !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9455  return;
9456 
9457  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9458  return;
9459 
9460  S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9461  << LHSStrippedType << RHSStrippedType
9462  << LHS->getSourceRange() << RHS->getSourceRange();
9463 }
9464 
9465 /// Diagnose bad pointer comparisons.
9467  ExprResult &LHS, ExprResult &RHS,
9468  bool IsError) {
9469  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9470  : diag::ext_typecheck_comparison_of_distinct_pointers)
9471  << LHS.get()->getType() << RHS.get()->getType()
9472  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9473 }
9474 
9475 /// Returns false if the pointers are converted to a composite type,
9476 /// true otherwise.
9478  ExprResult &LHS, ExprResult &RHS) {
9479  // C++ [expr.rel]p2:
9480  // [...] Pointer conversions (4.10) and qualification
9481  // conversions (4.4) are performed on pointer operands (or on
9482  // a pointer operand and a null pointer constant) to bring
9483  // them to their composite pointer type. [...]
9484  //
9485  // C++ [expr.eq]p1 uses the same notion for (in)equality
9486  // comparisons of pointers.
9487 
9488  QualType LHSType = LHS.get()->getType();
9489  QualType RHSType = RHS.get()->getType();
9490  assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9491  LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9492 
9493  QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9494  if (T.isNull()) {
9495  if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9496  (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9497  diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9498  else
9499  S.InvalidOperands(Loc, LHS, RHS);
9500  return true;
9501  }
9502 
9503  LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9504  RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9505  return false;
9506 }
9507 
9509  ExprResult &LHS,
9510  ExprResult &RHS,
9511  bool IsError) {
9512  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9513  : diag::ext_typecheck_comparison_of_fptr_to_void)
9514  << LHS.get()->getType() << RHS.get()->getType()
9515  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9516 }
9517 
9519  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9520  case Stmt::ObjCArrayLiteralClass:
9521  case Stmt::ObjCDictionaryLiteralClass:
9522  case Stmt::ObjCStringLiteralClass:
9523  case Stmt::ObjCBoxedExprClass:
9524  return true;
9525  default:
9526  // Note that ObjCBoolLiteral is NOT an object literal!
9527  return false;
9528  }
9529 }
9530 
9531 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9532  const ObjCObjectPointerType *Type =
9533  LHS->getType()->getAs<ObjCObjectPointerType>();
9534 
9535  // If this is not actually an Objective-C object, bail out.
9536  if (!Type)
9537  return false;
9538 
9539  // Get the LHS object's interface type.
9540  QualType InterfaceType = Type->getPointeeType();
9541 
9542  // If the RHS isn't an Objective-C object, bail out.
9543  if (!RHS->getType()->isObjCObjectPointerType())
9544  return false;
9545 
9546  // Try to find the -isEqual: method.
9547  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9548  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9549  InterfaceType,
9550  /*instance=*/true);
9551  if (!Method) {
9552  if (Type->isObjCIdType()) {
9553  // For 'id', just check the global pool.
9554  Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9555  /*receiverId=*/true);
9556  } else {
9557  // Check protocols.
9558  Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9559  /*instance=*/true);
9560  }
9561  }
9562 
9563  if (!Method)
9564  return false;
9565 
9566  QualType T = Method->parameters()[0]->getType();
9567  if (!T->isObjCObjectPointerType())
9568  return false;
9569 
9570  QualType R = Method->getReturnType();
9571  if (!R->isScalarType())
9572  return false;
9573 
9574  return true;
9575 }
9576 
9578  FromE = FromE->IgnoreParenImpCasts();
9579  switch (FromE->getStmtClass()) {
9580  default:
9581  break;
9582  case Stmt::ObjCStringLiteralClass:
9583  // "string literal"
9584  return LK_String;
9585  case Stmt::ObjCArrayLiteralClass:
9586  // "array literal"
9587  return LK_Array;
9588  case Stmt::ObjCDictionaryLiteralClass:
9589  // "dictionary literal"
9590  return LK_Dictionary;
9591  case Stmt::BlockExprClass:
9592  return LK_Block;
9593  case Stmt::ObjCBoxedExprClass: {
9594  Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9595  switch (Inner->getStmtClass()) {
9596  case Stmt::IntegerLiteralClass:
9597  case Stmt::FloatingLiteralClass:
9598  case Stmt::CharacterLiteralClass:
9599  case Stmt::ObjCBoolLiteralExprClass:
9600  case Stmt::CXXBoolLiteralExprClass:
9601  // "numeric literal"
9602  return LK_Numeric;
9603  case Stmt::ImplicitCastExprClass: {
9604  CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9605  // Boolean literals can be represented by implicit casts.
9606  if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9607  return LK_Numeric;
9608  break;
9609  }
9610  default:
9611  break;
9612  }
9613  return LK_Boxed;
9614  }
9615  }
9616  return LK_None;
9617 }
9618 
9620  ExprResult &LHS, ExprResult &RHS,
9622  Expr *Literal;
9623  Expr *Other;
9624  if (isObjCObjectLiteral(LHS)) {
9625  Literal = LHS.get();
9626  Other = RHS.get();
9627  } else {
9628  Literal = RHS.get();
9629  Other = LHS.get();
9630  }
9631 
9632  // Don't warn on comparisons against nil.
9633  Other = Other->IgnoreParenCasts();
9634  if (Other->isNullPointerConstant(S.getASTContext(),
9636  return;
9637 
9638  // This should be kept in sync with warn_objc_literal_comparison.
9639  // LK_String should always be after the other literals, since it has its own
9640  // warning flag.
9641  Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9642  assert(LiteralKind != Sema::LK_Block);
9643  if (LiteralKind == Sema::LK_None) {
9644  llvm_unreachable("Unknown Objective-C object literal kind");
9645  }
9646 
9647  if (LiteralKind == Sema::LK_String)
9648  S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9649  << Literal->getSourceRange();
9650  else
9651  S.Diag(Loc, diag::warn_objc_literal_comparison)
9652  << LiteralKind << Literal->getSourceRange();
9653 
9654  if (BinaryOperator::isEqualityOp(Opc) &&
9655  hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9656  SourceLocation Start = LHS.get()->getLocStart();
9657  SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9658  CharSourceRange OpRange =
9660 
9661  S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9662  << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9663  << FixItHint::CreateReplacement(OpRange, " isEqual:")
9664  << FixItHint::CreateInsertion(End, "]");
9665  }
9666 }
9667 
9668 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9670  ExprResult &RHS, SourceLocation Loc,
9671  BinaryOperatorKind Opc) {
9672  // Check that left hand side is !something.
9673  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9674  if (!UO || UO->getOpcode() != UO_LNot) return;
9675 
9676  // Only check if the right hand side is non-bool arithmetic type.
9677  if (RHS.get()->isKnownToHaveBooleanValue()) return;
9678 
9679  // Make sure that the something in !something is not bool.
9680  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9681  if (SubExpr->isKnownToHaveBooleanValue()) return;
9682 
9683  // Emit warning.
9684  bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9685  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9686  << Loc << IsBitwiseOp;
9687 
9688  // First note suggest !(x < y)
9689  SourceLocation FirstOpen = SubExpr->getLocStart();
9690  SourceLocation FirstClose = RHS.get()->getLocEnd();
9691  FirstClose = S.getLocForEndOfToken(FirstClose);
9692  if (FirstClose.isInvalid())
9693  FirstOpen = SourceLocation();
9694  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9695  << IsBitwiseOp
9696  << FixItHint::CreateInsertion(FirstOpen, "(")
9697  << FixItHint::CreateInsertion(FirstClose, ")");
9698 
9699  // Second note suggests (!x) < y
9700  SourceLocation SecondOpen = LHS.get()->getLocStart();
9701  SourceLocation SecondClose = LHS.get()->getLocEnd();
9702  SecondClose = S.getLocForEndOfToken(SecondClose);
9703  if (SecondClose.isInvalid())
9704  SecondOpen = SourceLocation();
9705  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9706  << FixItHint::CreateInsertion(SecondOpen, "(")
9707  << FixItHint::CreateInsertion(SecondClose, ")");
9708 }
9709 
9710 // Get the decl for a simple expression: a reference to a variable,
9711 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9713  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9714  return DR->getDecl();
9715  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9716  if (Ivar->isFreeIvar())
9717  return Ivar->getDecl();
9718  }
9719  if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9720  if (Mem->isImplicitAccess())
9721  return Mem->getMemberDecl();
9722  }
9723  return nullptr;
9724 }
9725 
9726 /// Diagnose some forms of syntactically-obvious tautological comparison.
9728  Expr *LHS, Expr *RHS,
9729  BinaryOperatorKind Opc) {
9730  Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9731  Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9732 
9733  QualType LHSType = LHS->getType();
9734  QualType RHSType = RHS->getType();
9735  if (LHSType->hasFloatingRepresentation() ||
9736  (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9737  LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9739  return;
9740 
9741  // Comparisons between two array types are ill-formed for operator<=>, so
9742  // we shouldn't emit any additional warnings about it.
9743  if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9744  return;
9745 
9746  // For non-floating point types, check for self-comparisons of the form
9747  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9748  // often indicate logic errors in the program.
9749  //
9750  // NOTE: Don't warn about comparison expressions resulting from macro
9751  // expansion. Also don't warn about comparisons which are only self
9752  // comparisons within a template instantiation. The warnings should catch
9753  // obvious cases in the definition of the template anyways. The idea is to
9754  // warn when the typed comparison operator will always evaluate to the same
9755  // result.
9756  ValueDecl *DL = getCompareDecl(LHSStripped);
9757  ValueDecl *DR = getCompareDecl(RHSStripped);
9758  if (DL && DR && declaresSameEntity(DL, DR)) {
9759  StringRef Result;
9760  switch (Opc) {
9761  case BO_EQ: case BO_LE: case BO_GE:
9762  Result = "true";
9763  break;
9764  case BO_NE: case BO_LT: case BO_GT:
9765  Result = "false";
9766  break;
9767  case BO_Cmp:
9768  Result = "'std::strong_ordering::equal'";
9769  break;
9770  default:
9771  break;
9772  }
9773  S.DiagRuntimeBehavior(Loc, nullptr,
9774  S.PDiag(diag::warn_comparison_always)
9775  << 0 /*self-comparison*/ << !Result.empty()
9776  << Result);
9777  } else if (DL && DR &&
9778  DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9779  !DL->isWeak() && !DR->isWeak()) {
9780  // What is it always going to evaluate to?
9781  StringRef Result;
9782  switch(Opc) {
9783  case BO_EQ: // e.g. array1 == array2
9784  Result = "false";
9785  break;
9786  case BO_NE: // e.g. array1 != array2
9787  Result = "true";
9788  break;
9789  default: // e.g. array1 <= array2
9790  // The best we can say is 'a constant'
9791  break;
9792  }
9793  S.DiagRuntimeBehavior(Loc, nullptr,
9794  S.PDiag(diag::warn_comparison_always)
9795  << 1 /*array comparison*/
9796  << !Result.empty() << Result);
9797  }
9798 
9799  if (isa<CastExpr>(LHSStripped))
9800  LHSStripped = LHSStripped->IgnoreParenCasts();
9801  if (isa<CastExpr>(RHSStripped))
9802  RHSStripped = RHSStripped->IgnoreParenCasts();
9803 
9804  // Warn about comparisons against a string constant (unless the other
9805  // operand is null); the user probably wants strcmp.
9806  Expr *LiteralString = nullptr;
9807  Expr *LiteralStringStripped = nullptr;
9808  if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9809  !RHSStripped->isNullPointerConstant(S.Context,
9811  LiteralString = LHS;
9812  LiteralStringStripped = LHSStripped;
9813  } else if ((isa<StringLiteral>(RHSStripped) ||
9814  isa<ObjCEncodeExpr>(RHSStripped)) &&
9815  !LHSStripped->isNullPointerConstant(S.Context,
9817  LiteralString = RHS;
9818  LiteralStringStripped = RHSStripped;
9819  }
9820 
9821  if (LiteralString) {
9822  S.DiagRuntimeBehavior(Loc, nullptr,
9823  S.PDiag(diag::warn_stringcompare)
9824  << isa<ObjCEncodeExpr>(LiteralStringStripped)
9825  << LiteralString->getSourceRange());
9826  }
9827 }
9828 
9830  switch (CK) {
9831  default: {
9832 #ifndef NDEBUG
9833  llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9834  << "\n";
9835 #endif
9836  llvm_unreachable("unhandled cast kind");
9837  }
9838  case CK_UserDefinedConversion:
9839  return ICK_Identity;
9840  case CK_LValueToRValue:
9841  return ICK_Lvalue_To_Rvalue;
9842  case CK_ArrayToPointerDecay:
9843  return ICK_Array_To_Pointer;
9844  case CK_FunctionToPointerDecay:
9845  return ICK_Function_To_Pointer;
9846  case CK_IntegralCast:
9847  return ICK_Integral_Conversion;
9848  case CK_FloatingCast:
9849  return ICK_Floating_Conversion;
9850  case CK_IntegralToFloating:
9851  case CK_FloatingToIntegral:
9852  return ICK_Floating_Integral;
9853  case CK_IntegralComplexCast:
9854  case CK_FloatingComplexCast:
9855  case CK_FloatingComplexToIntegralComplex:
9856  case CK_IntegralComplexToFloatingComplex:
9857  return ICK_Complex_Conversion;
9858  case CK_FloatingComplexToReal:
9859  case CK_FloatingRealToComplex:
9860  case CK_IntegralComplexToReal:
9861  case CK_IntegralRealToComplex:
9862  return ICK_Complex_Real;
9863  }
9864 }
9865 
9867  QualType FromType,
9868  SourceLocation Loc) {
9869  // Check for a narrowing implicit conversion.
9872  SCS.setToType(0, FromType);
9873  SCS.setToType(1, ToType);
9874  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9875  SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9876 
9877  APValue PreNarrowingValue;
9878  QualType PreNarrowingType;
9879  switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9880  PreNarrowingType,
9881  /*IgnoreFloatToIntegralConversion*/ true)) {
9883  // Implicit conversion to a narrower type, but the expression is
9884  // value-dependent so we can't tell whether it's actually narrowing.
9885  case NK_Not_Narrowing:
9886  return false;
9887 
9888  case NK_Constant_Narrowing:
9889  // Implicit conversion to a narrower type, and the value is not a constant
9890  // expression.
9891  S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9892  << /*Constant*/ 1
9893  << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9894  return true;
9895 
9896  case NK_Variable_Narrowing:
9897  // Implicit conversion to a narrower type, and the value is not a constant
9898  // expression.
9899  case NK_Type_Narrowing:
9900  S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9901  << /*Constant*/ 0 << FromType << ToType;
9902  // TODO: It's not a constant expression, but what if the user intended it
9903  // to be? Can we produce notes to help them figure out why it isn't?
9904  return true;
9905  }
9906  llvm_unreachable("unhandled case in switch");
9907 }
9908 
9910  ExprResult &LHS,
9911  ExprResult &RHS,
9912  SourceLocation Loc) {
9913  using CCT = ComparisonCategoryType;
9914 
9915  QualType LHSType = LHS.get()->getType();
9916  QualType RHSType = RHS.get()->getType();
9917  // Dig out the original argument type and expression before implicit casts
9918  // were applied. These are the types/expressions we need to check the
9919  // [expr.spaceship] requirements against.
9920  ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9921  ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9922  QualType LHSStrippedType = LHSStripped.get()->getType();
9923  QualType RHSStrippedType = RHSStripped.get()->getType();
9924 
9925  // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9926  // other is not, the program is ill-formed.
9927  if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9928  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9929  return QualType();
9930  }
9931 
9932  int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9933  RHSStrippedType->isEnumeralType();
9934  if (NumEnumArgs == 1) {
9935  bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9936  QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9937  if (OtherTy->hasFloatingRepresentation()) {
9938  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9939  return QualType();
9940  }
9941  }
9942  if (NumEnumArgs == 2) {
9943  // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9944  // type E, the operator yields the result of converting the operands
9945  // to the underlying type of E and applying <=> to the converted operands.
9946  if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9947  S.InvalidOperands(Loc, LHS, RHS);
9948  return QualType();
9949  }
9950  QualType IntType =
9951  LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
9952  assert(IntType->isArithmeticType());
9953 
9954  // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
9955  // promote the boolean type, and all other promotable integer types, to
9956  // avoid this.
9957  if (IntType->isPromotableIntegerType())
9958  IntType = S.Context.getPromotedIntegerType(IntType);
9959 
9960  LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
9961  RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
9962  LHSType = RHSType = IntType;
9963  }
9964 
9965  // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
9966  // usual arithmetic conversions are applied to the operands.
9968  if (LHS.isInvalid() || RHS.isInvalid())
9969  return QualType();
9970  if (Type.isNull())
9971  return S.InvalidOperands(Loc, LHS, RHS);
9972  assert(Type->isArithmeticType() || Type->isEnumeralType());
9973 
9974  bool HasNarrowing = checkThreeWayNarrowingConversion(
9975  S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
9976  HasNarrowing |= checkThreeWayNarrowingConversion(
9977  S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
9978  if (HasNarrowing)
9979  return QualType();
9980 
9981  assert(!Type.isNull() && "composite type for <=> has not been set");
9982 
9983  auto TypeKind = [&]() {
9984  if (const ComplexType *CT = Type->getAs<ComplexType>()) {
9985  if (CT->getElementType()->hasFloatingRepresentation())
9986  return CCT::WeakEquality;
9987  return CCT::StrongEquality;
9988  }
9989  if (Type->isIntegralOrEnumerationType())
9990  return CCT::StrongOrdering;
9991  if (Type->hasFloatingRepresentation())
9992  return CCT::PartialOrdering;
9993  llvm_unreachable("other types are unimplemented");
9994  }();
9995 
9996  return S.CheckComparisonCategoryType(TypeKind, Loc);
9997 }
9998 
10000  ExprResult &RHS,
10001  SourceLocation Loc,
10002  BinaryOperatorKind Opc) {
10003  if (Opc == BO_Cmp)
10004  return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10005 
10006  // C99 6.5.8p3 / C99 6.5.9p4
10008  if (LHS.isInvalid() || RHS.isInvalid())
10009  return QualType();
10010  if (Type.isNull())
10011  return S.InvalidOperands(Loc, LHS, RHS);
10012  assert(Type->isArithmeticType() || Type->isEnumeralType());
10013 
10014  checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10015 
10017  return S.InvalidOperands(Loc, LHS, RHS);
10018 
10019  // Check for comparisons of floating point operands using != and ==.
10021  S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10022 
10023  // The result of comparisons is 'bool' in C++, 'int' in C.
10024  return S.Context.getLogicalOperationType();
10025 }
10026 
10027 // C99 6.5.8, C++ [expr.rel]
10029  SourceLocation Loc,
10030  BinaryOperatorKind Opc) {
10031  bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10032  bool IsThreeWay = Opc == BO_Cmp;
10033  auto IsAnyPointerType = [](ExprResult E) {
10034  QualType Ty = E.get()->getType();
10035  return Ty->isPointerType() || Ty->isMemberPointerType();
10036  };
10037 
10038  // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10039  // type, array-to-pointer, ..., conversions are performed on both operands to
10040  // bring them to their composite type.
10041  // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10042  // any type-related checks.
10043  if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10044  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10045  if (LHS.isInvalid())
10046  return QualType();
10047  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10048  if (RHS.isInvalid())
10049  return QualType();
10050  } else {
10051  LHS = DefaultLvalueConversion(LHS.get());
10052  if (LHS.isInvalid())
10053  return QualType();
10054  RHS = DefaultLvalueConversion(RHS.get());
10055  if (RHS.isInvalid())
10056  return QualType();
10057  }
10058 
10059  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10060 
10061  // Handle vector comparisons separately.
10062  if (LHS.get()->getType()->isVectorType() ||
10063  RHS.get()->getType()->isVectorType())
10064  return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10065 
10066  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10067  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10068 
10069  QualType LHSType = LHS.get()->getType();
10070  QualType RHSType = RHS.get()->getType();
10071  if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10072  (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10073  return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10074 
10075  const Expr::NullPointerConstantKind LHSNullKind =
10076  LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10077  const Expr::NullPointerConstantKind RHSNullKind =
10078  RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10079  bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10080  bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10081 
10082  auto computeResultTy = [&]() {
10083  if (Opc != BO_Cmp)
10084  return Context.getLogicalOperationType();
10085  assert(getLangOpts().CPlusPlus);
10086  assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10087 
10088  QualType CompositeTy = LHS.get()->getType();
10089  assert(!CompositeTy->isReferenceType());
10090 
10091  auto buildResultTy = [&](ComparisonCategoryType Kind) {
10092  return CheckComparisonCategoryType(Kind, Loc);
10093  };
10094 
10095  // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10096  // pointer type, a pointer-to-member type, or std::nullptr_t, the
10097  // result is of type std::strong_equality
10098  if (CompositeTy->isFunctionPointerType() ||
10099  CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10100  // FIXME: consider making the function pointer case produce
10101  // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10102  // and direction polls
10103  return buildResultTy(ComparisonCategoryType::StrongEquality);
10104 
10105  // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10106  // pointer type, p <=> q is of type std::strong_ordering.
10107  if (CompositeTy->isPointerType()) {
10108  // P0946R0: Comparisons between a null pointer constant and an object
10109  // pointer result in std::strong_equality
10110  if (LHSIsNull != RHSIsNull)
10111  return buildResultTy(ComparisonCategoryType::StrongEquality);
10112  return buildResultTy(ComparisonCategoryType::StrongOrdering);
10113  }
10114  // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10115  // TODO: Extend support for operator<=> to ObjC types.
10116  return InvalidOperands(Loc, LHS, RHS);
10117  };
10118 
10119 
10120  if (!IsRelational && LHSIsNull != RHSIsNull) {
10121  bool IsEquality = Opc == BO_EQ;
10122  if (RHSIsNull)
10123  DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10124  RHS.get()->getSourceRange());
10125  else
10126  DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10127  LHS.get()->getSourceRange());
10128  }
10129 
10130  if ((LHSType->isIntegerType() && !LHSIsNull) ||
10131  (RHSType->isIntegerType() && !RHSIsNull)) {
10132  // Skip normal pointer conversion checks in this case; we have better
10133  // diagnostics for this below.
10134  } else if (getLangOpts().CPlusPlus) {
10135  // Equality comparison of a function pointer to a void pointer is invalid,
10136  // but we allow it as an extension.
10137  // FIXME: If we really want to allow this, should it be part of composite
10138  // pointer type computation so it works in conditionals too?
10139  if (!IsRelational &&
10140  ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10141  (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10142  // This is a gcc extension compatibility comparison.
10143  // In a SFINAE context, we treat this as a hard error to maintain
10144  // conformance with the C++ standard.
10146  *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10147 
10148  if (isSFINAEContext())
10149  return QualType();
10150 
10151  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10152  return computeResultTy();
10153  }
10154 
10155  // C++ [expr.eq]p2:
10156  // If at least one operand is a pointer [...] bring them to their
10157  // composite pointer type.
10158  // C++ [expr.spaceship]p6
10159  // If at least one of the operands is of pointer type, [...] bring them
10160  // to their composite pointer type.
10161  // C++ [expr.rel]p2:
10162  // If both operands are pointers, [...] bring them to their composite
10163  // pointer type.
10164  if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10165  (IsRelational ? 2 : 1) &&
10166  (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10167  RHSType->isObjCObjectPointerType()))) {
10168  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10169  return QualType();
10170  return computeResultTy();
10171  }
10172  } else if (LHSType->isPointerType() &&
10173  RHSType->isPointerType()) { // C99 6.5.8p2
10174  // All of the following pointer-related warnings are GCC extensions, except
10175  // when handling null pointer constants.
10176  QualType LCanPointeeTy =
10177  LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10178  QualType RCanPointeeTy =
10179  RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10180 
10181  // C99 6.5.9p2 and C99 6.5.8p2
10182  if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10183  RCanPointeeTy.getUnqualifiedType())) {
10184  // Valid unless a relational comparison of function pointers
10185  if (IsRelational && LCanPointeeTy->isFunctionType()) {
10186  Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10187  << LHSType << RHSType << LHS.get()->getSourceRange()
10188  << RHS.get()->getSourceRange();
10189  }
10190  } else if (!IsRelational &&
10191  (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10192  // Valid unless comparison between non-null pointer and function pointer
10193  if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10194  && !LHSIsNull && !RHSIsNull)
10195  diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10196  /*isError*/false);
10197  } else {
10198  // Invalid
10199  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10200  }
10201  if (LCanPointeeTy != RCanPointeeTy) {
10202  // Treat NULL constant as a special case in OpenCL.
10203  if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10204  const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10205  if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10206  Diag(Loc,
10207  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10208  << LHSType << RHSType << 0 /* comparison */
10209  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10210  }
10211  }
10212  LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10213  LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10214  CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10215  : CK_BitCast;
10216  if (LHSIsNull && !RHSIsNull)
10217  LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10218  else
10219  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10220  }
10221  return computeResultTy();
10222  }
10223 
10224  if (getLangOpts().CPlusPlus) {
10225  // C++ [expr.eq]p4:
10226  // Two operands of type std::nullptr_t or one operand of type
10227  // std::nullptr_t and the other a null pointer constant compare equal.
10228  if (!IsRelational && LHSIsNull && RHSIsNull) {
10229  if (LHSType->isNullPtrType()) {
10230  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10231  return computeResultTy();
10232  }
10233  if (RHSType->isNullPtrType()) {
10234  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10235  return computeResultTy();
10236  }
10237  }
10238 
10239  // Comparison of Objective-C pointers and block pointers against nullptr_t.
10240  // These aren't covered by the composite pointer type rules.
10241  if (!IsRelational && RHSType->isNullPtrType() &&
10242  (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10243  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10244  return computeResultTy();
10245  }
10246  if (!IsRelational && LHSType->isNullPtrType() &&
10247  (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10248  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10249  return computeResultTy();
10250  }
10251 
10252  if (IsRelational &&
10253  ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10254  (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10255  // HACK: Relational comparison of nullptr_t against a pointer type is
10256  // invalid per DR583, but we allow it within std::less<> and friends,
10257  // since otherwise common uses of it break.
10258  // FIXME: Consider removing this hack once LWG fixes std::less<> and
10259  // friends to have std::nullptr_t overload candidates.
10260  DeclContext *DC = CurContext;
10261  if (isa<FunctionDecl>(DC))
10262  DC = DC->getParent();
10263  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10264  if (CTSD->isInStdNamespace() &&
10265  llvm::StringSwitch<bool>(CTSD->getName())
10266  .Cases("less", "less_equal", "greater", "greater_equal", true)
10267  .Default(false)) {
10268  if (RHSType->isNullPtrType())
10269  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10270  else
10271  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10272  return computeResultTy();
10273  }
10274  }
10275  }
10276 
10277  // C++ [expr.eq]p2:
10278  // If at least one operand is a pointer to member, [...] bring them to
10279  // their composite pointer type.
10280  if (!IsRelational &&
10281  (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10282  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10283  return QualType();
10284  else
10285  return computeResultTy();
10286  }
10287  }
10288 
10289  // Handle block pointer types.
10290  if (!IsRelational && LHSType->isBlockPointerType() &&
10291  RHSType->isBlockPointerType()) {
10292  QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10293  QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10294 
10295  if (!LHSIsNull && !RHSIsNull &&
10296  !Context.typesAreCompatible(lpointee, rpointee)) {
10297  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10298  << LHSType << RHSType << LHS.get()->getSourceRange()
10299  << RHS.get()->getSourceRange();
10300  }
10301  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10302  return computeResultTy();
10303  }
10304 
10305  // Allow block pointers to be compared with null pointer constants.
10306  if (!IsRelational
10307  && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10308  || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10309  if (!LHSIsNull && !RHSIsNull) {
10310  if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10311  ->getPointeeType()->isVoidType())
10312  || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10313  ->getPointeeType()->isVoidType())))
10314  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10315  << LHSType << RHSType << LHS.get()->getSourceRange()
10316  << RHS.get()->getSourceRange();
10317  }
10318  if (LHSIsNull && !RHSIsNull)
10319  LHS = ImpCastExprToType(LHS.get(), RHSType,
10320  RHSType->isPointerType() ? CK_BitCast
10321  : CK_AnyPointerToBlockPointerCast);
10322  else
10323  RHS = ImpCastExprToType(RHS.get(), LHSType,
10324  LHSType->isPointerType() ? CK_BitCast
10325  : CK_AnyPointerToBlockPointerCast);
10326  return computeResultTy();
10327  }
10328 
10329  if (LHSType->isObjCObjectPointerType() ||
10330  RHSType->isObjCObjectPointerType()) {
10331  const PointerType *LPT = LHSType->getAs<PointerType>();
10332  const PointerType *RPT = RHSType->getAs<PointerType>();
10333  if (LPT || RPT) {
10334  bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10335  bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10336 
10337  if (!LPtrToVoid && !RPtrToVoid &&
10338  !Context.typesAreCompatible(LHSType, RHSType)) {
10339  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10340  /*isError*/false);
10341  }
10342  if (LHSIsNull && !RHSIsNull) {
10343  Expr *E = LHS.get();
10344  if (getLangOpts().ObjCAutoRefCount)
10345  CheckObjCConversion(SourceRange(), RHSType, E,
10346  CCK_ImplicitConversion);
10347  LHS = ImpCastExprToType(E, RHSType,
10348  RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10349  }
10350  else {
10351  Expr *E = RHS.get();
10352  if (getLangOpts().ObjCAutoRefCount)
10353  CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10354  /*Diagnose=*/true,
10355  /*DiagnoseCFAudited=*/false, Opc);
10356  RHS = ImpCastExprToType(E, LHSType,
10357  LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10358  }
10359  return computeResultTy();
10360  }
10361  if (LHSType->isObjCObjectPointerType() &&
10362  RHSType->isObjCObjectPointerType()) {
10363  if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10364  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10365  /*isError*/false);
10366  if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10367  diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10368 
10369  if (LHSIsNull && !RHSIsNull)
10370  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10371  else
10372  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10373  return computeResultTy();
10374  }
10375 
10376  if (!IsRelational && LHSType->isBlockPointerType() &&
10377  RHSType->isBlockCompatibleObjCPointerType(Context)) {
10378  LHS = ImpCastExprToType(LHS.get(), RHSType,
10379  CK_BlockPointerToObjCPointerCast);
10380  return computeResultTy();
10381  } else if (!IsRelational &&
10382  LHSType->isBlockCompatibleObjCPointerType(Context) &&
10383  RHSType->isBlockPointerType()) {
10384  RHS = ImpCastExprToType(RHS.get(), LHSType,
10385  CK_BlockPointerToObjCPointerCast);
10386  return computeResultTy();
10387  }
10388  }
10389  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10390  (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10391  unsigned DiagID = 0;
10392  bool isError = false;
10393  if (LangOpts.DebuggerSupport) {
10394  // Under a debugger, allow the comparison of pointers to integers,
10395  // since users tend to want to compare addresses.
10396  } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10397  (RHSIsNull && RHSType->isIntegerType())) {
10398  if (IsRelational) {
10399  isError = getLangOpts().CPlusPlus;
10400  DiagID =
10401  isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10402  : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10403  }
10404  } else if (getLangOpts().CPlusPlus) {
10405  DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10406  isError = true;
10407  } else if (IsRelational)
10408  DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10409  else
10410  DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10411 
10412  if (DiagID) {
10413  Diag(Loc, DiagID)
10414  << LHSType << RHSType << LHS.get()->getSourceRange()
10415  << RHS.get()->getSourceRange();
10416  if (isError)
10417  return QualType();
10418  }
10419 
10420  if (LHSType->isIntegerType())
10421  LHS = ImpCastExprToType(LHS.get(), RHSType,
10422  LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10423  else
10424  RHS = ImpCastExprToType(RHS.get(), LHSType,
10425  RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10426  return computeResultTy();
10427  }
10428 
10429  // Handle block pointers.
10430  if (!IsRelational && RHSIsNull
10431  && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10432  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10433  return computeResultTy();
10434  }
10435  if (!IsRelational && LHSIsNull
10436  && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10437  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10438  return computeResultTy();
10439  }
10440 
10441  if (getLangOpts().OpenCLVersion >= 200) {
10442  if (LHSIsNull && RHSType->isQueueT()) {
10443  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10444  return computeResultTy();
10445  }
10446 
10447  if (LHSType->isQueueT() && RHSIsNull) {
10448  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10449  return computeResultTy();
10450  }
10451  }
10452 
10453  return InvalidOperands(Loc, LHS, RHS);
10454 }
10455 
10456 // Return a signed ext_vector_type that is of identical size and number of
10457 // elements. For floating point vectors, return an integer type of identical
10458 // size and number of elements. In the non ext_vector_type case, search from
10459 // the largest type to the smallest type to avoid cases where long long == long,
10460 // where long gets picked over long long.
10462  const VectorType *VTy = V->getAs<VectorType>();
10463  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10464 
10465  if (isa<ExtVectorType>(VTy)) {
10466  if (TypeSize == Context.getTypeSize(Context.CharTy))
10467  return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10468  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10469  return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10470  else if (TypeSize == Context.getTypeSize(Context.IntTy))
10471  return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10472  else if (TypeSize == Context.getTypeSize(Context.LongTy))
10473  return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10474  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10475  "Unhandled vector element size in vector compare");
10476  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10477  }
10478 
10479  if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10480  return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10482  else if (TypeSize == Context.getTypeSize(Context.LongTy))
10483  return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10485  else if (TypeSize == Context.getTypeSize(Context.IntTy))
10486  return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10488  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10489  return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10491  assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10492  "Unhandled vector element size in vector compare");
10493  return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10495 }
10496 
10497 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10498 /// operates on extended vector types. Instead of producing an IntTy result,
10499 /// like a scalar comparison, a vector comparison produces a vector of integer
10500 /// types.
10502  SourceLocation Loc,
10503  BinaryOperatorKind Opc) {
10504  // Check to make sure we're operating on vectors of the same type and width,
10505  // Allowing one side to be a scalar of element type.
10506  QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10507  /*AllowBothBool*/true,
10508  /*AllowBoolConversions*/getLangOpts().ZVector);
10509  if (vType.isNull())
10510  return vType;
10511 
10512  QualType LHSType = LHS.get()->getType();
10513 
10514  // If AltiVec, the comparison results in a numeric type, i.e.
10515  // bool for C++, int for C
10516  if (getLangOpts().AltiVec &&
10518  return Context.getLogicalOperationType();
10519 
10520  // For non-floating point types, check for self-comparisons of the form
10521  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10522  // often indicate logic errors in the program.
10523  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10524 
10525  // Check for comparisons of floating point operands using != and ==.
10526  if (BinaryOperator::isEqualityOp(Opc) &&
10527  LHSType->hasFloatingRepresentation()) {
10528  assert(RHS.get()->getType()->hasFloatingRepresentation());
10529  CheckFloatComparison(Loc, LHS.get(), RHS.get());
10530  }
10531 
10532  // Return a signed type for the vector.
10533  return GetSignedVectorType(vType);
10534 }
10535 
10537  SourceLocation Loc) {
10538  // Ensure that either both operands are of the same vector type, or
10539  // one operand is of a vector type and the other is of its element type.
10540  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10541  /*AllowBothBool*/true,
10542  /*AllowBoolConversions*/false);
10543  if (vType.isNull())
10544  return InvalidOperands(Loc, LHS, RHS);
10545  if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10546  vType->hasFloatingRepresentation())
10547  return InvalidOperands(Loc, LHS, RHS);
10548  // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10549  // usage of the logical operators && and || with vectors in C. This
10550  // check could be notionally dropped.
10551  if (!getLangOpts().CPlusPlus &&
10552  !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10553  return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10554 
10555  return GetSignedVectorType(LHS.get()->getType());
10556 }
10557 
10559  SourceLocation Loc,
10560  BinaryOperatorKind Opc) {
10561  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10562 
10563  bool IsCompAssign =
10564  Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10565 
10566  if (LHS.get()->getType()->isVectorType() ||
10567  RHS.get()->getType()->isVectorType()) {
10568  if (LHS.get()->getType()->hasIntegerRepresentation() &&
10569  RHS.get()->getType()->hasIntegerRepresentation())
10570  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10571  /*AllowBothBool*/true,
10572  /*AllowBoolConversions*/getLangOpts().ZVector);
10573  return InvalidOperands(Loc, LHS, RHS);
10574  }
10575 
10576  if (Opc == BO_And)
10577  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10578 
10579  ExprResult LHSResult = LHS, RHSResult = RHS;
10580  QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10581  IsCompAssign);
10582  if (LHSResult.isInvalid() || RHSResult.isInvalid())
10583  return QualType();
10584  LHS = LHSResult.get();
10585  RHS = RHSResult.get();
10586 
10587  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10588  return compType;
10589  return InvalidOperands(Loc, LHS, RHS);
10590 }
10591 
10592 // C99 6.5.[13,14]
10594  SourceLocation Loc,
10595  BinaryOperatorKind Opc) {
10596  // Check vector operands differently.
10597  if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10598  return CheckVectorLogicalOperands(LHS, RHS, Loc);
10599 
10600  // Diagnose cases where the user write a logical and/or but probably meant a
10601  // bitwise one. We do this when the LHS is a non-bool integer and the RHS
10602  // is a constant.
10603  if (LHS.get()->getType()->isIntegerType() &&
10604  !LHS.get()->getType()->isBooleanType() &&
10605  RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10606  // Don't warn in macros or template instantiations.
10607  !Loc.isMacroID() && !inTemplateInstantiation()) {
10608  // If the RHS can be constant folded, and if it constant folds to something
10609  // that isn't 0 or 1 (which indicate a potential logical operation that
10610  // happened to fold to true/false) then warn.
10611  // Parens on the RHS are ignored.
10612  llvm::APSInt Result;
10613  if (RHS.get()->EvaluateAsInt(Result, Context))
10614  if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10615  !RHS.get()->getExprLoc().isMacroID()) ||
10616  (Result != 0 && Result != 1)) {
10617  Diag(Loc, diag::warn_logical_instead_of_bitwise)
10618  << RHS.get()->getSourceRange()
10619  << (Opc == BO_LAnd ? "&&" : "||");
10620  // Suggest replacing the logical operator with the bitwise version
10621  Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10622  << (Opc == BO_LAnd ? "&" : "|")
10624  Loc, getLocForEndOfToken(Loc)),
10625  Opc == BO_LAnd ? "&" : "|");
10626  if (Opc == BO_LAnd)
10627  // Suggest replacing "Foo() && kNonZero" with "Foo()"
10628  Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10630  SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10631  RHS.get()->getLocEnd()));
10632  }
10633  }
10634 
10635  if (!Context.getLangOpts().CPlusPlus) {
10636  // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10637  // not operate on the built-in scalar and vector float types.
10638  if (Context.getLangOpts().OpenCL &&
10639  Context.getLangOpts().OpenCLVersion < 120) {
10640  if (LHS.get()->getType()->isFloatingType() ||
10641  RHS.get()->getType()->isFloatingType())
10642  return InvalidOperands(Loc, LHS, RHS);
10643  }
10644 
10645  LHS = UsualUnaryConversions(LHS.get());
10646  if (LHS.isInvalid())
10647  return QualType();
10648 
10649  RHS = UsualUnaryConversions(RHS.get());
10650  if (RHS.isInvalid())
10651  return QualType();
10652 
10653  if (!LHS.get()->getType()->isScalarType() ||
10654  !RHS.get()->getType()->isScalarType())
10655  return InvalidOperands(Loc, LHS, RHS);
10656 
10657  return Context.IntTy;
10658  }
10659 
10660  // The following is safe because we only use this method for
10661  // non-overloadable operands.
10662 
10663  // C++ [expr.log.and]p1
10664  // C++ [expr.log.or]p1
10665  // The operands are both contextually converted to type bool.
10666  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10667  if (LHSRes.isInvalid())
10668  return InvalidOperands(Loc, LHS, RHS);
10669  LHS = LHSRes;
10670 
10671  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10672  if (RHSRes.isInvalid())
10673  return InvalidOperands(Loc, LHS, RHS);
10674  RHS = RHSRes;
10675 
10676  // C++ [expr.log.and]p2
10677  // C++ [expr.log.or]p2
10678  // The result is a bool.
10679  return Context.BoolTy;
10680 }
10681 
10682 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10683  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10684  if (!ME) return false;
10685  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10686  ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10688  if (!Base) return false;
10689  return Base->getMethodDecl() != nullptr;
10690 }
10691 
10692 /// Is the given expression (which must be 'const') a reference to a
10693 /// variable which was originally non-const, but which has become
10694 /// 'const' due to being captured within a block?
10697  assert(E->isLValue() && E->getType().isConstQualified());
10698  E = E->IgnoreParens();
10699 
10700  // Must be a reference to a declaration from an enclosing scope.
10701  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10702  if (!DRE) return NCCK_None;
10703  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10704 
10705  // The declaration must be a variable which is not declared 'const'.
10706  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10707  if (!var) return NCCK_None;
10708  if (var->getType().isConstQualified()) return NCCK_None;
10709  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10710 
10711  // Decide whether the first capture was for a block or a lambda.
10712  DeclContext *DC = S.CurContext, *Prev = nullptr;
10713  // Decide whether the first capture was for a block or a lambda.
10714  while (DC) {
10715  // For init-capture, it is possible that the variable belongs to the
10716  // template pattern of the current context.
10717  if (auto *FD = dyn_cast<FunctionDecl>(DC))
10718  if (var->isInitCapture() &&
10719  FD->getTemplateInstantiationPattern() == var->getDeclContext())
10720  break;
10721  if (DC == var->getDeclContext())
10722  break;
10723  Prev = DC;
10724  DC = DC->getParent();
10725  }
10726  // Unless we have an init-capture, we've gone one step too far.
10727  if (!var->isInitCapture())
10728  DC = Prev;
10729  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10730 }
10731 
10732 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10733  Ty = Ty.getNonReferenceType();
10734  if (IsDereference && Ty->isPointerType())
10735  Ty = Ty->getPointeeType();
10736  return !Ty.isConstQualified();
10737 }
10738 
10739 // Update err_typecheck_assign_const and note_typecheck_assign_const
10740 // when this enum is changed.
10741 enum {
10747  ConstUnknown, // Keep as last element
10748 };
10749 
10750 /// Emit the "read-only variable not assignable" error and print notes to give
10751 /// more information about why the variable is not assignable, such as pointing
10752 /// to the declaration of a const variable, showing that a method is const, or
10753 /// that the function is returning a const reference.
10754 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10755  SourceLocation Loc) {
10756  SourceRange ExprRange = E->getSourceRange();
10757 
10758  // Only emit one error on the first const found. All other consts will emit
10759  // a note to the error.
10760  bool DiagnosticEmitted = false;
10761 
10762  // Track if the current expression is the result of a dereference, and if the
10763  // next checked expression is the result of a dereference.
10764  bool IsDereference = false;
10765  bool NextIsDereference = false;
10766 
10767  // Loop to process MemberExpr chains.
10768  while (true) {
10769  IsDereference = NextIsDereference;
10770 
10771  E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10772  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10773  NextIsDereference = ME->isArrow();
10774  const ValueDecl *VD = ME->getMemberDecl();
10775  if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10776  // Mutable fields can be modified even if the class is const.
10777  if (Field->isMutable()) {
10778  assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10779  break;
10780  }
10781 
10782  if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10783  if (!DiagnosticEmitted) {
10784  S.Diag(Loc, diag::err_typecheck_assign_const)
10785  << ExprRange << ConstMember << false /*static*/ << Field
10786  << Field->getType();
10787  DiagnosticEmitted = true;
10788  }
10789  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10790  << ConstMember << false /*static*/ << Field << Field->getType()
10791  << Field->getSourceRange();
10792  }
10793  E = ME->getBase();
10794  continue;
10795  } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10796  if (VDecl->getType().isConstQualified()) {
10797  if (!DiagnosticEmitted) {
10798  S.Diag(Loc, diag::err_typecheck_assign_const)
10799  << ExprRange << ConstMember << true /*static*/ << VDecl
10800  << VDecl->getType();
10801  DiagnosticEmitted = true;
10802  }
10803  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10804  << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10805  << VDecl->getSourceRange();
10806  }
10807  // Static fields do not inherit constness from parents.
10808  break;
10809  }
10810  break; // End MemberExpr
10811  } else if (const ArraySubscriptExpr *ASE =
10812  dyn_cast<ArraySubscriptExpr>(E)) {
10813  E = ASE->getBase()->IgnoreParenImpCasts();
10814  continue;
10815  } else if (const ExtVectorElementExpr *EVE =
10816  dyn_cast<ExtVectorElementExpr>(E)) {
10817  E = EVE->getBase()->IgnoreParenImpCasts();
10818  continue;
10819  }
10820  break;
10821  }
10822 
10823  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10824  // Function calls
10825  const FunctionDecl *FD = CE->getDirectCallee();
10826  if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10827  if (!DiagnosticEmitted) {
10828  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10829  << ConstFunction << FD;
10830  DiagnosticEmitted = true;
10831  }
10833  diag::note_typecheck_assign_const)
10834  << ConstFunction << FD << FD->getReturnType()
10835  << FD->getReturnTypeSourceRange();
10836  }
10837  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10838  // Point to variable declaration.
10839  if (const ValueDecl *VD = DRE->getDecl()) {
10840  if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10841  if (!DiagnosticEmitted) {
10842  S.Diag(Loc, diag::err_typecheck_assign_const)
10843  << ExprRange << ConstVariable << VD << VD->getType();
10844  DiagnosticEmitted = true;
10845  }
10846  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10847  << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10848  }
10849  }
10850  } else if (isa<CXXThisExpr>(E)) {
10851  if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10852  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10853  if (MD->isConst()) {
10854  if (!DiagnosticEmitted) {
10855  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10856  << ConstMethod << MD;
10857  DiagnosticEmitted = true;
10858  }
10859  S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10860  << ConstMethod << MD << MD->getSourceRange();
10861  }
10862  }
10863  }
10864  }
10865 
10866  if (DiagnosticEmitted)
10867  return;
10868 
10869  // Can't determine a more specific message, so display the generic error.
10870  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10871 }
10872 
10877 };
10878 
10879 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10880  const RecordType *Ty,
10881  SourceLocation Loc, SourceRange Range,
10882  OriginalExprKind OEK,
10883  bool &DiagnosticEmitted,
10884  bool IsNested = false) {
10885  // We walk the record hierarchy breadth-first to ensure that we print
10886  // diagnostics in field nesting order.
10887  // First, check every field for constness.
10888  for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10889  if (Field->getType().isConstQualified()) {
10890  if (!DiagnosticEmitted) {
10891  S.Diag(Loc, diag::err_typecheck_assign_const)
10892  << Range << NestedConstMember << OEK << VD
10893  << IsNested << Field;
10894  DiagnosticEmitted = true;
10895  }
10896  S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10897  << NestedConstMember << IsNested << Field
10898  << Field->getType() << Field->getSourceRange();
10899  }
10900  }
10901  // Then, recurse.
10902  for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10903  QualType FTy = Field->getType();
10904  if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10905  DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10906  OEK, DiagnosticEmitted, true);
10907  }
10908 }
10909 
10910 /// Emit an error for the case where a record we are trying to assign to has a
10911 /// const-qualified field somewhere in its hierarchy.
10912 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10913  SourceLocation Loc) {
10914  QualType Ty = E->getType();
10915  assert(Ty->isRecordType() && "lvalue was not record?");
10916  SourceRange Range = E->getSourceRange();
10917  const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10918  bool DiagEmitted = false;
10919 
10920  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10921  DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10922  Range, OEK_Member, DiagEmitted);
10923  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10924  DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10925  Range, OEK_Variable, DiagEmitted);
10926  else
10927  DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10928  Range, OEK_LValue, DiagEmitted);
10929  if (!DiagEmitted)
10930  DiagnoseConstAssignment(S, E, Loc);
10931 }
10932 
10933 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
10934 /// emit an error and return true. If so, return false.
10936  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10937 
10939 
10940  SourceLocation OrigLoc = Loc;
10942  &Loc);
10943  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10945  if (IsLV == Expr::MLV_Valid)
10946  return false;
10947 
10948  unsigned DiagID = 0;
10949  bool NeedType = false;
10950  switch (IsLV) { // C99 6.5.16p2
10952  // Use a specialized diagnostic when we're assigning to an object
10953  // from an enclosing function or block.
10955  if (NCCK == NCCK_Block)
10956  DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10957  else
10958  DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10959  break;
10960  }
10961 
10962  // In ARC, use some specialized diagnostics for occasions where we
10963  // infer 'const'. These are always pseudo-strong variables.
10964  if (S.getLangOpts().ObjCAutoRefCount) {
10965  DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10966  if (declRef && isa<VarDecl>(declRef->getDecl())) {
10967  VarDecl *var = cast<VarDecl>(declRef->getDecl());
10968 
10969  // Use the normal diagnostic if it's pseudo-__strong but the
10970  // user actually wrote 'const'.
10971  if (var->isARCPseudoStrong() &&
10972  (!var->getTypeSourceInfo() ||
10973  !var->getTypeSourceInfo()->getType().isConstQualified())) {
10974  // There are two pseudo-strong cases:
10975  // - self
10976  ObjCMethodDecl *method = S.getCurMethodDecl();
10977  if (method && var == method->getSelfDecl())
10978  DiagID = method->isClassMethod()
10979  ? diag::err_typecheck_arc_assign_self_class_method
10980  : diag::err_typecheck_arc_assign_self;
10981 
10982  // - fast enumeration variables
10983  else
10984  DiagID = diag::err_typecheck_arr_assign_enumeration;
10985 
10986  SourceRange Assign;
10987  if (Loc != OrigLoc)
10988  Assign = SourceRange(OrigLoc, OrigLoc);
10989  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10990  // We need to preserve the AST regardless, so migration tool
10991  // can do its job.
10992  return false;
10993  }
10994  }
10995  }
10996 
10997  // If none of the special cases above are triggered, then this is a
10998  // simple const assignment.
10999  if (DiagID == 0) {
11000  DiagnoseConstAssignment(S, E, Loc);
11001  return true;
11002  }
11003 
11004  break;
11006  DiagnoseConstAssignment(S, E, Loc);
11007  return true;
11009  DiagnoseRecursiveConstFields(S, E, Loc);
11010  return true;
11011  case Expr::MLV_ArrayType:
11013  DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11014  NeedType = true;
11015  break;
11017  DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11018  NeedType = true;
11019  break;
11020  case Expr::MLV_LValueCast:
11021  DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11022  break;
11023  case Expr::MLV_Valid:
11024  llvm_unreachable("did not take early return for MLV_Valid");
11028  DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11029  break;
11032  return S.RequireCompleteType(Loc, E->getType(),
11033  diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11035  DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11036  break;
11038  llvm_unreachable("readonly properties should be processed differently");
11040  DiagID = diag::err_readonly_message_assignment;
11041  break;
11043  DiagID = diag::err_no_subobject_property_setting;
11044  break;
11045  }
11046 
11047  SourceRange Assign;
11048  if (Loc != OrigLoc)
11049  Assign = SourceRange(OrigLoc, OrigLoc);
11050  if (NeedType)
11051  S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11052  else
11053  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11054  return true;
11055 }
11056 
11057 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11058  SourceLocation Loc,
11059  Sema &Sema) {
11060  if (Sema.inTemplateInstantiation())
11061  return;
11062  if (Sema.isUnevaluatedContext())
11063  return;
11064  if (Loc.isInvalid() || Loc.isMacroID())
11065  return;
11066  if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11067  return;
11068 
11069  // C / C++ fields
11070  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11071  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11072  if (ML && MR) {
11073  if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11074  return;
11075  const ValueDecl *LHSDecl =
11076  cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11077  const ValueDecl *RHSDecl =
11078  cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11079  if (LHSDecl != RHSDecl)
11080  return;
11081  if (LHSDecl->getType().isVolatileQualified())
11082  return;
11083  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11084  if (RefTy->getPointeeType().isVolatileQualified())
11085  return;
11086 
11087  Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11088  }
11089 
11090  // Objective-C instance variables
11091  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11092  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11093  if (OL && OR && OL->getDecl() == OR->getDecl()) {
11094  DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11095  DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11096  if (RL && RR && RL->getDecl() == RR->getDecl())
11097  Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11098  }
11099 }
11100 
11101 // C99 6.5.16.1
11103  SourceLocation Loc,
11104  QualType CompoundType) {
11105  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11106 
11107  // Verify that LHS is a modifiable lvalue, and emit error if not.
11108  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11109  return QualType();
11110 
11111  QualType LHSType = LHSExpr->getType();
11112  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11113  CompoundType;
11114  // OpenCL v1.2 s6.1.1.1 p2:
11115  // The half data type can only be used to declare a pointer to a buffer that
11116  // contains half values
11117  if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11118  LHSType->isHalfType()) {
11119  Diag(Loc, diag::err_opencl_half_load_store) << 1
11120  << LHSType.getUnqualifiedType();
11121  return QualType();
11122  }
11123 
11124  AssignConvertType ConvTy;
11125  if (CompoundType.isNull()) {
11126  Expr *RHSCheck = RHS.get();
11127 
11128  CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11129 
11130  QualType LHSTy(LHSType);
11131  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11132  if (RHS.isInvalid())
11133  return QualType();
11134  // Special case of NSObject attributes on c-style pointer types.
11135  if (ConvTy == IncompatiblePointer &&
11136  ((Context.isObjCNSObjectType(LHSType) &&
11137  RHSType->isObjCObjectPointerType()) ||
11138  (Context.isObjCNSObjectType(RHSType) &&
11139  LHSType->isObjCObjectPointerType())))
11140  ConvTy = Compatible;
11141 
11142  if (ConvTy == Compatible &&
11143  LHSType->isObjCObjectType())
11144  Diag(Loc, diag::err_objc_object_assignment)
11145  << LHSType;
11146 
11147  // If the RHS is a unary plus or minus, check to see if they = and + are
11148  // right next to each other. If so, the user may have typo'd "x =+ 4"
11149  // instead of "x += 4".
11150  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11151  RHSCheck = ICE->getSubExpr();
11152  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11153  if ((UO->getOpcode() == UO_Plus ||
11154  UO->getOpcode() == UO_Minus) &&
11155  Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11156  // Only if the two operators are exactly adjacent.
11157  Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11158  // And there is a space or other character before the subexpr of the
11159  // unary +/-. We don't want to warn on "x=-1".
11160  Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
11161  UO->getSubExpr()->getLocStart().isFileID()) {
11162  Diag(Loc, diag::warn_not_compound_assign)
11163  << (UO->getOpcode() == UO_Plus ? "+" : "-")
11164  << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11165  }
11166  }
11167 
11168  if (ConvTy == Compatible) {
11169  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11170  // Warn about retain cycles where a block captures the LHS, but
11171  // not if the LHS is a simple variable into which the block is
11172  // being stored...unless that variable can be captured by reference!
11173  const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11174  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11175  if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11176  checkRetainCycles(LHSExpr, RHS.get());
11177  }
11178 
11179  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11180  LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11181  // It is safe to assign a weak reference into a strong variable.
11182  // Although this code can still have problems:
11183  // id x = self.weakProp;
11184  // id y = self.weakProp;
11185  // we do not warn to warn spuriously when 'x' and 'y' are on separate
11186  // paths through the function. This should be revisited if
11187  // -Wrepeated-use-of-weak is made flow-sensitive.
11188  // For ObjCWeak only, we do not warn if the assign is to a non-weak
11189  // variable, which will be valid for the current autorelease scope.
11190  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11191  RHS.get()->getLocStart()))
11192  getCurFunction()->markSafeWeakUse(RHS.get());
11193 
11194  } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11195  checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11196  }
11197  }
11198  } else {
11199  // Compound assignment "x += y"
11200  ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11201  }
11202 
11203  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11204  RHS.get(), AA_Assigning))
11205  return QualType();
11206 
11207  CheckForNullPointerDereference(*this, LHSExpr);
11208 
11209  // C99 6.5.16p3: The type of an assignment expression is the type of the
11210  // left operand unless the left operand has qualified type, in which case
11211  // it is the unqualified version of the type of the left operand.
11212  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11213  // is converted to the type of the assignment expression (above).
11214  // C++ 5.17p1: the type of the assignment expression is that of its left
11215  // operand.
11216  return (getLangOpts().CPlusPlus
11217  ? LHSType : LHSType.getUnqualifiedType());
11218 }
11219 
11220 // Only ignore explicit casts to void.
11221 static bool IgnoreCommaOperand(const Expr *E) {
11222  E = E->IgnoreParens();
11223 
11224  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11225  if (CE->getCastKind() == CK_ToVoid) {
11226  return true;
11227  }
11228  }
11229 
11230  return false;
11231 }
11232 
11233 // Look for instances where it is likely the comma operator is confused with
11234 // another operator. There is a whitelist of acceptable expressions for the
11235 // left hand side of the comma operator, otherwise emit a warning.
11237  // No warnings in macros
11238  if (Loc.isMacroID())
11239  return;
11240 
11241  // Don't warn in template instantiations.
11242  if (inTemplateInstantiation())
11243  return;
11244 
11245  // Scope isn't fine-grained enough to whitelist the specific cases, so
11246  // instead, skip more than needed, then call back into here with the
11247  // CommaVisitor in SemaStmt.cpp.
11248  // The whitelisted locations are the initialization and increment portions
11249  // of a for loop. The additional checks are on the condition of
11250  // if statements, do/while loops, and for loops.
11251  const unsigned ForIncrementFlags =
11253  const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11254  const unsigned ScopeFlags = getCurScope()->getFlags();
11255  if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11256  (ScopeFlags & ForInitFlags) == ForInitFlags)
11257  return;
11258 
11259  // If there are multiple comma operators used together, get the RHS of the
11260  // of the comma operator as the LHS.
11261  while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11262  if (BO->getOpcode() != BO_Comma)
11263  break;
11264  LHS = BO->getRHS();
11265  }
11266 
11267  // Only allow some expressions on LHS to not warn.
11268  if (IgnoreCommaOperand(LHS))
11269  return;
11270 
11271  Diag(Loc, diag::warn_comma_operator);
11272  Diag(LHS->getLocStart(), diag::note_cast_to_void)
11273  << LHS->getSourceRange()
11275  LangOpts.CPlusPlus ? "static_cast<void>("
11276  : "(void)(")
11277  << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
11278  ")");
11279 }
11280 
11281 // C99 6.5.17
11283  SourceLocation Loc) {
11284  LHS = S.CheckPlaceholderExpr(LHS.get());
11285  RHS = S.CheckPlaceholderExpr(RHS.get());
11286  if (LHS.isInvalid() || RHS.isInvalid())
11287  return QualType();
11288 
11289  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11290  // operands, but not unary promotions.
11291  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11292 
11293  // So we treat the LHS as a ignored value, and in C++ we allow the
11294  // containing site to determine what should be done with the RHS.
11295  LHS = S.IgnoredValueConversions(LHS.get());
11296  if (LHS.isInvalid())
11297  return QualType();
11298 
11299  S.DiagnoseUnusedExprResult(LHS.get());
11300 
11301  if (!S.getLangOpts().CPlusPlus) {
11303  if (RHS.isInvalid())
11304  return QualType();
11305  if (!RHS.get()->getType()->isVoidType())
11306  S.RequireCompleteType(Loc, RHS.get()->getType(),
11307  diag::err_incomplete_type);
11308  }
11309 
11310  if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11311  S.DiagnoseCommaOperator(LHS.get(), Loc);
11312 
11313  return RHS.get()->getType();
11314 }
11315 
11316 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11317 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11319  ExprValueKind &VK,
11320  ExprObjectKind &OK,
11321  SourceLocation OpLoc,
11322  bool IsInc, bool IsPrefix) {
11323  if (Op->isTypeDependent())
11324  return S.Context.DependentTy;
11325 
11326  QualType ResType = Op->getType();
11327  // Atomic types can be used for increment / decrement where the non-atomic
11328  // versions can, so ignore the _Atomic() specifier for the purpose of
11329  // checking.
11330  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11331  ResType = ResAtomicType->getValueType();
11332 
11333  assert(!ResType.isNull() && "no type for increment/decrement expression");
11334 
11335  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11336  // Decrement of bool is not allowed.
11337  if (!IsInc) {
11338  S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11339  return QualType();
11340  }
11341  // Increment of bool sets it to true, but is deprecated.
11342  S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11343  : diag::warn_increment_bool)
11344  << Op->getSourceRange();
11345  } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11346  // Error on enum increments and decrements in C++ mode
11347  S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11348  return QualType();
11349  } else if (ResType->isRealType()) {
11350  // OK!
11351  } else if (ResType->isPointerType()) {
11352  // C99 6.5.2.4p2, 6.5.6p2
11353  if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11354  return QualType();
11355  } else if (ResType->isObjCObjectPointerType()) {
11356  // On modern runtimes, ObjC pointer arithmetic is forbidden.
11357  // Otherwise, we just need a complete type.
11358  if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11359  checkArithmeticOnObjCPointer(S, OpLoc, Op))
11360  return QualType();
11361  } else if (ResType->isAnyComplexType()) {
11362  // C99 does not support ++/-- on complex types, we allow as an extension.
11363  S.Diag(OpLoc, diag::ext_integer_increment_complex)
11364  << ResType << Op->getSourceRange();
11365  } else if (ResType->isPlaceholderType()) {
11366  ExprResult PR = S.CheckPlaceholderExpr(Op);
11367  if (PR.isInvalid()) return QualType();
11368  return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11369  IsInc, IsPrefix);
11370  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11371  // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11372  } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11373  (ResType->getAs<VectorType>()->getVectorKind() !=
11375  // The z vector extensions allow ++ and -- for non-bool vectors.
11376  } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11377  ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11378  // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11379  } else {
11380  S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11381  << ResType << int(IsInc) << Op->getSourceRange();
11382  return QualType();
11383  }
11384  // At this point, we know we have a real, complex or pointer type.
11385  // Now make sure the operand is a modifiable lvalue.
11386  if (CheckForModifiableLvalue(Op, OpLoc, S))
11387  return QualType();
11388  // In C++, a prefix increment is the same type as the operand. Otherwise
11389  // (in C or with postfix), the increment is the unqualified type of the
11390  // operand.
11391  if (IsPrefix && S.getLangOpts().CPlusPlus) {
11392  VK = VK_LValue;
11393  OK = Op->getObjectKind();
11394  return ResType;
11395  } else {
11396  VK = VK_RValue;
11397  return ResType.getUnqualifiedType();
11398  }
11399 }
11400 
11401 
11402 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11403 /// This routine allows us to typecheck complex/recursive expressions
11404 /// where the declaration is needed for type checking. We only need to
11405 /// handle cases when the expression references a function designator
11406 /// or is an lvalue. Here are some examples:
11407 /// - &(x) => x
11408 /// - &*****f => f for f a function designator.
11409 /// - &s.xx => s
11410 /// - &s.zz[1].yy -> s, if zz is an array
11411 /// - *(x + 1) -> x, if x is an array
11412 /// - &"123"[2] -> 0
11413 /// - & __real__ x -> x
11415  switch (E->getStmtClass()) {
11416  case Stmt::DeclRefExprClass:
11417  return cast<DeclRefExpr>(E)->getDecl();
11418  case Stmt::MemberExprClass:
11419  // If this is an arrow operator, the address is an offset from
11420  // the base's value, so the object the base refers to is
11421  // irrelevant.
11422  if (cast<MemberExpr>(E)->isArrow())
11423  return nullptr;
11424  // Otherwise, the expression refers to a part of the base
11425  return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11426  case Stmt::ArraySubscriptExprClass: {
11427  // FIXME: This code shouldn't be necessary! We should catch the implicit
11428  // promotion of register arrays earlier.
11429  Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11430  if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11431  if (ICE->getSubExpr()->getType()->isArrayType())
11432  return getPrimaryDecl(ICE->getSubExpr());
11433  }
11434  return nullptr;
11435  }
11436  case Stmt::UnaryOperatorClass: {
11437  UnaryOperator *UO = cast<UnaryOperator>(E);
11438 
11439  switch(UO->getOpcode()) {
11440  case UO_Real:
11441  case UO_Imag:
11442  case UO_Extension:
11443  return getPrimaryDecl(UO->getSubExpr());
11444  default:
11445  return nullptr;
11446  }
11447  }
11448  case Stmt::ParenExprClass:
11449  return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11450  case Stmt::ImplicitCastExprClass:
11451  // If the result of an implicit cast is an l-value, we care about
11452  // the sub-expression; otherwise, the result here doesn't matter.
11453  return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11454  default:
11455  return nullptr;
11456  }
11457 }
11458 
11459 namespace {
11460  enum {
11461  AO_Bit_Field = 0,
11462  AO_Vector_Element = 1,
11463  AO_Property_Expansion = 2,
11464  AO_Register_Variable = 3,
11465  AO_No_Error = 4
11466  };
11467 }
11468 /// Diagnose invalid operand for address of operations.
11469 ///
11470 /// \param Type The type of operand which cannot have its address taken.
11472  Expr *E, unsigned Type) {
11473  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11474 }
11475 
11476 /// CheckAddressOfOperand - The operand of & must be either a function
11477 /// designator or an lvalue designating an object. If it is an lvalue, the
11478 /// object cannot be declared with storage class register or be a bit field.
11479 /// Note: The usual conversions are *not* applied to the operand of the &
11480 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11481 /// In C++, the operand might be an overloaded function name, in which case
11482 /// we allow the '&' but retain the overloaded-function type.
11484  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11485  if (PTy->getKind() == BuiltinType::Overload) {
11486  Expr *E = OrigOp.get()->IgnoreParens();
11487  if (!isa<OverloadExpr>(E)) {
11488  assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11489  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11490  << OrigOp.get()->getSourceRange();
11491  return QualType();
11492  }
11493 
11494  OverloadExpr *Ovl = cast<OverloadExpr>(E);
11495  if (isa<UnresolvedMemberExpr>(Ovl))
11496  if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11497  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11498  << OrigOp.get()->getSourceRange();
11499  return QualType();
11500  }
11501 
11502  return Context.OverloadTy;
11503  }
11504 
11505  if (PTy->getKind() == BuiltinType::UnknownAny)
11506  return Context.UnknownAnyTy;
11507 
11508  if (PTy->getKind() == BuiltinType::BoundMember) {
11509  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11510  << OrigOp.get()->getSourceRange();
11511  return QualType();
11512  }
11513 
11514  OrigOp = CheckPlaceholderExpr(OrigOp.get());
11515  if (OrigOp.isInvalid()) return QualType();
11516  }
11517 
11518  if (OrigOp.get()->isTypeDependent())
11519  return Context.DependentTy;
11520 
11521  assert(!OrigOp.get()->getType()->isPlaceholderType());
11522 
11523  // Make sure to ignore parentheses in subsequent checks
11524  Expr *op = OrigOp.get()->IgnoreParens();
11525 
11526  // In OpenCL captures for blocks called as lambda functions
11527  // are located in the private address space. Blocks used in
11528  // enqueue_kernel can be located in a different address space
11529  // depending on a vendor implementation. Thus preventing
11530  // taking an address of the capture to avoid invalid AS casts.
11531  if (LangOpts.OpenCL) {
11532  auto* VarRef = dyn_cast<DeclRefExpr>(op);
11533  if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11534  Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11535  return QualType();
11536  }
11537  }
11538 
11539  if (getLangOpts().C99) {
11540  // Implement C99-only parts of addressof rules.
11541  if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11542  if (uOp->getOpcode() == UO_Deref)
11543  // Per C99 6.5.3.2, the address of a deref always returns a valid result
11544  // (assuming the deref expression is valid).
11545  return uOp->getSubExpr()->getType();
11546  }
11547  // Technically, there should be a check for array subscript
11548  // expressions here, but the result of one is always an lvalue anyway.
11549  }
11550  ValueDecl *dcl = getPrimaryDecl(op);
11551 
11552  if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11553  if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11554  op->getLocStart()))
11555  return QualType();
11556 
11557  Expr::LValueClassification lval = op->ClassifyLValue(Context);
11558  unsigned AddressOfError = AO_No_Error;
11559 
11560  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11561  bool sfinae = (bool)isSFINAEContext();
11562  Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11563  : diag::ext_typecheck_addrof_temporary)
11564  << op->getType() << op->getSourceRange();
11565  if (sfinae)
11566  return QualType();
11567  // Materialize the temporary as an lvalue so that we can take its address.
11568  OrigOp = op =
11569  CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11570  } else if (isa<ObjCSelectorExpr>(op)) {
11571  return Context.getPointerType(op->getType());
11572  } else if (lval == Expr::LV_MemberFunction) {
11573  // If it's an instance method, make a member pointer.
11574  // The expression must have exactly the form &A::foo.
11575 
11576  // If the underlying expression isn't a decl ref, give up.
11577  if (!isa<DeclRefExpr>(op)) {
11578  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11579  << OrigOp.get()->getSourceRange();
11580  return QualType();
11581  }
11582  DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11583  CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11584 
11585  // The id-expression was parenthesized.
11586  if (OrigOp.get() != DRE) {
11587  Diag(OpLoc, diag::err_parens_pointer_member_function)
11588  << OrigOp.get()->getSourceRange();
11589 
11590  // The method was named without a qualifier.
11591  } else if (!DRE->getQualifier()) {
11592  if (MD->getParent()->getName().empty())
11593  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11594  << op->getSourceRange();
11595  else {
11596  SmallString<32> Str;
11597  StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11598  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11599  << op->getSourceRange()
11601  }
11602  }
11603 
11604  // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11605  if (isa<CXXDestructorDecl>(MD))
11606  Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11607 
11608  QualType MPTy = Context.getMemberPointerType(
11609  op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11610  // Under the MS ABI, lock down the inheritance model now.
11611  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11612  (void)isCompleteType(OpLoc, MPTy);
11613  return MPTy;
11614  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11615  // C99 6.5.3.2p1
11616  // The operand must be either an l-value or a function designator
11617  if (!op->getType()->isFunctionType()) {
11618  // Use a special diagnostic for loads from property references.
11619  if (isa<PseudoObjectExpr>(op)) {
11620  AddressOfError = AO_Property_Expansion;
11621  } else {
11622  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11623  << op->getType() << op->getSourceRange();
11624  return QualType();
11625  }
11626  }
11627  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11628  // The operand cannot be a bit-field
11629  AddressOfError = AO_Bit_Field;
11630  } else if (op->getObjectKind() == OK_VectorComponent) {
11631  // The operand cannot be an element of a vector
11632  AddressOfError = AO_Vector_Element;
11633  } else if (dcl) { // C99 6.5.3.2p1
11634  // We have an lvalue with a decl. Make sure the decl is not declared
11635  // with the register storage-class specifier.
11636  if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11637  // in C++ it is not error to take address of a register
11638  // variable (c++03 7.1.1P3)
11639  if (vd->getStorageClass() == SC_Register &&
11640  !getLangOpts().CPlusPlus) {
11641  AddressOfError = AO_Register_Variable;
11642  }
11643  } else if (isa<MSPropertyDecl>(dcl)) {
11644  AddressOfError = AO_Property_Expansion;
11645  } else if (isa<FunctionTemplateDecl>(dcl)) {
11646  return Context.OverloadTy;
11647  } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11648  // Okay: we can take the address of a field.
11649  // Could be a pointer to member, though, if there is an explicit
11650  // scope qualifier for the class.
11651  if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11652  DeclContext *Ctx = dcl->getDeclContext();
11653  if (Ctx && Ctx->isRecord()) {
11654  if (dcl->getType()->isReferenceType()) {
11655  Diag(OpLoc,
11656  diag::err_cannot_form_pointer_to_member_of_reference_type)
11657  << dcl->getDeclName() << dcl->getType();
11658  return QualType();
11659  }
11660 
11661  while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11662  Ctx = Ctx->getParent();
11663 
11664  QualType MPTy = Context.getMemberPointerType(
11665  op->getType(),
11666  Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11667  // Under the MS ABI, lock down the inheritance model now.
11668  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11669  (void)isCompleteType(OpLoc, MPTy);
11670  return MPTy;
11671  }
11672  }
11673  } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11674  !isa<BindingDecl>(dcl))
11675  llvm_unreachable("Unknown/unexpected decl type");
11676  }
11677 
11678  if (AddressOfError != AO_No_Error) {
11679  diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11680  return QualType();
11681  }
11682 
11683  if (lval == Expr::LV_IncompleteVoidType) {
11684  // Taking the address of a void variable is technically illegal, but we
11685  // allow it in cases which are otherwise valid.
11686  // Example: "extern void x; void* y = &x;".
11687  Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11688  }
11689 
11690  // If the operand has type "type", the result has type "pointer to type".
11691  if (op->getType()->isObjCObjectType())
11692  return Context.getObjCObjectPointerType(op->getType());
11693 
11694  CheckAddressOfPackedMember(op);
11695 
11696  return Context.getPointerType(op->getType());
11697 }
11698 
11699 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11700  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11701  if (!DRE)
11702  return;
11703  const Decl *D = DRE->getDecl();
11704  if (!D)
11705  return;
11706  const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11707  if (!Param)
11708  return;
11709  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11710  if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11711  return;
11712  if (FunctionScopeInfo *FD = S.getCurFunction())
11713  if (!FD->ModifiedNonNullParams.count(Param))
11714  FD->ModifiedNonNullParams.insert(Param);
11715 }
11716 
11717 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11719  SourceLocation OpLoc) {
11720  if (Op->isTypeDependent())
11721  return S.Context.DependentTy;
11722 
11723  ExprResult ConvResult = S.UsualUnaryConversions(Op);
11724  if (ConvResult.isInvalid())
11725  return QualType();
11726  Op = ConvResult.get();
11727  QualType OpTy = Op->getType();
11728  QualType Result;
11729 
11730  if (isa<CXXReinterpretCastExpr>(Op)) {
11731  QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11732  S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11733  Op->getSourceRange());
11734  }
11735 
11736  if (const PointerType *PT = OpTy->getAs<PointerType>())
11737  {
11738  Result = PT->getPointeeType();
11739  }
11740  else if (const ObjCObjectPointerType *OPT =
11741  OpTy->getAs<ObjCObjectPointerType>())
11742  Result = OPT->getPointeeType();
11743  else {
11744  ExprResult PR = S.CheckPlaceholderExpr(Op);
11745  if (PR.isInvalid()) return QualType();
11746  if (PR.get() != Op)
11747  return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11748  }
11749 
11750  if (Result.isNull()) {
11751  S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11752  << OpTy << Op->getSourceRange();
11753  return QualType();
11754  }
11755 
11756  // Note that per both C89 and C99, indirection is always legal, even if Result
11757  // is an incomplete type or void. It would be possible to warn about
11758  // dereferencing a void pointer, but it's completely well-defined, and such a
11759  // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11760  // for pointers to 'void' but is fine for any other pointer type:
11761  //
11762  // C++ [expr.unary.op]p1:
11763  // [...] the expression to which [the unary * operator] is applied shall
11764  // be a pointer to an object type, or a pointer to a function type
11765  if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11766  S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11767  << OpTy << Op->getSourceRange();
11768 
11769  // Dereferences are usually l-values...
11770  VK = VK_LValue;
11771 
11772  // ...except that certain expressions are never l-values in C.
11773  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11774  VK = VK_RValue;
11775 
11776  return Result;
11777 }
11778 
11779 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11780  BinaryOperatorKind Opc;
11781  switch (Kind) {
11782  default: llvm_unreachable("Unknown binop!");
11783  case tok::periodstar: Opc = BO_PtrMemD; break;
11784  case tok::arrowstar: Opc = BO_PtrMemI; break;
11785  case tok::star: Opc = BO_Mul; break;
11786  case tok::slash: Opc = BO_Div; break;
11787  case tok::percent: Opc = BO_Rem; break;
11788  case tok::plus: Opc = BO_Add; break;
11789  case tok::minus: Opc = BO_Sub; break;
11790  case tok::lessless: Opc = BO_Shl; break;
11791  case tok::greatergreater: Opc = BO_Shr; break;
11792  case tok::lessequal: Opc = BO_LE; break;
11793  case tok::less: Opc = BO_LT; break;
11794  case tok::greaterequal: Opc = BO_GE; break;
11795  case tok::greater: Opc = BO_GT; break;
11796  case tok::exclaimequal: Opc = BO_NE; break;
11797  case tok::equalequal: Opc = BO_EQ; break;
11798  case tok::spaceship: Opc = BO_Cmp; break;
11799  case tok::amp: Opc = BO_And; break;
11800  case tok::caret: Opc = BO_Xor; break;
11801  case tok::pipe: Opc = BO_Or; break;
11802  case tok::ampamp: Opc = BO_LAnd; break;
11803  case tok::pipepipe: Opc = BO_LOr; break;
11804  case tok::equal: Opc = BO_Assign; break;
11805  case tok::starequal: Opc = BO_MulAssign; break;
11806  case tok::slashequal: Opc = BO_DivAssign; break;
11807  case tok::percentequal: Opc = BO_RemAssign; break;
11808  case tok::plusequal: Opc = BO_AddAssign; break;
11809  case tok::minusequal: Opc = BO_SubAssign; break;
11810  case tok::lesslessequal: Opc = BO_ShlAssign; break;
11811  case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
11812  case tok::ampequal: Opc = BO_AndAssign; break;
11813  case tok::caretequal: Opc = BO_XorAssign; break;
11814  case tok::pipeequal: Opc = BO_OrAssign; break;
11815  case tok::comma: Opc = BO_Comma; break;
11816  }
11817  return Opc;
11818 }
11819 
11821  tok::TokenKind Kind) {
11822  UnaryOperatorKind Opc;
11823  switch (Kind) {
11824  default: llvm_unreachable("Unknown unary op!");
11825  case tok::plusplus: Opc = UO_PreInc; break;
11826  case tok::minusminus: Opc = UO_PreDec; break;
11827  case tok::amp: Opc = UO_AddrOf; break;
11828  case tok::star: Opc = UO_Deref; break;
11829  case tok::plus: Opc = UO_Plus; break;
11830  case tok::minus: Opc = UO_Minus; break;
11831  case tok::tilde: Opc = UO_Not; break;
11832  case tok::exclaim: Opc = UO_LNot; break;
11833  case tok::kw___real: Opc = UO_Real; break;
11834  case tok::kw___imag: Opc = UO_Imag; break;
11835  case tok::kw___extension__: Opc = UO_Extension; break;
11836  }
11837  return Opc;
11838 }
11839 
11840 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11841 /// This warning suppressed in the event of macro expansions.
11842 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11843  SourceLocation OpLoc, bool IsBuiltin) {
11844  if (S.inTemplateInstantiation())
11845  return;
11846  if (S.isUnevaluatedContext())
11847  return;
11848  if (OpLoc.isInvalid() || OpLoc.isMacroID())
11849  return;
11850  LHSExpr = LHSExpr->IgnoreParenImpCasts();
11851  RHSExpr = RHSExpr->IgnoreParenImpCasts();
11852  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11853  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11854  if (!LHSDeclRef || !RHSDeclRef ||
11855  LHSDeclRef->getLocation().isMacroID() ||
11856  RHSDeclRef->getLocation().isMacroID())
11857  return;
11858  const ValueDecl *LHSDecl =
11859  cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11860  const ValueDecl *RHSDecl =
11861  cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11862  if (LHSDecl != RHSDecl)
11863  return;
11864  if (LHSDecl->getType().isVolatileQualified())
11865  return;
11866  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11867  if (RefTy->getPointeeType().isVolatileQualified())
11868  return;
11869 
11870  S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11871  : diag::warn_self_assignment_overloaded)
11872  << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11873  << RHSExpr->getSourceRange();
11874 }
11875 
11876 /// Check if a bitwise-& is performed on an Objective-C pointer. This
11877 /// is usually indicative of introspection within the Objective-C pointer.
11879  SourceLocation OpLoc) {
11880  if (!S.getLangOpts().ObjC1)
11881  return;
11882 
11883  const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11884  const Expr *LHS = L.get();
11885  const Expr *RHS = R.get();
11886 
11888  ObjCPointerExpr = LHS;
11889  OtherExpr = RHS;
11890  }
11891  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11892  ObjCPointerExpr = RHS;
11893  OtherExpr = LHS;
11894  }
11895 
11896  // This warning is deliberately made very specific to reduce false
11897  // positives with logic that uses '&' for hashing. This logic mainly
11898  // looks for code trying to introspect into tagged pointers, which
11899  // code should generally never do.
11900  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11901  unsigned Diag = diag::warn_objc_pointer_masking;
11902  // Determine if we are introspecting the result of performSelectorXXX.
11903  const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11904  // Special case messages to -performSelector and friends, which
11905  // can return non-pointer values boxed in a pointer value.
11906  // Some clients may wish to silence warnings in this subcase.
11907  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11908  Selector S = ME->getSelector();
11909  StringRef SelArg0 = S.getNameForSlot(0);
11910  if (SelArg0.startswith("performSelector"))
11911  Diag = diag::warn_objc_pointer_masking_performSelector;
11912  }
11913 
11914  S.Diag(OpLoc, Diag)
11915  << ObjCPointerExpr->getSourceRange();
11916  }
11917 }
11918 
11920  if (!E)
11921  return nullptr;
11922  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11923  return DRE->getDecl();
11924  if (auto *ME = dyn_cast<MemberExpr>(E))
11925  return ME->getMemberDecl();
11926  if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11927  return IRE->getDecl();
11928  return nullptr;
11929 }
11930 
11931 // This helper function promotes a binary operator's operands (which are of a
11932 // half vector type) to a vector of floats and then truncates the result to
11933 // a vector of either half or short.
11935  BinaryOperatorKind Opc, QualType ResultTy,
11937  bool IsCompAssign, SourceLocation OpLoc,
11938  FPOptions FPFeatures) {
11939  auto &Context = S.getASTContext();
11940  assert((isVector(ResultTy, Context.HalfTy) ||
11941  isVector(ResultTy, Context.ShortTy)) &&
11942  "Result must be a vector of half or short");
11943  assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11944  isVector(RHS.get()->getType(), Context.HalfTy) &&
11945  "both operands expected to be a half vector");
11946 
11947  RHS = convertVector(RHS.get(), Context.FloatTy, S);
11948  QualType BinOpResTy = RHS.get()->getType();
11949 
11950  // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11951  // change BinOpResTy to a vector of ints.
11952  if (isVector(ResultTy, Context.ShortTy))
11953  BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11954 
11955  if (IsCompAssign)
11956  return new (Context) CompoundAssignOperator(
11957  LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11958  OpLoc, FPFeatures);
11959 
11960  LHS = convertVector(LHS.get(), Context.FloatTy, S);
11961  auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11962  VK, OK, OpLoc, FPFeatures);
11963  return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11964 }
11965 
11966 static std::pair<ExprResult, ExprResult>
11968  Expr *RHSExpr) {
11969  ExprResult LHS = LHSExpr, RHS = RHSExpr;
11970  if (!S.getLangOpts().CPlusPlus) {
11971  // C cannot handle TypoExpr nodes on either side of a binop because it
11972  // doesn't handle dependent types properly, so make sure any TypoExprs have
11973  // been dealt with before checking the operands.
11974  LHS = S.CorrectDelayedTyposInExpr(LHS);
11975  RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11976  if (Opc != BO_Assign)
11977  return ExprResult(E);
11978  // Avoid correcting the RHS to the same Expr as the LHS.
11979  Decl *D = getDeclFromExpr(E);
11980  return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11981  });
11982  }
11983  return std::make_pair(LHS, RHS);
11984 }
11985 
11986 /// Returns true if conversion between vectors of halfs and vectors of floats
11987 /// is needed.
11988 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11989  QualType SrcType) {
11990  return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11992  isVector(SrcType, Ctx.HalfTy);
11993 }
11994 
11995 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11996 /// operator @p Opc at location @c TokLoc. This routine only supports
11997 /// built-in operations; ActOnBinOp handles overloaded operators.
11999  BinaryOperatorKind Opc,
12000  Expr *LHSExpr, Expr *RHSExpr) {
12001  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12002  // The syntax only allows initializer lists on the RHS of assignment,
12003  // so we don't need to worry about accepting invalid code for
12004  // non-assignment operators.
12005  // C++11 5.17p9:
12006  // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12007  // of x = {} is x = T().
12009  RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
12010  InitializedEntity Entity =
12012  InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12013  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12014  if (Init.isInvalid())
12015  return Init;
12016  RHSExpr = Init.get();
12017  }
12018 
12019  ExprResult LHS = LHSExpr, RHS = RHSExpr;
12020  QualType ResultTy; // Result type of the binary operator.
12021  // The following two variables are used for compound assignment operators
12022  QualType CompLHSTy; // Type of LHS after promotions for computation
12023  QualType CompResultTy; // Type of computation result
12024  ExprValueKind VK = VK_RValue;
12026  bool ConvertHalfVec = false;
12027 
12028  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12029  if (!LHS.isUsable() || !RHS.isUsable())
12030  return ExprError();
12031 
12032  if (getLangOpts().OpenCL) {
12033  QualType LHSTy = LHSExpr->getType();
12034  QualType RHSTy = RHSExpr->getType();
12035  // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12036  // the ATOMIC_VAR_INIT macro.
12037  if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12038  SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
12039  if (BO_Assign == Opc)
12040  Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12041  else
12042  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12043  return ExprError();
12044  }
12045 
12046  // OpenCL special types - image, sampler, pipe, and blocks are to be used
12047  // only with a builtin functions and therefore should be disallowed here.
12048  if (LHSTy->isImageType() || RHSTy->isImageType() ||
12049  LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12050  LHSTy->isPipeType() || RHSTy->isPipeType() ||
12051  LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12052  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12053  return ExprError();
12054  }
12055  }
12056 
12057  switch (Opc) {
12058  case BO_Assign:
12059  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12060  if (getLangOpts().CPlusPlus &&
12061  LHS.get()->getObjectKind() != OK_ObjCProperty) {
12062  VK = LHS.get()->getValueKind();
12063  OK = LHS.get()->getObjectKind();
12064  }
12065  if (!ResultTy.isNull()) {
12066  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12067  DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12068  }
12069  RecordModifiableNonNullParam(*this, LHS.get());
12070  break;
12071  case BO_PtrMemD:
12072  case BO_PtrMemI:
12073  ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12074  Opc == BO_PtrMemI);
12075  break;
12076  case BO_Mul:
12077  case BO_Div:
12078  ConvertHalfVec = true;
12079  ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12080  Opc == BO_Div);
12081  break;
12082  case BO_Rem:
12083  ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12084  break;
12085  case BO_Add:
12086  ConvertHalfVec = true;
12087  ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12088  break;
12089  case BO_Sub:
12090  ConvertHalfVec = true;
12091  ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12092  break;
12093  case BO_Shl:
12094  case BO_Shr:
12095  ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12096  break;
12097  case BO_LE:
12098  case BO_LT:
12099  case BO_GE:
12100  case BO_GT:
12101  ConvertHalfVec = true;
12102  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12103  break;
12104  case BO_EQ:
12105  case BO_NE:
12106  ConvertHalfVec = true;
12107  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12108  break;
12109  case BO_Cmp:
12110  ConvertHalfVec = true;
12111  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12112  assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12113  break;
12114  case BO_And:
12115  checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12116  LLVM_FALLTHROUGH;
12117  case BO_Xor:
12118  case BO_Or:
12119  ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12120  break;
12121  case BO_LAnd:
12122  case BO_LOr:
12123  ConvertHalfVec = true;
12124  ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12125  break;
12126  case BO_MulAssign:
12127  case BO_DivAssign:
12128  ConvertHalfVec = true;
12129  CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12130  Opc == BO_DivAssign);
12131  CompLHSTy = CompResultTy;
12132  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12133  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12134  break;
12135  case BO_RemAssign:
12136  CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12137  CompLHSTy = CompResultTy;
12138  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12139  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12140  break;
12141  case BO_AddAssign:
12142  ConvertHalfVec = true;
12143  CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12144  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12145  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12146  break;
12147  case BO_SubAssign:
12148  ConvertHalfVec = true;
12149  CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12150  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12151  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12152  break;
12153  case BO_ShlAssign:
12154  case BO_ShrAssign:
12155  CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12156  CompLHSTy = CompResultTy;
12157  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12158  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12159  break;
12160  case BO_AndAssign:
12161  case BO_OrAssign: // fallthrough
12162  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12163  LLVM_FALLTHROUGH;
12164  case BO_XorAssign:
12165  CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12166  CompLHSTy = CompResultTy;
12167  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12168  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12169  break;
12170  case BO_Comma:
12171  ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12172  if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12173  VK = RHS.get()->getValueKind();
12174  OK = RHS.get()->getObjectKind();
12175  }
12176  break;
12177  }
12178  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12179  return ExprError();
12180 
12181  // Some of the binary operations require promoting operands of half vector to
12182  // float vectors and truncating the result back to half vector. For now, we do
12183  // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12184  // arm64).
12185  assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12186  isVector(LHS.get()->getType(), Context.HalfTy) &&
12187  "both sides are half vectors or neither sides are");
12188  ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12189  LHS.get()->getType());
12190 
12191  // Check for array bounds violations for both sides of the BinaryOperator
12192  CheckArrayAccess(LHS.get());
12193  CheckArrayAccess(RHS.get());
12194 
12195  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12196  NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12197  &Context.Idents.get("object_setClass"),
12198  SourceLocation(), LookupOrdinaryName);
12199  if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12200  SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
12201  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
12202  FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
12203  FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
12204  FixItHint::CreateInsertion(RHSLocEnd, ")");
12205  }
12206  else
12207  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12208  }
12209  else if (const ObjCIvarRefExpr *OIRE =
12210  dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12211  DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12212 
12213  // Opc is not a compound assignment if CompResultTy is null.
12214  if (CompResultTy.isNull()) {
12215  if (ConvertHalfVec)
12216  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12217  OpLoc, FPFeatures);
12218  return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12219  OK, OpLoc, FPFeatures);
12220  }
12221 
12222  // Handle compound assignments.
12223  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12224  OK_ObjCProperty) {
12225  VK = VK_LValue;
12226  OK = LHS.get()->getObjectKind();
12227  }
12228 
12229  if (ConvertHalfVec)
12230  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12231  OpLoc, FPFeatures);
12232 
12233  return new (Context) CompoundAssignOperator(
12234  LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12235  OpLoc, FPFeatures);
12236 }
12237 
12238 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12239 /// operators are mixed in a way that suggests that the programmer forgot that
12240 /// comparison operators have higher precedence. The most typical example of
12241 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12243  SourceLocation OpLoc, Expr *LHSExpr,
12244  Expr *RHSExpr) {
12245  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12246  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12247 
12248  // Check that one of the sides is a comparison operator and the other isn't.
12249  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12250  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12251  if (isLeftComp == isRightComp)
12252  return;
12253 
12254  // Bitwise operations are sometimes used as eager logical ops.
12255  // Don't diagnose this.
12256  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12257  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12258  if (isLeftBitwise || isRightBitwise)
12259  return;
12260 
12261  SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
12262  OpLoc)
12263  : SourceRange(OpLoc, RHSExpr->getLocEnd());
12264  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12265  SourceRange ParensRange = isLeftComp ?
12266  SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
12267  : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
12268 
12269  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12270  << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12271  SuggestParentheses(Self, OpLoc,
12272  Self.PDiag(diag::note_precedence_silence) << OpStr,
12273  (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12274  SuggestParentheses(Self, OpLoc,
12275  Self.PDiag(diag::note_precedence_bitwise_first)
12277  ParensRange);
12278 }
12279 
12280 /// It accepts a '&&' expr that is inside a '||' one.
12281 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12282 /// in parentheses.
12283 static void
12285  BinaryOperator *Bop) {
12286  assert(Bop->getOpcode() == BO_LAnd);
12287  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12288  << Bop->getSourceRange() << OpLoc;
12289  SuggestParentheses(Self, Bop->getOperatorLoc(),
12290  Self.PDiag(diag::note_precedence_silence)
12291  << Bop->getOpcodeStr(),
12292  Bop->getSourceRange());
12293 }
12294 
12295 /// Returns true if the given expression can be evaluated as a constant
12296 /// 'true'.
12297 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12298  bool Res;
12299  return !E->isValueDependent() &&
12300  E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12301 }
12302 
12303 /// Returns true if the given expression can be evaluated as a constant
12304 /// 'false'.
12305 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12306  bool Res;
12307  return !E->isValueDependent() &&
12308  E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12309 }
12310 
12311 /// Look for '&&' in the left hand of a '||' expr.
12313  Expr *LHSExpr, Expr *RHSExpr) {
12314  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12315  if (Bop->getOpcode() == BO_LAnd) {
12316  // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12317  if (EvaluatesAsFalse(S, RHSExpr))
12318  return;
12319  // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12320  if (!EvaluatesAsTrue(S, Bop->getLHS()))
12321  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12322  } else if (Bop->getOpcode() == BO_LOr) {
12323  if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12324  // If it's "a || b && 1 || c" we didn't warn earlier for
12325  // "a || b && 1", but warn now.
12326  if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12327  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12328  }
12329  }
12330  }
12331 }
12332 
12333 /// Look for '&&' in the right hand of a '||' expr.
12335  Expr *LHSExpr, Expr *RHSExpr) {
12336  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12337  if (Bop->getOpcode() == BO_LAnd) {
12338  // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12339  if (EvaluatesAsFalse(S, LHSExpr))
12340  return;
12341  // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12342  if (!EvaluatesAsTrue(S, Bop->getRHS()))
12343  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12344  }
12345  }
12346 }
12347 
12348 /// Look for bitwise op in the left or right hand of a bitwise op with
12349 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12350 /// the '&' expression in parentheses.
12352  SourceLocation OpLoc, Expr *SubExpr) {
12353  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12354  if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12355  S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12356  << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12357  << Bop->getSourceRange() << OpLoc;
12358  SuggestParentheses(S, Bop->getOperatorLoc(),
12359  S.PDiag(diag::note_precedence_silence)
12360  << Bop->getOpcodeStr(),
12361  Bop->getSourceRange());
12362  }
12363  }
12364 }
12365 
12367  Expr *SubExpr, StringRef Shift) {
12368  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12369  if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12370  StringRef Op = Bop->getOpcodeStr();
12371  S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12372  << Bop->getSourceRange() << OpLoc << Shift << Op;
12373  SuggestParentheses(S, Bop->getOperatorLoc(),
12374  S.PDiag(diag::note_precedence_silence) << Op,
12375  Bop->getSourceRange());
12376  }
12377  }
12378 }
12379 
12381  Expr *LHSExpr, Expr *RHSExpr) {
12382  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12383  if (!OCE)
12384  return;
12385 
12386  FunctionDecl *FD = OCE->getDirectCallee();
12387  if (!FD || !FD->isOverloadedOperator())
12388  return;
12389 
12391  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12392  return;
12393 
12394  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12395  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12396  << (Kind == OO_LessLess);
12398  S.PDiag(diag::note_precedence_silence)
12399  << (Kind == OO_LessLess ? "<<" : ">>"),
12400  OCE->getSourceRange());
12401  SuggestParentheses(S, OpLoc,
12402  S.PDiag(diag::note_evaluate_comparison_first),
12403  SourceRange(OCE->getArg(1)->getLocStart(),
12404  RHSExpr->getLocEnd()));
12405 }
12406 
12407 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12408 /// precedence.
12410  SourceLocation OpLoc, Expr *LHSExpr,
12411  Expr *RHSExpr){
12412  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12413  if (BinaryOperator::isBitwiseOp(Opc))
12414  DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12415 
12416  // Diagnose "arg1 & arg2 | arg3"
12417  if ((Opc == BO_Or || Opc == BO_Xor) &&
12418  !OpLoc.isMacroID()/* Don't warn in macros. */) {
12419  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12420  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12421  }
12422 
12423  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12424  // We don't warn for 'assert(a || b && "bad")' since this is safe.
12425  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12426  DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12427  DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12428  }
12429 
12430  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12431  || Opc == BO_Shr) {
12432  StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12433  DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12434  DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12435  }
12436 
12437  // Warn on overloaded shift operators and comparisons, such as:
12438  // cout << 5 == 4;
12440  DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12441 }
12442 
12443 // Binary Operators. 'Tok' is the token for the operator.
12445  tok::TokenKind Kind,
12446  Expr *LHSExpr, Expr *RHSExpr) {
12447  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12448  assert(LHSExpr && "ActOnBinOp(): missing left expression");
12449  assert(RHSExpr && "ActOnBinOp(): missing right expression");
12450 
12451  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12452  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12453 
12454  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12455 }
12456 
12457 /// Build an overloaded binary operator expression in the given scope.
12459  BinaryOperatorKind Opc,
12460  Expr *LHS, Expr *RHS) {
12461  switch (Opc) {
12462  case BO_Assign:
12463  case BO_DivAssign:
12464  case BO_RemAssign:
12465  case BO_SubAssign:
12466  case BO_AndAssign:
12467  case BO_OrAssign:
12468  case BO_XorAssign:
12469  DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12470  CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12471  break;
12472  default:
12473  break;
12474  }
12475 
12476  // Find all of the overloaded operators visible from this
12477  // point. We perform both an operator-name lookup from the local
12478  // scope and an argument-dependent lookup based on the types of
12479  // the arguments.
12480  UnresolvedSet<16> Functions;
12481  OverloadedOperatorKind OverOp
12483  if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12484  S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12485  RHS->getType(), Functions);
12486 
12487  // Build the (potentially-overloaded, potentially-dependent)
12488  // binary operation.
12489  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12490 }
12491 
12493  BinaryOperatorKind Opc,
12494  Expr *LHSExpr, Expr *RHSExpr) {
12495  ExprResult LHS, RHS;
12496  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12497  if (!LHS.isUsable() || !RHS.isUsable())
12498  return ExprError();
12499  LHSExpr = LHS.get();
12500  RHSExpr = RHS.get();
12501 
12502  // We want to end up calling one of checkPseudoObjectAssignment
12503  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12504  // both expressions are overloadable or either is type-dependent),
12505  // or CreateBuiltinBinOp (in any other case). We also want to get
12506  // any placeholder types out of the way.
12507 
12508  // Handle pseudo-objects in the LHS.
12509  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12510  // Assignments with a pseudo-object l-value need special analysis.
12511  if (pty->getKind() == BuiltinType::PseudoObject &&
12513  return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12514 
12515  // Don't resolve overloads if the other type is overloadable.
12516  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12517  // We can't actually test that if we still have a placeholder,
12518  // though. Fortunately, none of the exceptions we see in that
12519  // code below are valid when the LHS is an overload set. Note
12520  // that an overload set can be dependently-typed, but it never
12521  // instantiates to having an overloadable type.
12522  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12523  if (resolvedRHS.isInvalid()) return ExprError();
12524  RHSExpr = resolvedRHS.get();
12525 
12526  if (RHSExpr->isTypeDependent() ||
12527  RHSExpr->getType()->isOverloadableType())
12528  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12529  }
12530 
12531  // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12532  // template, diagnose the missing 'template' keyword instead of diagnosing
12533  // an invalid use of a bound member function.
12534  //
12535  // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12536  // to C++1z [over.over]/1.4, but we already checked for that case above.
12537  if (Opc == BO_LT && inTemplateInstantiation() &&
12538  (pty->getKind() == BuiltinType::BoundMember ||
12539  pty->getKind() == BuiltinType::Overload)) {
12540  auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12541  if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12542  std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12543  return isa<FunctionTemplateDecl>(ND);
12544  })) {
12545  Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12546  : OE->getNameLoc(),
12547  diag::err_template_kw_missing)
12548  << OE->getName().getAsString() << "";
12549  return ExprError();
12550  }
12551  }
12552 
12553  ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12554  if (LHS.isInvalid()) return ExprError();
12555  LHSExpr = LHS.get();
12556  }
12557 
12558  // Handle pseudo-objects in the RHS.
12559  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12560  // An overload in the RHS can potentially be resolved by the type
12561  // being assigned to.
12562  if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12563  if (getLangOpts().CPlusPlus &&
12564  (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12565  LHSExpr->getType()->isOverloadableType()))
12566  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12567 
12568  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12569  }
12570 
12571  // Don't resolve overloads if the other type is overloadable.
12572  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12573  LHSExpr->getType()->isOverloadableType())
12574  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12575 
12576  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12577  if (!resolvedRHS.isUsable()) return ExprError();
12578  RHSExpr = resolvedRHS.get();
12579  }
12580 
12581  if (getLangOpts().CPlusPlus) {
12582  // If either expression is type-dependent, always build an
12583  // overloaded op.
12584  if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12585  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12586 
12587  // Otherwise, build an overloaded op if either expression has an
12588  // overloadable type.
12589  if (LHSExpr->getType()->isOverloadableType() ||
12590  RHSExpr->getType()->isOverloadableType())
12591  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12592  }
12593 
12594  // Build a built-in binary operation.
12595  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12596 }
12597 
12599  if (T.isNull() || T->isDependentType())
12600  return false;
12601 
12602  if (!T->isPromotableIntegerType())
12603  return true;
12604 
12605  return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12606 }
12607 
12609  UnaryOperatorKind Opc,
12610  Expr *InputExpr) {
12611  ExprResult Input = InputExpr;
12612  ExprValueKind VK = VK_RValue;
12614  QualType resultType;
12615  bool CanOverflow = false;
12616 
12617  bool ConvertHalfVec = false;
12618  if (getLangOpts().OpenCL) {
12619  QualType Ty = InputExpr->getType();
12620  // The only legal unary operation for atomics is '&'.
12621  if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12622  // OpenCL special types - image, sampler, pipe, and blocks are to be used
12623  // only with a builtin functions and therefore should be disallowed here.
12624  (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12625  || Ty->isBlockPointerType())) {
12626  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12627  << InputExpr->getType()
12628  << Input.get()->getSourceRange());
12629  }
12630  }
12631  switch (Opc) {
12632  case UO_PreInc:
12633  case UO_PreDec:
12634  case UO_PostInc:
12635  case UO_PostDec:
12636  resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12637  OpLoc,
12638  Opc == UO_PreInc ||
12639  Opc == UO_PostInc,
12640  Opc == UO_PreInc ||
12641  Opc == UO_PreDec);
12642  CanOverflow = isOverflowingIntegerType(Context, resultType);
12643  break;
12644  case UO_AddrOf:
12645  resultType = CheckAddressOfOperand(Input, OpLoc);
12646  RecordModifiableNonNullParam(*this, InputExpr);
12647  break;
12648  case UO_Deref: {
12649  Input = DefaultFunctionArrayLvalueConversion(Input.get());
12650  if (Input.isInvalid()) return ExprError();
12651  resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12652  break;
12653  }
12654  case UO_Plus:
12655  case UO_Minus:
12656  CanOverflow = Opc == UO_Minus &&
12657  isOverflowingIntegerType(Context, Input.get()->getType());
12658  Input = UsualUnaryConversions(Input.get());
12659  if (Input.isInvalid()) return ExprError();
12660  // Unary plus and minus require promoting an operand of half vector to a
12661  // float vector and truncating the result back to a half vector. For now, we
12662  // do this only when HalfArgsAndReturns is set (that is, when the target is
12663  // arm or arm64).
12664  ConvertHalfVec =
12665  needsConversionOfHalfVec(true, Context, Input.get()->getType());
12666 
12667  // If the operand is a half vector, promote it to a float vector.
12668  if (ConvertHalfVec)
12669  Input = convertVector(Input.get(), Context.FloatTy, *this);
12670  resultType = Input.get()->getType();
12671  if (resultType->isDependentType())
12672  break;
12673  if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12674  break;
12675  else if (resultType->isVectorType() &&
12676  // The z vector extensions don't allow + or - with bool vectors.
12677  (!Context.getLangOpts().ZVector ||
12678  resultType->getAs<VectorType>()->getVectorKind() !=
12680  break;
12681  else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12682  Opc == UO_Plus &&
12683  resultType->isPointerType())
12684  break;
12685 
12686  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12687  << resultType << Input.get()->getSourceRange());
12688 
12689  case UO_Not: // bitwise complement
12690  Input = UsualUnaryConversions(Input.get());
12691  if (Input.isInvalid())
12692  return ExprError();
12693  resultType = Input.get()->getType();
12694 
12695  if (resultType->isDependentType())
12696  break;
12697  // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12698  if (resultType->isComplexType() || resultType->isComplexIntegerType())
12699  // C99 does not support '~' for complex conjugation.
12700  Diag(OpLoc, diag::ext_integer_complement_complex)
12701  << resultType << Input.get()->getSourceRange();
12702  else if (resultType->hasIntegerRepresentation())
12703  break;
12704  else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12705  // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12706  // on vector float types.
12707  QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12708  if (!T->isIntegerType())
12709  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12710  << resultType << Input.get()->getSourceRange());
12711  } else {
12712  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12713  << resultType << Input.get()->getSourceRange());
12714  }
12715  break;
12716 
12717  case UO_LNot: // logical negation
12718  // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12719  Input = DefaultFunctionArrayLvalueConversion(Input.get());
12720  if (Input.isInvalid()) return ExprError();
12721  resultType = Input.get()->getType();
12722 
12723  // Though we still have to promote half FP to float...
12724  if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12725  Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12726  resultType = Context.FloatTy;
12727  }
12728 
12729  if (resultType->isDependentType())
12730  break;
12731  if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12732  // C99 6.5.3.3p1: ok, fallthrough;
12733  if (Context.getLangOpts().CPlusPlus) {
12734  // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12735  // operand contextually converted to bool.
12736  Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12737  ScalarTypeToBooleanCastKind(resultType));
12738  } else if (Context.getLangOpts().OpenCL &&
12739  Context.getLangOpts().OpenCLVersion < 120) {
12740  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12741  // operate on scalar float types.
12742  if (!resultType->isIntegerType() && !resultType->isPointerType())
12743  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12744  << resultType << Input.get()->getSourceRange());
12745  }
12746  } else if (resultType->isExtVectorType()) {
12747  if (Context.getLangOpts().OpenCL &&
12748  Context.getLangOpts().OpenCLVersion < 120) {
12749  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12750  // operate on vector float types.
12751  QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12752  if (!T->isIntegerType())
12753  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12754  << resultType << Input.get()->getSourceRange());
12755  }
12756  // Vector logical not returns the signed variant of the operand type.
12757  resultType = GetSignedVectorType(resultType);
12758  break;
12759  } else {
12760  // FIXME: GCC's vector extension permits the usage of '!' with a vector
12761  // type in C++. We should allow that here too.
12762  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12763  << resultType << Input.get()->getSourceRange());
12764  }
12765 
12766  // LNot always has type int. C99 6.5.3.3p5.
12767  // In C++, it's bool. C++ 5.3.1p8
12768  resultType = Context.getLogicalOperationType();
12769  break;
12770  case UO_Real:
12771  case UO_Imag:
12772  resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12773  // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12774  // complex l-values to ordinary l-values and all other values to r-values.
12775  if (Input.isInvalid()) return ExprError();
12776  if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12777  if (Input.get()->getValueKind() != VK_RValue &&
12778  Input.get()->getObjectKind() == OK_Ordinary)
12779  VK = Input.get()->getValueKind();
12780  } else if (!getLangOpts().CPlusPlus) {
12781  // In C, a volatile scalar is read by __imag. In C++, it is not.
12782  Input = DefaultLvalueConversion(Input.get());
12783  }
12784  break;
12785  case UO_Extension:
12786  resultType = Input.get()->getType();
12787  VK = Input.get()->getValueKind();
12788  OK = Input.get()->getObjectKind();
12789  break;
12790  case UO_Coawait:
12791  // It's unnecessary to represent the pass-through operator co_await in the
12792  // AST; just return the input expression instead.
12793  assert(!Input.get()->getType()->isDependentType() &&
12794  "the co_await expression must be non-dependant before "
12795  "building operator co_await");
12796  return Input;
12797  }
12798  if (resultType.isNull() || Input.isInvalid())
12799  return ExprError();
12800 
12801  // Check for array bounds violations in the operand of the UnaryOperator,
12802  // except for the '*' and '&' operators that have to be handled specially
12803  // by CheckArrayAccess (as there are special cases like &array[arraysize]
12804  // that are explicitly defined as valid by the standard).
12805  if (Opc != UO_AddrOf && Opc != UO_Deref)
12806  CheckArrayAccess(Input.get());
12807 
12808  auto *UO = new (Context)
12809  UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12810  // Convert the result back to a half vector.
12811  if (ConvertHalfVec)
12812  return convertVector(UO, Context.HalfTy, *this);
12813  return UO;
12814 }
12815 
12816 /// Determine whether the given expression is a qualified member
12817 /// access expression, of a form that could be turned into a pointer to member
12818 /// with the address-of operator.
12820  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12821  if (!DRE->getQualifier())
12822  return false;
12823 
12824  ValueDecl *VD = DRE->getDecl();
12825  if (!VD->isCXXClassMember())
12826  return false;
12827 
12828  if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12829  return true;
12830  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12831  return Method->isInstance();
12832 
12833  return false;
12834  }
12835 
12836  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12837  if (!ULE->getQualifier())
12838  return false;
12839 
12840  for (NamedDecl *D : ULE->decls()) {
12841  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12842  if (Method->isInstance())
12843  return true;
12844  } else {
12845  // Overload set does not contain methods.
12846  break;
12847  }
12848  }
12849 
12850  return false;
12851  }
12852 
12853  return false;
12854 }
12855 
12857  UnaryOperatorKind Opc, Expr *Input) {
12858  // First things first: handle placeholders so that the
12859  // overloaded-operator check considers the right type.
12860  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12861  // Increment and decrement of pseudo-object references.
12862  if (pty->getKind() == BuiltinType::PseudoObject &&
12864  return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12865 
12866  // extension is always a builtin operator.
12867  if (Opc == UO_Extension)
12868  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12869 
12870  // & gets special logic for several kinds of placeholder.
12871  // The builtin code knows what to do.
12872  if (Opc == UO_AddrOf &&
12873  (pty->getKind() == BuiltinType::Overload ||
12874  pty->getKind() == BuiltinType::UnknownAny ||
12875  pty->getKind() == BuiltinType::BoundMember))
12876  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12877 
12878  // Anything else needs to be handled now.
12879  ExprResult Result = CheckPlaceholderExpr(Input);
12880  if (Result.isInvalid()) return ExprError();
12881  Input = Result.get();
12882  }
12883 
12884  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12886  !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12887  // Find all of the overloaded operators visible from this
12888  // point. We perform both an operator-name lookup from the local
12889  // scope and an argument-dependent lookup based on the types of
12890  // the arguments.
12891  UnresolvedSet<16> Functions;
12893  if (S && OverOp != OO_None)
12894  LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12895  Functions);
12896 
12897  return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12898  }
12899 
12900  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12901 }
12902 
12903 // Unary Operators. 'Tok' is the token for the operator.
12905  tok::TokenKind Op, Expr *Input) {
12906  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12907 }
12908 
12909 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12911  LabelDecl *TheDecl) {
12912  TheDecl->markUsed(Context);
12913  // Create the AST node. The address of a label always has type 'void*'.
12914  return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12915  Context.getPointerType(Context.VoidTy));
12916 }
12917 
12918 /// Given the last statement in a statement-expression, check whether
12919 /// the result is a producing expression (like a call to an
12920 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12921 /// release out of the full-expression. Otherwise, return null.
12922 /// Cannot fail.
12924  // Should always be wrapped with one of these.
12925  ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12926  if (!cleanups) return nullptr;
12927 
12928  ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12929  if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12930  return nullptr;
12931 
12932  // Splice out the cast. This shouldn't modify any interesting
12933  // features of the statement.
12934  Expr *producer = cast->getSubExpr();
12935  assert(producer->getType() == cast->getType());
12936  assert(producer->getValueKind() == cast->getValueKind());
12937  cleanups->setSubExpr(producer);
12938  return cleanups;
12939 }
12940 
12942  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12943 }
12944 
12946  // Note that function is also called by TreeTransform when leaving a
12947  // StmtExpr scope without rebuilding anything.
12948 
12949  DiscardCleanupsInEvaluationContext();
12950  PopExpressionEvaluationContext();
12951 }
12952 
12953 ExprResult
12955  SourceLocation RPLoc) { // "({..})"
12956  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12957  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12958 
12959  if (hasAnyUnrecoverableErrorsInThisFunction())
12960  DiscardCleanupsInEvaluationContext();
12961  assert(!Cleanup.exprNeedsCleanups() &&
12962  "cleanups within StmtExpr not correctly bound!");
12963  PopExpressionEvaluationContext();
12964 
12965  // FIXME: there are a variety of strange constraints to enforce here, for
12966  // example, it is not possible to goto into a stmt expression apparently.
12967  // More semantic analysis is needed.
12968 
12969  // If there are sub-stmts in the compound stmt, take the type of the last one
12970  // as the type of the stmtexpr.
12971  QualType Ty = Context.VoidTy;
12972  bool StmtExprMayBindToTemp = false;
12973  if (!Compound->body_empty()) {
12974  Stmt *LastStmt = Compound->body_back();
12975  LabelStmt *LastLabelStmt = nullptr;
12976  // If LastStmt is a label, skip down through into the body.
12977  while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12978  LastLabelStmt = Label;
12979  LastStmt = Label->getSubStmt();
12980  }
12981 
12982  if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12983  // Do function/array conversion on the last expression, but not
12984  // lvalue-to-rvalue. However, initialize an unqualified type.
12985  ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12986  if (LastExpr.isInvalid())
12987  return ExprError();
12988  Ty = LastExpr.get()->getType().getUnqualifiedType();
12989 
12990  if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12991  // In ARC, if the final expression ends in a consume, splice
12992  // the consume out and bind it later. In the alternate case
12993  // (when dealing with a retainable type), the result
12994  // initialization will create a produce. In both cases the
12995  // result will be +1, and we'll need to balance that out with
12996  // a bind.
12997  if (Expr *rebuiltLastStmt
12998  = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12999  LastExpr = rebuiltLastStmt;
13000  } else {
13001  LastExpr = PerformCopyInitialization(
13003  SourceLocation(), LastExpr);
13004  }
13005 
13006  if (LastExpr.isInvalid())
13007  return ExprError();
13008  if (LastExpr.get() != nullptr) {
13009  if (!LastLabelStmt)
13010  Compound->setLastStmt(LastExpr.get());
13011  else
13012  LastLabelStmt->setSubStmt(LastExpr.get());
13013  StmtExprMayBindToTemp = true;
13014  }
13015  }
13016  }
13017  }
13018 
13019  // FIXME: Check that expression type is complete/non-abstract; statement
13020  // expressions are not lvalues.
13021  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13022  if (StmtExprMayBindToTemp)
13023  return MaybeBindToTemporary(ResStmtExpr);
13024  return ResStmtExpr;
13025 }
13026 
13028  TypeSourceInfo *TInfo,
13029  ArrayRef<OffsetOfComponent> Components,
13030  SourceLocation RParenLoc) {
13031  QualType ArgTy = TInfo->getType();
13032  bool Dependent = ArgTy->isDependentType();
13033  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13034 
13035  // We must have at least one component that refers to the type, and the first
13036  // one is known to be a field designator. Verify that the ArgTy represents
13037  // a struct/union/class.
13038  if (!Dependent && !ArgTy->isRecordType())
13039  return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13040  << ArgTy << TypeRange);
13041 
13042  // Type must be complete per C99 7.17p3 because a declaring a variable
13043  // with an incomplete type would be ill-formed.
13044  if (!Dependent
13045  && RequireCompleteType(BuiltinLoc, ArgTy,
13046  diag::err_offsetof_incomplete_type, TypeRange))
13047  return ExprError();
13048 
13049  bool DidWarnAboutNonPOD = false;
13050  QualType CurrentType = ArgTy;
13052  SmallVector<Expr*, 4> Exprs;
13053  for (const OffsetOfComponent &OC : Components) {
13054  if (OC.isBrackets) {
13055  // Offset of an array sub-field. TODO: Should we allow vector elements?
13056  if (!CurrentType->isDependentType()) {
13057  const ArrayType *AT = Context.getAsArrayType(CurrentType);
13058  if(!AT)
13059  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13060  << CurrentType);
13061  CurrentType = AT->getElementType();
13062  } else
13063  CurrentType = Context.DependentTy;
13064 
13065  ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13066  if (IdxRval.isInvalid())
13067  return ExprError();
13068  Expr *Idx = IdxRval.get();
13069 
13070  // The expression must be an integral expression.
13071  // FIXME: An integral constant expression?
13072  if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13073  !Idx->getType()->isIntegerType())
13074  return ExprError(Diag(Idx->getLocStart(),
13075  diag::err_typecheck_subscript_not_integer)
13076  << Idx->getSourceRange());
13077 
13078  // Record this array index.
13079  Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13080  Exprs.push_back(Idx);
13081  continue;
13082  }
13083 
13084  // Offset of a field.
13085  if (CurrentType->isDependentType()) {
13086  // We have the offset of a field, but we can't look into the dependent
13087  // type. Just record the identifier of the field.
13088  Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13089  CurrentType = Context.DependentTy;
13090  continue;
13091  }
13092 
13093  // We need to have a complete type to look into.
13094  if (RequireCompleteType(OC.LocStart, CurrentType,
13095  diag::err_offsetof_incomplete_type))
13096  return ExprError();
13097 
13098  // Look for the designated field.
13099  const RecordType *RC = CurrentType->getAs<RecordType>();
13100  if (!RC)
13101  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13102  << CurrentType);
13103  RecordDecl *RD = RC->getDecl();
13104 
13105  // C++ [lib.support.types]p5:
13106  // The macro offsetof accepts a restricted set of type arguments in this
13107  // International Standard. type shall be a POD structure or a POD union
13108  // (clause 9).
13109  // C++11 [support.types]p4:
13110  // If type is not a standard-layout class (Clause 9), the results are
13111  // undefined.
13112  if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13113  bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13114  unsigned DiagID =
13115  LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13116  : diag::ext_offsetof_non_pod_type;
13117 
13118  if (!IsSafe && !DidWarnAboutNonPOD &&
13119  DiagRuntimeBehavior(BuiltinLoc, nullptr,
13120  PDiag(DiagID)
13121  << SourceRange(Components[0].LocStart, OC.LocEnd)
13122  << CurrentType))
13123  DidWarnAboutNonPOD = true;
13124  }
13125 
13126  // Look for the field.
13127  LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13128  LookupQualifiedName(R, RD);
13129  FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13130  IndirectFieldDecl *IndirectMemberDecl = nullptr;
13131  if (!MemberDecl) {
13132  if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13133  MemberDecl = IndirectMemberDecl->getAnonField();
13134  }
13135 
13136  if (!MemberDecl)
13137  return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13138  << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13139  OC.LocEnd));
13140 
13141  // C99 7.17p3:
13142  // (If the specified member is a bit-field, the behavior is undefined.)
13143  //
13144  // We diagnose this as an error.
13145  if (MemberDecl->isBitField()) {
13146  Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13147  << MemberDecl->getDeclName()
13148  << SourceRange(BuiltinLoc, RParenLoc);
13149  Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13150  return ExprError();
13151  }
13152 
13153  RecordDecl *Parent = MemberDecl->getParent();
13154  if (IndirectMemberDecl)
13155  Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13156 
13157  // If the member was found in a base class, introduce OffsetOfNodes for
13158  // the base class indirections.
13159  CXXBasePaths Paths;
13160  if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13161  Paths)) {
13162  if (Paths.getDetectedVirtual()) {
13163  Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13164  << MemberDecl->getDeclName()
13165  << SourceRange(BuiltinLoc, RParenLoc);
13166  return ExprError();
13167  }
13168 
13169  CXXBasePath &Path = Paths.front();
13170  for (const CXXBasePathElement &B : Path)
13171  Comps.push_back(OffsetOfNode(B.Base));
13172  }
13173 
13174  if (IndirectMemberDecl) {
13175  for (auto *FI : IndirectMemberDecl->chain()) {
13176  assert(isa<FieldDecl>(FI));
13177  Comps.push_back(OffsetOfNode(OC.LocStart,
13178  cast<FieldDecl>(FI), OC.LocEnd));
13179  }
13180  } else
13181  Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13182 
13183  CurrentType = MemberDecl->getType().getNonReferenceType();
13184  }
13185 
13186  return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13187  Comps, Exprs, RParenLoc);
13188 }
13189 
13191  SourceLocation BuiltinLoc,
13193  ParsedType ParsedArgTy,
13194  ArrayRef<OffsetOfComponent> Components,
13195  SourceLocation RParenLoc) {
13196 
13197  TypeSourceInfo *ArgTInfo;
13198  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13199  if (ArgTy.isNull())
13200  return ExprError();
13201 
13202  if (!ArgTInfo)
13203  ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13204 
13205  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13206 }
13207 
13208 
13210  Expr *CondExpr,
13211  Expr *LHSExpr, Expr *RHSExpr,
13212  SourceLocation RPLoc) {
13213  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13214 
13215  ExprValueKind VK = VK_RValue;
13217  QualType resType;
13218  bool ValueDependent = false;
13219  bool CondIsTrue = false;
13220  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13221  resType = Context.DependentTy;
13222  ValueDependent = true;
13223  } else {
13224  // The conditional expression is required to be a constant expression.
13225  llvm::APSInt condEval(32);
13226  ExprResult CondICE
13227  = VerifyIntegerConstantExpression(CondExpr, &condEval,
13228  diag::err_typecheck_choose_expr_requires_constant, false);
13229  if (CondICE.isInvalid())
13230  return ExprError();
13231  CondExpr = CondICE.get();
13232  CondIsTrue = condEval.getZExtValue();
13233 
13234  // If the condition is > zero, then the AST type is the same as the LHSExpr.
13235  Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13236 
13237  resType = ActiveExpr->getType();
13238  ValueDependent = ActiveExpr->isValueDependent();
13239  VK = ActiveExpr->getValueKind();
13240  OK = ActiveExpr->getObjectKind();
13241  }
13242 
13243  return new (Context)
13244  ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13245  CondIsTrue, resType->isDependentType(), ValueDependent);
13246 }
13247 
13248 //===----------------------------------------------------------------------===//
13249 // Clang Extensions.
13250 //===----------------------------------------------------------------------===//
13251 
13252 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13253 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13254  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13255 
13256  if (LangOpts.CPlusPlus) {
13257  Decl *ManglingContextDecl;
13258  if (MangleNumberingContext *MCtx =
13259  getCurrentMangleNumberContext(Block->getDeclContext(),
13260  ManglingContextDecl)) {
13261  unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13262  Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13263  }
13264  }
13265 
13266  PushBlockScope(CurScope, Block);
13267  CurContext->addDecl(Block);
13268  if (CurScope)
13269  PushDeclContext(CurScope, Block);
13270  else
13271  CurContext = Block;
13272 
13273  getCurBlock()->HasImplicitReturnType = true;
13274 
13275  // Enter a new evaluation context to insulate the block from any
13276  // cleanups from the enclosing full-expression.
13277  PushExpressionEvaluationContext(
13278  ExpressionEvaluationContext::PotentiallyEvaluated);
13279 }
13280 
13282  Scope *CurScope) {
13283  assert(ParamInfo.getIdentifier() == nullptr &&
13284  "block-id should have no identifier!");
13285  assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13286  BlockScopeInfo *CurBlock = getCurBlock();
13287 
13288  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13289  QualType T = Sig->getType();
13290 
13291  // FIXME: We should allow unexpanded parameter packs here, but that would,
13292  // in turn, make the block expression contain unexpanded parameter packs.
13293  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13294  // Drop the parameters.
13296  EPI.HasTrailingReturn = false;
13298  T = Context.getFunctionType(Context.DependentTy, None, EPI);
13299  Sig = Context.getTrivialTypeSourceInfo(T);
13300  }
13301 
13302  // GetTypeForDeclarator always produces a function type for a block
13303  // literal signature. Furthermore, it is always a FunctionProtoType
13304  // unless the function was written with a typedef.
13305  assert(T->isFunctionType() &&
13306  "GetTypeForDeclarator made a non-function block signature");
13307 
13308  // Look for an explicit signature in that function type.
13309  FunctionProtoTypeLoc ExplicitSignature;
13310 
13311  if ((ExplicitSignature =
13313 
13314  // Check whether that explicit signature was synthesized by
13315  // GetTypeForDeclarator. If so, don't save that as part of the
13316  // written signature.
13317  if (ExplicitSignature.getLocalRangeBegin() ==
13318  ExplicitSignature.getLocalRangeEnd()) {
13319  // This would be much cheaper if we stored TypeLocs instead of
13320  // TypeSourceInfos.
13321  TypeLoc Result = ExplicitSignature.getReturnLoc();
13322  unsigned Size = Result.getFullDataSize();
13323  Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13324  Sig->getTypeLoc().initializeFullCopy(Result, Size);
13325 
13326  ExplicitSignature = FunctionProtoTypeLoc();
13327  }
13328  }
13329 
13330  CurBlock->TheDecl->setSignatureAsWritten(Sig);
13331  CurBlock->FunctionType = T;
13332 
13333  const FunctionType *Fn = T->getAs<FunctionType>();
13334  QualType RetTy = Fn->getReturnType();
13335  bool isVariadic =
13336  (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13337 
13338  CurBlock->TheDecl->setIsVariadic(isVariadic);
13339 
13340  // Context.DependentTy is used as a placeholder for a missing block
13341  // return type. TODO: what should we do with declarators like:
13342  // ^ * { ... }
13343  // If the answer is "apply template argument deduction"....
13344  if (RetTy != Context.DependentTy) {
13345  CurBlock->ReturnType = RetTy;
13346  CurBlock->TheDecl->setBlockMissingReturnType(false);
13347  CurBlock->HasImplicitReturnType = false;
13348  }
13349 
13350  // Push block parameters from the declarator if we had them.
13352  if (ExplicitSignature) {
13353  for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13354  ParmVarDecl *Param = ExplicitSignature.getParam(I);
13355  if (Param->getIdentifier() == nullptr &&
13356  !Param->isImplicit() &&
13357  !Param->isInvalidDecl() &&
13358  !getLangOpts().CPlusPlus)
13359  Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13360  Params.push_back(Param);
13361  }
13362 
13363  // Fake up parameter variables if we have a typedef, like
13364  // ^ fntype { ... }
13365  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13366  for (const auto &I : Fn->param_types()) {
13367  ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13368  CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13369  Params.push_back(Param);
13370  }
13371  }
13372 
13373  // Set the parameters on the block decl.
13374  if (!Params.empty()) {
13375  CurBlock->TheDecl->setParams(Params);
13376  CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13377  /*CheckParameterNames=*/false);
13378  }
13379 
13380  // Finally we can process decl attributes.
13381  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13382 
13383  // Put the parameter variables in scope.
13384  for (auto AI : CurBlock->TheDecl->parameters()) {
13385  AI->setOwningFunction(CurBlock->TheDecl);
13386 
13387  // If this has an identifier, add it to the scope stack.
13388  if (AI->getIdentifier()) {
13389  CheckShadow(CurBlock->TheScope, AI);
13390 
13391  PushOnScopeChains(AI, CurBlock->TheScope);
13392  }
13393  }
13394 }
13395 
13396 /// ActOnBlockError - If there is an error parsing a block, this callback
13397 /// is invoked to pop the information about the block from the action impl.
13398 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13399  // Leave the expression-evaluation context.
13400  DiscardCleanupsInEvaluationContext();
13401  PopExpressionEvaluationContext();
13402 
13403  // Pop off CurBlock, handle nested blocks.
13404  PopDeclContext();
13405  PopFunctionScopeInfo();
13406 }
13407 
13408 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13409 /// literal was successfully completed. ^(int x){...}
13411  Stmt *Body, Scope *CurScope) {
13412  // If blocks are disabled, emit an error.
13413  if (!LangOpts.Blocks)
13414  Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13415 
13416  // Leave the expression-evaluation context.
13417  if (hasAnyUnrecoverableErrorsInThisFunction())
13418  DiscardCleanupsInEvaluationContext();
13419  assert(!Cleanup.exprNeedsCleanups() &&
13420  "cleanups within block not correctly bound!");
13421  PopExpressionEvaluationContext();
13422 
13423  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13424 
13425  if (BSI->HasImplicitReturnType)
13426  deduceClosureReturnType(*BSI);
13427 
13428  PopDeclContext();
13429 
13430  QualType RetTy = Context.VoidTy;
13431  if (!BSI->ReturnType.isNull())
13432  RetTy = BSI->ReturnType;
13433 
13434  bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13435  QualType BlockTy;
13436 
13437  // Set the captured variables on the block.
13438  // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13440  for (Capture &Cap : BSI->Captures) {
13441  if (Cap.isThisCapture())
13442  continue;
13443  BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13444  Cap.isNested(), Cap.getInitExpr());
13445  Captures.push_back(NewCap);
13446  }
13447  BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13448 
13449  // If the user wrote a function type in some form, try to use that.
13450  if (!BSI->FunctionType.isNull()) {
13451  const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13452 
13453  FunctionType::ExtInfo Ext = FTy->getExtInfo();
13454  if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13455 
13456  // Turn protoless block types into nullary block types.
13457  if (isa<FunctionNoProtoType>(FTy)) {
13459  EPI.ExtInfo = Ext;
13460  BlockTy = Context.getFunctionType(RetTy, None, EPI);
13461 
13462  // Otherwise, if we don't need to change anything about the function type,
13463  // preserve its sugar structure.
13464  } else if (FTy->getReturnType() == RetTy &&
13465  (!NoReturn || FTy->getNoReturnAttr())) {
13466  BlockTy = BSI->FunctionType;
13467 
13468  // Otherwise, make the minimal modifications to the function type.
13469  } else {
13470  const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13472  EPI.TypeQuals = 0; // FIXME: silently?
13473  EPI.ExtInfo = Ext;
13474  BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13475  }
13476 
13477  // If we don't have a function type, just build one from nothing.
13478  } else {
13480  EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13481  BlockTy = Context.getFunctionType(RetTy, None, EPI);
13482  }
13483 
13484  DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13485  BlockTy = Context.getBlockPointerType(BlockTy);
13486 
13487  // If needed, diagnose invalid gotos and switches in the block.
13488  if (getCurFunction()->NeedsScopeChecking() &&
13489  !PP.isCodeCompletionEnabled())
13490  DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13491 
13492  BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13493 
13494  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13495  DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13496 
13497  // Try to apply the named return value optimization. We have to check again
13498  // if we can do this, though, because blocks keep return statements around
13499  // to deduce an implicit return type.
13500  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13501  !BSI->TheDecl->isDependentContext())
13502  computeNRVO(Body, BSI);
13503 
13504  BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13505  AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13506  PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13507 
13508  // If the block isn't obviously global, i.e. it captures anything at
13509  // all, then we need to do a few things in the surrounding context:
13510  if (Result->getBlockDecl()->hasCaptures()) {
13511  // First, this expression has a new cleanup object.
13512  ExprCleanupObjects.push_back(Result->getBlockDecl());
13513  Cleanup.setExprNeedsCleanups(true);
13514 
13515  // It also gets a branch-protected scope if any of the captured
13516  // variables needs destruction.
13517  for (const auto &CI : Result->getBlockDecl()->captures()) {
13518  const VarDecl *var = CI.getVariable();
13519  if (var->getType().isDestructedType() != QualType::DK_none) {
13520  setFunctionHasBranchProtectedScope();
13521  break;
13522  }
13523  }
13524  }
13525 
13526  return Result;
13527 }
13528 
13530  SourceLocation RPLoc) {
13531  TypeSourceInfo *TInfo;
13532  GetTypeFromParser(Ty, &TInfo);
13533  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13534 }
13535 
13537  Expr *E, TypeSourceInfo *TInfo,
13538  SourceLocation RPLoc) {
13539  Expr *OrigExpr = E;
13540  bool IsMS = false;
13541 
13542  // CUDA device code does not support varargs.
13543  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13544  if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13545  CUDAFunctionTarget T = IdentifyCUDATarget(F);
13546  if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13547  return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13548  }
13549  }
13550 
13551  // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13552  // as Microsoft ABI on an actual Microsoft platform, where
13553  // __builtin_ms_va_list and __builtin_va_list are the same.)
13554  if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13556  QualType MSVaListType = Context.getBuiltinMSVaListType();
13557  if (Context.hasSameType(MSVaListType, E->getType())) {
13558  if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13559  return ExprError();
13560  IsMS = true;
13561  }
13562  }
13563 
13564  // Get the va_list type
13565  QualType VaListType = Context.getBuiltinVaListType();
13566  if (!IsMS) {
13567  if (VaListType->isArrayType()) {
13568  // Deal with implicit array decay; for example, on x86-64,
13569  // va_list is an array, but it's supposed to decay to
13570  // a pointer for va_arg.
13571  VaListType = Context.getArrayDecayedType(VaListType);
13572  // Make sure the input expression also decays appropriately.
13573  ExprResult Result = UsualUnaryConversions(E);
13574  if (Result.isInvalid())
13575  return ExprError();
13576  E = Result.get();
13577  } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13578  // If va_list is a record type and we are compiling in C++ mode,
13579  // check the argument using reference binding.
13581  Context, Context.getLValueReferenceType(VaListType), false);
13582  ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13583  if (Init.isInvalid())
13584  return ExprError();
13585  E = Init.getAs<Expr>();
13586  } else {
13587  // Otherwise, the va_list argument must be an l-value because
13588  // it is modified by va_arg.
13589  if (!E->isTypeDependent() &&
13590  CheckForModifiableLvalue(E, BuiltinLoc, *this))
13591  return ExprError();
13592  }
13593  }
13594 
13595  if (!IsMS && !E->isTypeDependent() &&
13596  !Context.hasSameType(VaListType, E->getType()))
13597  return ExprError(Diag(E->getLocStart(),
13598  diag::err_first_argument_to_va_arg_not_of_type_va_list)
13599  << OrigExpr->getType() << E->getSourceRange());
13600 
13601  if (!TInfo->getType()->isDependentType()) {
13602  if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13603  diag::err_second_parameter_to_va_arg_incomplete,
13604  TInfo->getTypeLoc()))
13605  return ExprError();
13606 
13607  if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13608  TInfo->getType(),
13609  diag::err_second_parameter_to_va_arg_abstract,
13610  TInfo->getTypeLoc()))
13611  return ExprError();
13612 
13613  if (!TInfo->getType().isPODType(Context)) {
13614  Diag(TInfo->getTypeLoc().getBeginLoc(),
13615  TInfo->getType()->isObjCLifetimeType()
13616  ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13617  : diag::warn_second_parameter_to_va_arg_not_pod)
13618  << TInfo->getType()
13619  << TInfo->getTypeLoc().getSourceRange();
13620  }
13621 
13622  // Check for va_arg where arguments of the given type will be promoted
13623  // (i.e. this va_arg is guaranteed to have undefined behavior).
13624  QualType PromoteType;
13625  if (TInfo->getType()->isPromotableIntegerType()) {
13626  PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13627  if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13628  PromoteType = QualType();
13629  }
13630  if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13631  PromoteType = Context.DoubleTy;
13632  if (!PromoteType.isNull())
13633  DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13634  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13635  << TInfo->getType()
13636  << PromoteType
13637  << TInfo->getTypeLoc().getSourceRange());
13638  }
13639 
13640  QualType T = TInfo->getType().getNonLValueExprType(Context);
13641  return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13642 }
13643 
13645  // The type of __null will be int or long, depending on the size of
13646  // pointers on the target.
13647  QualType Ty;
13648  unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13649  if (pw == Context.getTargetInfo().getIntWidth())
13650  Ty = Context.IntTy;
13651  else if (pw == Context.getTargetInfo().getLongWidth())
13652  Ty = Context.LongTy;
13653  else if (pw == Context.getTargetInfo().getLongLongWidth())
13654  Ty = Context.LongLongTy;
13655  else {
13656  llvm_unreachable("I don't know size of pointer!");
13657  }
13658 
13659  return new (Context) GNUNullExpr(Ty, TokenLoc);
13660 }
13661 
13663  bool Diagnose) {
13664  if (!getLangOpts().ObjC1)
13665  return false;
13666 
13667  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13668  if (!PT)
13669  return false;
13670 
13671  if (!PT->isObjCIdType()) {
13672  // Check if the destination is the 'NSString' interface.
13673  const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13674  if (!ID || !ID->getIdentifier()->isStr("NSString"))
13675  return false;
13676  }
13677 
13678  // Ignore any parens, implicit casts (should only be
13679  // array-to-pointer decays), and not-so-opaque values. The last is
13680  // important for making this trigger for property assignments.
13681  Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13682  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13683  if (OV->getSourceExpr())
13684  SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13685 
13686  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13687  if (!SL || !SL->isAscii())
13688  return false;
13689  if (Diagnose) {
13690  Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13691  << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13692  Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13693  }
13694  return true;
13695 }
13696 
13698  const Expr *SrcExpr) {
13699  if (!DstType->isFunctionPointerType() ||
13700  !SrcExpr->getType()->isFunctionType())
13701  return false;
13702 
13703  auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13704  if (!DRE)
13705  return false;
13706 
13707  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13708  if (!FD)
13709  return false;
13710 
13711  return !S.checkAddressOfFunctionIsAvailable(FD,
13712  /*Complain=*/true,
13713  SrcExpr->getLocStart());
13714 }
13715 
13717  SourceLocation Loc,
13718  QualType DstType, QualType SrcType,
13719  Expr *SrcExpr, AssignmentAction Action,
13720  bool *Complained) {
13721  if (Complained)
13722  *Complained = false;
13723 
13724  // Decode the result (notice that AST's are still created for extensions).
13725  bool CheckInferredResultType = false;
13726  bool isInvalid = false;
13727  unsigned DiagKind = 0;
13728  FixItHint Hint;
13729  ConversionFixItGenerator ConvHints;
13730  bool MayHaveConvFixit = false;
13731  bool MayHaveFunctionDiff = false;
13732  const ObjCInterfaceDecl *IFace = nullptr;
13733  const ObjCProtocolDecl *PDecl = nullptr;
13734 
13735  switch (ConvTy) {
13736  case Compatible:
13737  DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13738  return false;
13739 
13740  case PointerToInt:
13741  DiagKind = diag::ext_typecheck_convert_pointer_int;
13742  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13743  MayHaveConvFixit = true;
13744  break;
13745  case IntToPointer:
13746  DiagKind = diag::ext_typecheck_convert_int_pointer;
13747  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13748  MayHaveConvFixit = true;
13749  break;
13750  case IncompatiblePointer:
13751  if (Action == AA_Passing_CFAudited)
13752  DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13753  else if (SrcType->isFunctionPointerType() &&
13754  DstType->isFunctionPointerType())
13755  DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13756  else
13757  DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13758 
13759  CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13760  SrcType->isObjCObjectPointerType();
13761  if (Hint.isNull() && !CheckInferredResultType) {
13762  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13763  }
13764  else if (CheckInferredResultType) {
13765  SrcType = SrcType.getUnqualifiedType();
13766  DstType = DstType.getUnqualifiedType();
13767  }
13768  MayHaveConvFixit = true;
13769  break;
13770  case IncompatiblePointerSign:
13771  DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13772  break;
13773  case FunctionVoidPointer:
13774  DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13775  break;
13776  case IncompatiblePointerDiscardsQualifiers: {
13777  // Perform array-to-pointer decay if necessary.
13778  if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13779 
13780  Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13781  Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13782  if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13783  DiagKind = diag::err_typecheck_incompatible_address_space;
13784  break;
13785 
13786  } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13787  DiagKind = diag::err_typecheck_incompatible_ownership;
13788  break;
13789  }
13790 
13791  llvm_unreachable("unknown error case for discarding qualifiers!");
13792  // fallthrough
13793  }
13794  case CompatiblePointerDiscardsQualifiers:
13795  // If the qualifiers lost were because we were applying the
13796  // (deprecated) C++ conversion from a string literal to a char*
13797  // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
13798  // Ideally, this check would be performed in
13799  // checkPointerTypesForAssignment. However, that would require a
13800  // bit of refactoring (so that the second argument is an
13801  // expression, rather than a type), which should be done as part
13802  // of a larger effort to fix checkPointerTypesForAssignment for
13803  // C++ semantics.
13804  if (getLangOpts().CPlusPlus &&
13805  IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13806  return false;
13807  DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13808  break;
13809  case IncompatibleNestedPointerQualifiers:
13810  DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13811  break;
13812  case IntToBlockPointer:
13813  DiagKind = diag::err_int_to_block_pointer;
13814  break;
13815  case IncompatibleBlockPointer:
13816  DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13817  break;
13818  case IncompatibleObjCQualifiedId: {
13819  if (SrcType->isObjCQualifiedIdType()) {
13820  const ObjCObjectPointerType *srcOPT =
13821  SrcType->getAs<ObjCObjectPointerType>();
13822  for (auto *srcProto : srcOPT->quals()) {
13823  PDecl = srcProto;
13824  break;
13825  }
13826  if (const ObjCInterfaceType *IFaceT =
13828  IFace = IFaceT->getDecl();
13829  }
13830  else if (DstType->isObjCQualifiedIdType()) {
13831  const ObjCObjectPointerType *dstOPT =
13832  DstType->getAs<ObjCObjectPointerType>();
13833  for (auto *dstProto : dstOPT->quals()) {
13834  PDecl = dstProto;
13835  break;
13836  }
13837  if (const ObjCInterfaceType *IFaceT =
13839  IFace = IFaceT->getDecl();
13840  }
13841  DiagKind = diag::warn_incompatible_qualified_id;
13842  break;
13843  }
13844  case IncompatibleVectors:
13845  DiagKind = diag::warn_incompatible_vectors;
13846  break;
13847  case IncompatibleObjCWeakRef:
13848  DiagKind = diag::err_arc_weak_unavailable_assign;
13849  break;
13850  case Incompatible:
13851  if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13852  if (Complained)
13853  *Complained = true;
13854  return true;
13855  }
13856 
13857  DiagKind = diag::err_typecheck_convert_incompatible;
13858  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13859  MayHaveConvFixit = true;
13860  isInvalid = true;
13861  MayHaveFunctionDiff = true;
13862  break;
13863  }
13864 
13865  QualType FirstType, SecondType;
13866  switch (Action) {
13867  case AA_Assigning:
13868  case AA_Initializing:
13869  // The destination type comes first.
13870  FirstType = DstType;
13871  SecondType = SrcType;
13872  break;
13873 
13874  case AA_Returning:
13875  case AA_Passing:
13876  case AA_Passing_CFAudited:
13877  case AA_Converting:
13878  case AA_Sending:
13879  case AA_Casting:
13880  // The source type comes first.
13881  FirstType = SrcType;
13882  SecondType = DstType;
13883  break;
13884  }
13885 
13886  PartialDiagnostic FDiag = PDiag(DiagKind);
13887  if (Action == AA_Passing_CFAudited)
13888  FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13889  else
13890  FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13891 
13892  // If we can fix the conversion, suggest the FixIts.
13893  assert(ConvHints.isNull() || Hint.isNull());
13894  if (!ConvHints.isNull()) {
13895  for (FixItHint &H : ConvHints.Hints)
13896  FDiag << H;
13897  } else {
13898  FDiag << Hint;
13899  }
13900  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13901 
13902  if (MayHaveFunctionDiff)
13903  HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13904 
13905  Diag(Loc, FDiag);
13906  if (DiagKind == diag::warn_incompatible_qualified_id &&
13907  PDecl && IFace && !IFace->hasDefinition())
13908  Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13909  << IFace << PDecl;
13910 
13911  if (SecondType == Context.OverloadTy)
13912  NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13913  FirstType, /*TakingAddress=*/true);
13914 
13915  if (CheckInferredResultType)
13916  EmitRelatedResultTypeNote(SrcExpr);
13917 
13918  if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13919  EmitRelatedResultTypeNoteForReturn(DstType);
13920 
13921  if (Complained)
13922  *Complained = true;
13923  return isInvalid;
13924 }
13925 
13927  llvm::APSInt *Result) {
13928  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13929  public:
13930  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13931  S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13932  }
13933  } Diagnoser;
13934 
13935  return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13936 }
13937 
13939  llvm::APSInt *Result,
13940  unsigned DiagID,
13941  bool AllowFold) {
13942  class IDDiagnoser : public VerifyICEDiagnoser {
13943  unsigned DiagID;
13944 
13945  public:
13946  IDDiagnoser(unsigned DiagID)
13947  : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13948 
13949  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13950  S.Diag(Loc, DiagID) << SR;
13951  }
13952  } Diagnoser(DiagID);
13953 
13954  return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13955 }
13956 
13958  SourceRange SR) {
13959  S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13960 }
13961 
13962 ExprResult
13964  VerifyICEDiagnoser &Diagnoser,
13965  bool AllowFold) {
13966  SourceLocation DiagLoc = E->getLocStart();
13967 
13968  if (getLangOpts().CPlusPlus11) {
13969  // C++11 [expr.const]p5:
13970  // If an expression of literal class type is used in a context where an
13971  // integral constant expression is required, then that class type shall
13972  // have a single non-explicit conversion function to an integral or
13973  // unscoped enumeration type
13974  ExprResult Converted;
13975  class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13976  public:
13977  CXX11ConvertDiagnoser(bool Silent)
13978  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13979  Silent, true) {}
13980 
13981  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13982  QualType T) override {
13983  return S.Diag(Loc, diag::err_ice_not_integral) << T;
13984  }
13985 
13986  SemaDiagnosticBuilder diagnoseIncomplete(
13987  Sema &S, SourceLocation Loc, QualType T) override {
13988  return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13989  }
13990 
13991  SemaDiagnosticBuilder diagnoseExplicitConv(
13992  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13993  return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13994  }
13995 
13996  SemaDiagnosticBuilder noteExplicitConv(
13997  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13998  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13999  << ConvTy->isEnumeralType() << ConvTy;
14000  }
14001 
14002  SemaDiagnosticBuilder diagnoseAmbiguous(
14003  Sema &S, SourceLocation Loc, QualType T) override {
14004  return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14005  }
14006 
14007  SemaDiagnosticBuilder noteAmbiguous(
14008  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14009  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14010  << ConvTy->isEnumeralType() << ConvTy;
14011  }
14012 
14013  SemaDiagnosticBuilder diagnoseConversion(
14014  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14015  llvm_unreachable("conversion functions are permitted");
14016  }
14017  } ConvertDiagnoser(Diagnoser.Suppress);
14018 
14019  Converted = PerformContextualImplicitConversion(DiagLoc, E,
14020  ConvertDiagnoser);
14021  if (Converted.isInvalid())
14022  return Converted;
14023  E = Converted.get();
14025  return ExprError();
14026  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14027  // An ICE must be of integral or unscoped enumeration type.
14028  if (!Diagnoser.Suppress)
14029  Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14030  return ExprError();
14031  }
14032 
14033  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14034  // in the non-ICE case.
14035  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14036  if (Result)
14037  *Result = E->EvaluateKnownConstInt(Context);
14038  return E;
14039  }
14040 
14041  Expr::EvalResult EvalResult;
14043  EvalResult.Diag = &Notes;
14044 
14045  // Try to evaluate the expression, and produce diagnostics explaining why it's
14046  // not a constant expression as a side-effect.
14047  bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14048  EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14049 
14050  // In C++11, we can rely on diagnostics being produced for any expression
14051  // which is not a constant expression. If no diagnostics were produced, then
14052  // this is a constant expression.
14053  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14054  if (Result)
14055  *Result = EvalResult.Val.getInt();
14056  return E;
14057  }
14058 
14059  // If our only note is the usual "invalid subexpression" note, just point
14060  // the caret at its location rather than producing an essentially
14061  // redundant note.
14062  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14063  diag::note_invalid_subexpr_in_const_expr) {
14064  DiagLoc = Notes[0].first;
14065  Notes.clear();
14066  }
14067 
14068  if (!Folded || !AllowFold) {
14069  if (!Diagnoser.Suppress) {
14070  Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14071  for (const PartialDiagnosticAt &Note : Notes)
14072  Diag(Note.first, Note.second);
14073  }
14074 
14075  return ExprError();
14076  }
14077 
14078  Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14079  for (const PartialDiagnosticAt &Note : Notes)
14080  Diag(Note.first, Note.second);
14081 
14082  if (Result)
14083  *Result = EvalResult.Val.getInt();
14084  return E;
14085 }
14086 
14087 namespace {
14088  // Handle the case where we conclude a expression which we speculatively
14089  // considered to be unevaluated is actually evaluated.
14090  class TransformToPE : public TreeTransform<TransformToPE> {
14091  typedef TreeTransform<TransformToPE> BaseTransform;
14092 
14093  public:
14094  TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14095 
14096  // Make sure we redo semantic analysis
14097  bool AlwaysRebuild() { return true; }
14098 
14099  // Make sure we handle LabelStmts correctly.
14100  // FIXME: This does the right thing, but maybe we need a more general
14101  // fix to TreeTransform?
14102  StmtResult TransformLabelStmt(LabelStmt *S) {
14103  S->getDecl()->setStmt(nullptr);
14104  return BaseTransform::TransformLabelStmt(S);
14105  }
14106 
14107  // We need to special-case DeclRefExprs referring to FieldDecls which
14108  // are not part of a member pointer formation; normal TreeTransforming
14109  // doesn't catch this case because of the way we represent them in the AST.
14110  // FIXME: This is a bit ugly; is it really the best way to handle this
14111  // case?
14112  //
14113  // Error on DeclRefExprs referring to FieldDecls.
14114  ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14115  if (isa<FieldDecl>(E->getDecl()) &&
14116  !SemaRef.isUnevaluatedContext())
14117  return SemaRef.Diag(E->getLocation(),
14118  diag::err_invalid_non_static_member_use)
14119  << E->getDecl() << E->getSourceRange();
14120 
14121  return BaseTransform::TransformDeclRefExpr(E);
14122  }
14123 
14124  // Exception: filter out member pointer formation
14125  ExprResult TransformUnaryOperator(UnaryOperator *E) {
14126  if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14127  return E;
14128 
14129  return BaseTransform::TransformUnaryOperator(E);
14130  }
14131 
14132  ExprResult TransformLambdaExpr(LambdaExpr *E) {
14133  // Lambdas never need to be transformed.
14134  return E;
14135  }
14136  };
14137 }
14138 
14140  assert(isUnevaluatedContext() &&
14141  "Should only transform unevaluated expressions");
14142  ExprEvalContexts.back().Context =
14143  ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14144  if (isUnevaluatedContext())
14145  return E;
14146  return TransformToPE(*this).TransformExpr(E);
14147 }
14148 
14149 void
14151  ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14153  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14154  LambdaContextDecl, ExprContext);
14155  Cleanup.reset();
14156  if (!MaybeODRUseExprs.empty())
14157  std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14158 }
14159 
14160 void
14164  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14165  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14166 }
14167 
14169  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14170  unsigned NumTypos = Rec.NumTypos;
14171 
14172  if (!Rec.Lambdas.empty()) {
14174  if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14175  (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14176  unsigned D;
14177  if (Rec.isUnevaluated()) {
14178  // C++11 [expr.prim.lambda]p2:
14179  // A lambda-expression shall not appear in an unevaluated operand
14180  // (Clause 5).
14181  D = diag::err_lambda_unevaluated_operand;
14182  } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14183  // C++1y [expr.const]p2:
14184  // A conditional-expression e is a core constant expression unless the
14185  // evaluation of e, following the rules of the abstract machine, would
14186  // evaluate [...] a lambda-expression.
14187  D = diag::err_lambda_in_constant_expression;
14188  } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14189  // C++17 [expr.prim.lamda]p2:
14190  // A lambda-expression shall not appear [...] in a template-argument.
14191  D = diag::err_lambda_in_invalid_context;
14192  } else
14193  llvm_unreachable("Couldn't infer lambda error message.");
14194 
14195  for (const auto *L : Rec.Lambdas)
14196  Diag(L->getLocStart(), D);
14197  } else {
14198  // Mark the capture expressions odr-used. This was deferred
14199  // during lambda expression creation.
14200  for (auto *Lambda : Rec.Lambdas) {
14201  for (auto *C : Lambda->capture_inits())
14202  MarkDeclarationsReferencedInExpr(C);
14203  }
14204  }
14205  }
14206 
14207  // When are coming out of an unevaluated context, clear out any
14208  // temporaries that we may have created as part of the evaluation of
14209  // the expression in that context: they aren't relevant because they
14210  // will never be constructed.
14211  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14212  ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14213  ExprCleanupObjects.end());
14214  Cleanup = Rec.ParentCleanup;
14215  CleanupVarDeclMarking();
14216  std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14217  // Otherwise, merge the contexts together.
14218  } else {
14219  Cleanup.mergeFrom(Rec.ParentCleanup);
14220  MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14221  Rec.SavedMaybeODRUseExprs.end());
14222  }
14223 
14224  // Pop the current expression evaluation context off the stack.
14225  ExprEvalContexts.pop_back();
14226 
14227  if (!ExprEvalContexts.empty())
14228  ExprEvalContexts.back().NumTypos += NumTypos;
14229  else
14230  assert(NumTypos == 0 && "There are outstanding typos after popping the "
14231  "last ExpressionEvaluationContextRecord");
14232 }
14233 
14235  ExprCleanupObjects.erase(
14236  ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14237  ExprCleanupObjects.end());
14238  Cleanup.reset();
14239  MaybeODRUseExprs.clear();
14240 }
14241 
14243  if (!E->getType()->isVariablyModifiedType())
14244  return E;
14245  return TransformToPotentiallyEvaluated(E);
14246 }
14247 
14248 /// Are we within a context in which some evaluation could be performed (be it
14249 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14250 /// captured by C++'s idea of an "unevaluated context".
14251 static bool isEvaluatableContext(Sema &SemaRef) {
14252  switch (SemaRef.ExprEvalContexts.back().Context) {
14255  // Expressions in this context are never evaluated.
14256  return false;
14257 
14262  // Expressions in this context could be evaluated.
14263  return true;
14264 
14266  // Referenced declarations will only be used if the construct in the
14267  // containing expression is used, at which point we'll be given another
14268  // turn to mark them.
14269  return false;
14270  }
14271  llvm_unreachable("Invalid context");
14272 }
14273 
14274 /// Are we within a context in which references to resolved functions or to
14275 /// variables result in odr-use?
14276 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14277  // An expression in a template is not really an expression until it's been
14278  // instantiated, so it doesn't trigger odr-use.
14279  if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14280  return false;
14281 
14282  switch (SemaRef.ExprEvalContexts.back().Context) {
14287  return false;
14288 
14291  return true;
14292 
14294  return false;
14295  }
14296  llvm_unreachable("Invalid context");
14297 }
14298 
14300  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14301  return Func->isConstexpr() &&
14302  (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14303 }
14304 
14305 /// Mark a function referenced, and check whether it is odr-used
14306 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14308  bool MightBeOdrUse) {
14309  assert(Func && "No function?");
14310 
14311  Func->setReferenced();
14312 
14313  // C++11 [basic.def.odr]p3:
14314  // A function whose name appears as a potentially-evaluated expression is
14315  // odr-used if it is the unique lookup result or the selected member of a
14316  // set of overloaded functions [...].
14317  //
14318  // We (incorrectly) mark overload resolution as an unevaluated context, so we
14319  // can just check that here.
14320  bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14321 
14322  // Determine whether we require a function definition to exist, per
14323  // C++11 [temp.inst]p3:
14324  // Unless a function template specialization has been explicitly
14325  // instantiated or explicitly specialized, the function template
14326  // specialization is implicitly instantiated when the specialization is
14327  // referenced in a context that requires a function definition to exist.
14328  //
14329  // That is either when this is an odr-use, or when a usage of a constexpr
14330  // function occurs within an evaluatable context.
14331  bool NeedDefinition =
14332  OdrUse || (isEvaluatableContext(*this) &&
14334 
14335  // C++14 [temp.expl.spec]p6:
14336  // If a template [...] is explicitly specialized then that specialization
14337  // shall be declared before the first use of that specialization that would
14338  // cause an implicit instantiation to take place, in every translation unit
14339  // in which such a use occurs
14340  if (NeedDefinition &&
14342  Func->getMemberSpecializationInfo()))
14343  checkSpecializationVisibility(Loc, Func);
14344 
14345  // C++14 [except.spec]p17:
14346  // An exception-specification is considered to be needed when:
14347  // - the function is odr-used or, if it appears in an unevaluated operand,
14348  // would be odr-used if the expression were potentially-evaluated;
14349  //
14350  // Note, we do this even if MightBeOdrUse is false. That indicates that the
14351  // function is a pure virtual function we're calling, and in that case the
14352  // function was selected by overload resolution and we need to resolve its
14353  // exception specification for a different reason.
14354  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14356  ResolveExceptionSpec(Loc, FPT);
14357 
14358  // If we don't need to mark the function as used, and we don't need to
14359  // try to provide a definition, there's nothing more to do.
14360  if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14361  (!NeedDefinition || Func->getBody()))
14362  return;
14363 
14364  // Note that this declaration has been used.
14365  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14366  Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14367  if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14368  if (Constructor->isDefaultConstructor()) {
14369  if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14370  return;
14371  DefineImplicitDefaultConstructor(Loc, Constructor);
14372  } else if (Constructor->isCopyConstructor()) {
14373  DefineImplicitCopyConstructor(Loc, Constructor);
14374  } else if (Constructor->isMoveConstructor()) {
14375  DefineImplicitMoveConstructor(Loc, Constructor);
14376  }
14377  } else if (Constructor->getInheritedConstructor()) {
14378  DefineInheritingConstructor(Loc, Constructor);
14379  }
14380  } else if (CXXDestructorDecl *Destructor =
14381  dyn_cast<CXXDestructorDecl>(Func)) {
14382  Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14383  if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14384  if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14385  return;
14386  DefineImplicitDestructor(Loc, Destructor);
14387  }
14388  if (Destructor->isVirtual() && getLangOpts().AppleKext)
14389  MarkVTableUsed(Loc, Destructor->getParent());
14390  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14391  if (MethodDecl->isOverloadedOperator() &&
14392  MethodDecl->getOverloadedOperator() == OO_Equal) {
14393  MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14394  if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14395  if (MethodDecl->isCopyAssignmentOperator())
14396  DefineImplicitCopyAssignment(Loc, MethodDecl);
14397  else if (MethodDecl->isMoveAssignmentOperator())
14398  DefineImplicitMoveAssignment(Loc, MethodDecl);
14399  }
14400  } else if (isa<CXXConversionDecl>(MethodDecl) &&
14401  MethodDecl->getParent()->isLambda()) {
14402  CXXConversionDecl *Conversion =
14403  cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14404  if (Conversion->isLambdaToBlockPointerConversion())
14405  DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14406  else
14407  DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14408  } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14409  MarkVTableUsed(Loc, MethodDecl->getParent());
14410  }
14411 
14412  // Recursive functions should be marked when used from another function.
14413  // FIXME: Is this really right?
14414  if (CurContext == Func) return;
14415 
14416  // Implicit instantiation of function templates and member functions of
14417  // class templates.
14418  if (Func->isImplicitlyInstantiable()) {
14420  SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14421  bool FirstInstantiation = PointOfInstantiation.isInvalid();
14422  if (FirstInstantiation) {
14423  PointOfInstantiation = Loc;
14424  Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14425  } else if (TSK != TSK_ImplicitInstantiation) {
14426  // Use the point of use as the point of instantiation, instead of the
14427  // point of explicit instantiation (which we track as the actual point of
14428  // instantiation). This gives better backtraces in diagnostics.
14429  PointOfInstantiation = Loc;
14430  }
14431 
14432  if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14433  Func->isConstexpr()) {
14434  if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14435  cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14436  CodeSynthesisContexts.size())
14437  PendingLocalImplicitInstantiations.push_back(
14438  std::make_pair(Func, PointOfInstantiation));
14439  else if (Func->isConstexpr())
14440  // Do not defer instantiations of constexpr functions, to avoid the
14441  // expression evaluator needing to call back into Sema if it sees a
14442  // call to such a function.
14443  InstantiateFunctionDefinition(PointOfInstantiation, Func);
14444  else {
14445  Func->setInstantiationIsPending(true);
14446  PendingInstantiations.push_back(std::make_pair(Func,
14447  PointOfInstantiation));
14448  // Notify the consumer that a function was implicitly instantiated.
14449  Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14450  }
14451  }
14452  } else {
14453  // Walk redefinitions, as some of them may be instantiable.
14454  for (auto i : Func->redecls()) {
14455  if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14456  MarkFunctionReferenced(Loc, i, OdrUse);
14457  }
14458  }
14459 
14460  if (!OdrUse) return;
14461 
14462  // Keep track of used but undefined functions.
14463  if (!Func->isDefined()) {
14464  if (mightHaveNonExternalLinkage(Func))
14465  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14466  else if (Func->getMostRecentDecl()->isInlined() &&
14467  !LangOpts.GNUInline &&
14468  !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14469  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14470  else if (isExternalWithNoLinkageType(Func))
14471  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14472  }
14473 
14474  Func->markUsed(Context);
14475 }
14476 
14477 static void
14479  ValueDecl *var, DeclContext *DC) {
14480  DeclContext *VarDC = var->getDeclContext();
14481 
14482  // If the parameter still belongs to the translation unit, then
14483  // we're actually just using one parameter in the declaration of
14484  // the next.
14485  if (isa<ParmVarDecl>(var) &&
14486  isa<TranslationUnitDecl>(VarDC))
14487  return;
14488 
14489  // For C code, don't diagnose about capture if we're not actually in code
14490  // right now; it's impossible to write a non-constant expression outside of
14491  // function context, so we'll get other (more useful) diagnostics later.
14492  //
14493  // For C++, things get a bit more nasty... it would be nice to suppress this
14494  // diagnostic for certain cases like using a local variable in an array bound
14495  // for a member of a local class, but the correct predicate is not obvious.
14496  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14497  return;
14498 
14499  unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14500  unsigned ContextKind = 3; // unknown
14501  if (isa<CXXMethodDecl>(VarDC) &&
14502  cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14503  ContextKind = 2;
14504  } else if (isa<FunctionDecl>(VarDC)) {
14505  ContextKind = 0;
14506  } else if (isa<BlockDecl>(VarDC)) {
14507  ContextKind = 1;
14508  }
14509 
14510  S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14511  << var << ValueKind << ContextKind << VarDC;
14512  S.Diag(var->getLocation(), diag::note_entity_declared_at)
14513  << var;
14514 
14515  // FIXME: Add additional diagnostic info about class etc. which prevents
14516  // capture.
14517 }
14518 
14519 
14521  bool &SubCapturesAreNested,
14522  QualType &CaptureType,
14523  QualType &DeclRefType) {
14524  // Check whether we've already captured it.
14525  if (CSI->CaptureMap.count(Var)) {
14526  // If we found a capture, any subcaptures are nested.
14527  SubCapturesAreNested = true;
14528 
14529  // Retrieve the capture type for this variable.
14530  CaptureType = CSI->getCapture(Var).getCaptureType();
14531 
14532  // Compute the type of an expression that refers to this variable.
14533  DeclRefType = CaptureType.getNonReferenceType();
14534 
14535  // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14536  // are mutable in the sense that user can change their value - they are
14537  // private instances of the captured declarations.
14538  const Capture &Cap = CSI->getCapture(Var);
14539  if (Cap.isCopyCapture() &&
14540  !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14541  !(isa<CapturedRegionScopeInfo>(CSI) &&
14542  cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14543  DeclRefType.addConst();
14544  return true;
14545  }
14546  return false;
14547 }
14548 
14549 // Only block literals, captured statements, and lambda expressions can
14550 // capture; other scopes don't work.
14552  SourceLocation Loc,
14553  const bool Diagnose, Sema &S) {
14554  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14556  else if (Var->hasLocalStorage()) {
14557  if (Diagnose)
14558  diagnoseUncapturableValueReference(S, Loc, Var, DC);
14559  }
14560  return nullptr;
14561 }
14562 
14563 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14564 // certain types of variables (unnamed, variably modified types etc.)
14565 // so check for eligibility.
14567  SourceLocation Loc,
14568  const bool Diagnose, Sema &S) {
14569 
14570  bool IsBlock = isa<BlockScopeInfo>(CSI);
14571  bool IsLambda = isa<LambdaScopeInfo>(CSI);
14572 
14573  // Lambdas are not allowed to capture unnamed variables
14574  // (e.g. anonymous unions).
14575  // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14576  // assuming that's the intent.
14577  if (IsLambda && !Var->getDeclName()) {
14578  if (Diagnose) {
14579  S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14580  S.Diag(Var->getLocation(), diag::note_declared_at);
14581  }
14582  return false;
14583  }
14584 
14585  // Prohibit variably-modified types in blocks; they're difficult to deal with.
14586  if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14587  if (Diagnose) {
14588  S.Diag(Loc, diag::err_ref_vm_type);
14589  S.Diag(Var->getLocation(), diag::note_previous_decl)
14590  << Var->getDeclName();
14591  }
14592  return false;
14593  }
14594  // Prohibit structs with flexible array members too.
14595  // We cannot capture what is in the tail end of the struct.
14596  if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14597  if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14598  if (Diagnose) {
14599  if (IsBlock)
14600  S.Diag(Loc, diag::err_ref_flexarray_type);
14601  else
14602  S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14603  << Var->getDeclName();
14604  S.Diag(Var->getLocation(), diag::note_previous_decl)
14605  << Var->getDeclName();
14606  }
14607  return false;
14608  }
14609  }
14610  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14611  // Lambdas and captured statements are not allowed to capture __block
14612  // variables; they don't support the expected semantics.
14613  if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14614  if (Diagnose) {
14615  S.Diag(Loc, diag::err_capture_block_variable)
14616  << Var->getDeclName() << !IsLambda;
14617  S.Diag(Var->getLocation(), diag::note_previous_decl)
14618  << Var->getDeclName();
14619  }
14620  return false;
14621  }
14622  // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14623  if (S.getLangOpts().OpenCL && IsBlock &&
14624  Var->getType()->isBlockPointerType()) {
14625  if (Diagnose)
14626  S.Diag(Loc, diag::err_opencl_block_ref_block);
14627  return false;
14628  }
14629 
14630  return true;
14631 }
14632 
14633 // Returns true if the capture by block was successful.
14634 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14635  SourceLocation Loc,
14636  const bool BuildAndDiagnose,
14637  QualType &CaptureType,
14638  QualType &DeclRefType,
14639  const bool Nested,
14640  Sema &S) {
14641  Expr *CopyExpr = nullptr;
14642  bool ByRef = false;
14643 
14644  // Blocks are not allowed to capture arrays.
14645  if (CaptureType->isArrayType()) {
14646  if (BuildAndDiagnose) {
14647  S.Diag(Loc, diag::err_ref_array_type);
14648  S.Diag(Var->getLocation(), diag::note_previous_decl)
14649  << Var->getDeclName();
14650  }
14651  return false;
14652  }
14653 
14654  // Forbid the block-capture of autoreleasing variables.
14655  if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14656  if (BuildAndDiagnose) {
14657  S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14658  << /*block*/ 0;
14659  S.Diag(Var->getLocation(), diag::note_previous_decl)
14660  << Var->getDeclName();
14661  }
14662  return false;
14663  }
14664 
14665  // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14666  if (const auto *PT = CaptureType->getAs<PointerType>()) {
14667  // This function finds out whether there is an AttributedType of kind
14668  // attr_objc_ownership in Ty. The existence of AttributedType of kind
14669  // attr_objc_ownership implies __autoreleasing was explicitly specified
14670  // rather than being added implicitly by the compiler.
14671  auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14672  while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14673  if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14674  return true;
14675 
14676  // Peel off AttributedTypes that are not of kind objc_ownership.
14677  Ty = AttrTy->getModifiedType();
14678  }
14679 
14680  return false;
14681  };
14682 
14683  QualType PointeeTy = PT->getPointeeType();
14684 
14685  if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14687  !IsObjCOwnershipAttributedType(PointeeTy)) {
14688  if (BuildAndDiagnose) {
14689  SourceLocation VarLoc = Var->getLocation();
14690  S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14691  S.Diag(VarLoc, diag::note_declare_parameter_strong);
14692  }
14693  }
14694  }
14695 
14696  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14697  if (HasBlocksAttr || CaptureType->isReferenceType() ||
14698  (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14699  // Block capture by reference does not change the capture or
14700  // declaration reference types.
14701  ByRef = true;
14702  } else {
14703  // Block capture by copy introduces 'const'.
14704  CaptureType = CaptureType.getNonReferenceType().withConst();
14705  DeclRefType = CaptureType;
14706 
14707  if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14708  if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14709  // The capture logic needs the destructor, so make sure we mark it.
14710  // Usually this is unnecessary because most local variables have
14711  // their destructors marked at declaration time, but parameters are
14712  // an exception because it's technically only the call site that
14713  // actually requires the destructor.
14714  if (isa<ParmVarDecl>(Var))
14715  S.FinalizeVarWithDestructor(Var, Record);
14716 
14717  // Enter a new evaluation context to insulate the copy
14718  // full-expression.
14721 
14722  // According to the blocks spec, the capture of a variable from
14723  // the stack requires a const copy constructor. This is not true
14724  // of the copy/move done to move a __block variable to the heap.
14725  Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14726  DeclRefType.withConst(),
14727  VK_LValue, Loc);
14728 
14729  ExprResult Result
14732  CaptureType, false),
14733  Loc, DeclRef);
14734 
14735  // Build a full-expression copy expression if initialization
14736  // succeeded and used a non-trivial constructor. Recover from
14737  // errors by pretending that the copy isn't necessary.
14738  if (!Result.isInvalid() &&
14739  !cast<CXXConstructExpr>(Result.get())->getConstructor()
14740  ->isTrivial()) {
14741  Result = S.MaybeCreateExprWithCleanups(Result);
14742  CopyExpr = Result.get();
14743  }
14744  }
14745  }
14746  }
14747 
14748  // Actually capture the variable.
14749  if (BuildAndDiagnose)
14750  BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14751  SourceLocation(), CaptureType, CopyExpr);
14752 
14753  return true;
14754 
14755 }
14756 
14757 
14758 /// Capture the given variable in the captured region.
14760  VarDecl *Var,
14761  SourceLocation Loc,
14762  const bool BuildAndDiagnose,
14763  QualType &CaptureType,
14764  QualType &DeclRefType,
14765  const bool RefersToCapturedVariable,
14766  Sema &S) {
14767  // By default, capture variables by reference.
14768  bool ByRef = true;
14769  // Using an LValue reference type is consistent with Lambdas (see below).
14770  if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14771  if (S.isOpenMPCapturedDecl(Var)) {
14772  bool HasConst = DeclRefType.isConstQualified();
14773  DeclRefType = DeclRefType.getUnqualifiedType();
14774  // Don't lose diagnostics about assignments to const.
14775  if (HasConst)
14776  DeclRefType.addConst();
14777  }
14778  ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14779  }
14780 
14781  if (ByRef)
14782  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14783  else
14784  CaptureType = DeclRefType;
14785 
14786  Expr *CopyExpr = nullptr;
14787  if (BuildAndDiagnose) {
14788  // The current implementation assumes that all variables are captured
14789  // by references. Since there is no capture by copy, no expression
14790  // evaluation will be needed.
14791  RecordDecl *RD = RSI->TheRecordDecl;
14792 
14793  FieldDecl *Field
14794  = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14795  S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14796  nullptr, false, ICIS_NoInit);
14797  Field->setImplicit(true);
14798  Field->setAccess(AS_private);
14799  RD->addDecl(Field);
14800  if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14801  S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14802 
14803  CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14804  DeclRefType, VK_LValue, Loc);
14805  Var->setReferenced(true);
14806  Var->markUsed(S.Context);
14807  }
14808 
14809  // Actually capture the variable.
14810  if (BuildAndDiagnose)
14811  RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14812  SourceLocation(), CaptureType, CopyExpr);
14813 
14814 
14815  return true;
14816 }
14817 
14818 /// Create a field within the lambda class for the variable
14819 /// being captured.
14821  QualType FieldType, QualType DeclRefType,
14822  SourceLocation Loc,
14823  bool RefersToCapturedVariable) {
14824  CXXRecordDecl *Lambda = LSI->Lambda;
14825 
14826  // Build the non-static data member.
14827  FieldDecl *Field
14828  = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14829  S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14830  nullptr, false, ICIS_NoInit);
14831  Field->setImplicit(true);
14832  Field->setAccess(AS_private);
14833  Lambda->addDecl(Field);
14834 }
14835 
14836 /// Capture the given variable in the lambda.
14838  VarDecl *Var,
14839  SourceLocation Loc,
14840  const bool BuildAndDiagnose,
14841  QualType &CaptureType,
14842  QualType &DeclRefType,
14843  const bool RefersToCapturedVariable,
14844  const Sema::TryCaptureKind Kind,
14845  SourceLocation EllipsisLoc,
14846  const bool IsTopScope,
14847  Sema &S) {
14848 
14849  // Determine whether we are capturing by reference or by value.
14850  bool ByRef = false;
14851  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14852  ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14853  } else {
14855  }
14856 
14857  // Compute the type of the field that will capture this variable.
14858  if (ByRef) {
14859  // C++11 [expr.prim.lambda]p15:
14860  // An entity is captured by reference if it is implicitly or
14861  // explicitly captured but not captured by copy. It is
14862  // unspecified whether additional unnamed non-static data
14863  // members are declared in the closure type for entities
14864  // captured by reference.
14865  //
14866  // FIXME: It is not clear whether we want to build an lvalue reference
14867  // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14868  // to do the former, while EDG does the latter. Core issue 1249 will
14869  // clarify, but for now we follow GCC because it's a more permissive and
14870  // easily defensible position.
14871  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14872  } else {
14873  // C++11 [expr.prim.lambda]p14:
14874  // For each entity captured by copy, an unnamed non-static
14875  // data member is declared in the closure type. The
14876  // declaration order of these members is unspecified. The type
14877  // of such a data member is the type of the corresponding
14878  // captured entity if the entity is not a reference to an
14879  // object, or the referenced type otherwise. [Note: If the
14880  // captured entity is a reference to a function, the
14881  // corresponding data member is also a reference to a
14882  // function. - end note ]
14883  if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14884  if (!RefType->getPointeeType()->isFunctionType())
14885  CaptureType = RefType->getPointeeType();
14886  }
14887 
14888  // Forbid the lambda copy-capture of autoreleasing variables.
14889  if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14890  if (BuildAndDiagnose) {
14891  S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14892  S.Diag(Var->getLocation(), diag::note_previous_decl)
14893  << Var->getDeclName();
14894  }
14895  return false;
14896  }
14897 
14898  // Make sure that by-copy captures are of a complete and non-abstract type.
14899  if (BuildAndDiagnose) {
14900  if (!CaptureType->isDependentType() &&
14901  S.RequireCompleteType(Loc, CaptureType,
14902  diag::err_capture_of_incomplete_type,
14903  Var->getDeclName()))
14904  return false;
14905 
14906  if (S.RequireNonAbstractType(Loc, CaptureType,
14907  diag::err_capture_of_abstract_type))
14908  return false;
14909  }
14910  }
14911 
14912  // Capture this variable in the lambda.
14913  if (BuildAndDiagnose)
14914  addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14915  RefersToCapturedVariable);
14916 
14917  // Compute the type of a reference to this captured variable.
14918  if (ByRef)
14919  DeclRefType = CaptureType.getNonReferenceType();
14920  else {
14921  // C++ [expr.prim.lambda]p5:
14922  // The closure type for a lambda-expression has a public inline
14923  // function call operator [...]. This function call operator is
14924  // declared const (9.3.1) if and only if the lambda-expression's
14925  // parameter-declaration-clause is not followed by mutable.
14926  DeclRefType = CaptureType.getNonReferenceType();
14927  if (!LSI->Mutable && !CaptureType->isReferenceType())
14928  DeclRefType.addConst();
14929  }
14930 
14931  // Add the capture.
14932  if (BuildAndDiagnose)
14933  LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14934  Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14935 
14936  return true;
14937 }
14938 
14940  VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14941  SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14942  QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14943  // An init-capture is notionally from the context surrounding its
14944  // declaration, but its parent DC is the lambda class.
14945  DeclContext *VarDC = Var->getDeclContext();
14946  if (Var->isInitCapture())
14947  VarDC = VarDC->getParent();
14948 
14949  DeclContext *DC = CurContext;
14950  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14951  ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14952  // We need to sync up the Declaration Context with the
14953  // FunctionScopeIndexToStopAt
14954  if (FunctionScopeIndexToStopAt) {
14955  unsigned FSIndex = FunctionScopes.size() - 1;
14956  while (FSIndex != MaxFunctionScopesIndex) {
14958  --FSIndex;
14959  }
14960  }
14961 
14962 
14963  // If the variable is declared in the current context, there is no need to
14964  // capture it.
14965  if (VarDC == DC) return true;
14966 
14967  // Capture global variables if it is required to use private copy of this
14968  // variable.
14969  bool IsGlobal = !Var->hasLocalStorage();
14970  if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14971  return true;
14972  Var = Var->getCanonicalDecl();
14973 
14974  // Walk up the stack to determine whether we can capture the variable,
14975  // performing the "simple" checks that don't depend on type. We stop when
14976  // we've either hit the declared scope of the variable or find an existing
14977  // capture of that variable. We start from the innermost capturing-entity
14978  // (the DC) and ensure that all intervening capturing-entities
14979  // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14980  // declcontext can either capture the variable or have already captured
14981  // the variable.
14982  CaptureType = Var->getType();
14983  DeclRefType = CaptureType.getNonReferenceType();
14984  bool Nested = false;
14985  bool Explicit = (Kind != TryCapture_Implicit);
14986  unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14987  do {
14988  // Only block literals, captured statements, and lambda expressions can
14989  // capture; other scopes don't work.
14990  DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14991  ExprLoc,
14992  BuildAndDiagnose,
14993  *this);
14994  // We need to check for the parent *first* because, if we *have*
14995  // private-captured a global variable, we need to recursively capture it in
14996  // intermediate blocks, lambdas, etc.
14997  if (!ParentDC) {
14998  if (IsGlobal) {
14999  FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15000  break;
15001  }
15002  return true;
15003  }
15004 
15005  FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
15006  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15007 
15008 
15009  // Check whether we've already captured it.
15010  if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15011  DeclRefType)) {
15012  CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15013  break;
15014  }
15015  // If we are instantiating a generic lambda call operator body,
15016  // we do not want to capture new variables. What was captured
15017  // during either a lambdas transformation or initial parsing
15018  // should be used.
15020  if (BuildAndDiagnose) {
15021  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15023  Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15024  Diag(Var->getLocation(), diag::note_previous_decl)
15025  << Var->getDeclName();
15026  Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
15027  } else
15028  diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15029  }
15030  return true;
15031  }
15032  // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15033  // certain types of variables (unnamed, variably modified types etc.)
15034  // so check for eligibility.
15035  if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15036  return true;
15037 
15038  // Try to capture variable-length arrays types.
15039  if (Var->getType()->isVariablyModifiedType()) {
15040  // We're going to walk down into the type and look for VLA
15041  // expressions.
15042  QualType QTy = Var->getType();
15043  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15044  QTy = PVD->getOriginalType();
15045  captureVariablyModifiedType(Context, QTy, CSI);
15046  }
15047 
15048  if (getLangOpts().OpenMP) {
15049  if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15050  // OpenMP private variables should not be captured in outer scope, so
15051  // just break here. Similarly, global variables that are captured in a
15052  // target region should not be captured outside the scope of the region.
15053  if (RSI->CapRegionKind == CR_OpenMP) {
15054  bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15055  auto IsTargetCap = !IsOpenMPPrivateDecl &&
15056  isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15057  // When we detect target captures we are looking from inside the
15058  // target region, therefore we need to propagate the capture from the
15059  // enclosing region. Therefore, the capture is not initially nested.
15060  if (IsTargetCap)
15061  adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15062 
15063  if (IsTargetCap || IsOpenMPPrivateDecl) {
15064  Nested = !IsTargetCap;
15065  DeclRefType = DeclRefType.getUnqualifiedType();
15066  CaptureType = Context.getLValueReferenceType(DeclRefType);
15067  break;
15068  }
15069  }
15070  }
15071  }
15072  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15073  // No capture-default, and this is not an explicit capture
15074  // so cannot capture this variable.
15075  if (BuildAndDiagnose) {
15076  Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15077  Diag(Var->getLocation(), diag::note_previous_decl)
15078  << Var->getDeclName();
15079  if (cast<LambdaScopeInfo>(CSI)->Lambda)
15080  Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
15081  diag::note_lambda_decl);
15082  // FIXME: If we error out because an outer lambda can not implicitly
15083  // capture a variable that an inner lambda explicitly captures, we
15084  // should have the inner lambda do the explicit capture - because
15085  // it makes for cleaner diagnostics later. This would purely be done
15086  // so that the diagnostic does not misleadingly claim that a variable
15087  // can not be captured by a lambda implicitly even though it is captured
15088  // explicitly. Suggestion:
15089  // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15090  // at the function head
15091  // - cache the StartingDeclContext - this must be a lambda
15092  // - captureInLambda in the innermost lambda the variable.
15093  }
15094  return true;
15095  }
15096 
15097  FunctionScopesIndex--;
15098  DC = ParentDC;
15099  Explicit = false;
15100  } while (!VarDC->Equals(DC));
15101 
15102  // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15103  // computing the type of the capture at each step, checking type-specific
15104  // requirements, and adding captures if requested.
15105  // If the variable had already been captured previously, we start capturing
15106  // at the lambda nested within that one.
15107  for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15108  ++I) {
15109  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15110 
15111  if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15112  if (!captureInBlock(BSI, Var, ExprLoc,
15113  BuildAndDiagnose, CaptureType,
15114  DeclRefType, Nested, *this))
15115  return true;
15116  Nested = true;
15117  } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15118  if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15119  BuildAndDiagnose, CaptureType,
15120  DeclRefType, Nested, *this))
15121  return true;
15122  Nested = true;
15123  } else {
15124  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15125  if (!captureInLambda(LSI, Var, ExprLoc,
15126  BuildAndDiagnose, CaptureType,
15127  DeclRefType, Nested, Kind, EllipsisLoc,
15128  /*IsTopScope*/I == N - 1, *this))
15129  return true;
15130  Nested = true;
15131  }
15132  }
15133  return false;
15134 }
15135 
15137  TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15138  QualType CaptureType;
15139  QualType DeclRefType;
15140  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15141  /*BuildAndDiagnose=*/true, CaptureType,
15142  DeclRefType, nullptr);
15143 }
15144 
15146  QualType CaptureType;
15147  QualType DeclRefType;
15148  return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15149  /*BuildAndDiagnose=*/false, CaptureType,
15150  DeclRefType, nullptr);
15151 }
15152 
15154  QualType CaptureType;
15155  QualType DeclRefType;
15156 
15157  // Determine whether we can capture this variable.
15158  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15159  /*BuildAndDiagnose=*/false, CaptureType,
15160  DeclRefType, nullptr))
15161  return QualType();
15162 
15163  return DeclRefType;
15164 }
15165 
15166 
15167 
15168 // If either the type of the variable or the initializer is dependent,
15169 // return false. Otherwise, determine whether the variable is a constant
15170 // expression. Use this if you need to know if a variable that might or
15171 // might not be dependent is truly a constant expression.
15173  ASTContext &Context) {
15174 
15175  if (Var->getType()->isDependentType())
15176  return false;
15177  const VarDecl *DefVD = nullptr;
15178  Var->getAnyInitializer(DefVD);
15179  if (!DefVD)
15180  return false;
15181  EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15182  Expr *Init = cast<Expr>(Eval->Value);
15183  if (Init->isValueDependent())
15184  return false;
15185  return IsVariableAConstantExpression(Var, Context);
15186 }
15187 
15188 
15190  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15191  // an object that satisfies the requirements for appearing in a
15192  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15193  // is immediately applied." This function handles the lvalue-to-rvalue
15194  // conversion part.
15195  MaybeODRUseExprs.erase(E->IgnoreParens());
15196 
15197  // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15198  // to a variable that is a constant expression, and if so, identify it as
15199  // a reference to a variable that does not involve an odr-use of that
15200  // variable.
15201  if (LambdaScopeInfo *LSI = getCurLambda()) {
15202  Expr *SansParensExpr = E->IgnoreParens();
15203  VarDecl *Var = nullptr;
15204  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15205  Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15206  else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15207  Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15208 
15209  if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15210  LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15211  }
15212 }
15213 
15215  Res = CorrectDelayedTyposInExpr(Res);
15216 
15217  if (!Res.isUsable())
15218  return Res;
15219 
15220  // If a constant-expression is a reference to a variable where we delay
15221  // deciding whether it is an odr-use, just assume we will apply the
15222  // lvalue-to-rvalue conversion. In the one case where this doesn't happen
15223  // (a non-type template argument), we have special handling anyway.
15224  UpdateMarkingForLValueToRValue(Res.get());
15225  return Res;
15226 }
15227 
15229  for (Expr *E : MaybeODRUseExprs) {
15230  VarDecl *Var;
15231  SourceLocation Loc;
15232  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15233  Var = cast<VarDecl>(DRE->getDecl());
15234  Loc = DRE->getLocation();
15235  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15236  Var = cast<VarDecl>(ME->getMemberDecl());
15237  Loc = ME->getMemberLoc();
15238  } else {
15239  llvm_unreachable("Unexpected expression");
15240  }
15241 
15242  MarkVarDeclODRUsed(Var, Loc, *this,
15243  /*MaxFunctionScopeIndex Pointer*/ nullptr);
15244  }
15245 
15246  MaybeODRUseExprs.clear();
15247 }
15248 
15249 
15250 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15251  VarDecl *Var, Expr *E) {
15252  assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15253  "Invalid Expr argument to DoMarkVarDeclReferenced");
15254  Var->setReferenced();
15255 
15257 
15258  bool OdrUseContext = isOdrUseContext(SemaRef);
15259  bool UsableInConstantExpr =
15260  Var->isUsableInConstantExpressions(SemaRef.Context);
15261  bool NeedDefinition =
15262  OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15263 
15265  dyn_cast<VarTemplateSpecializationDecl>(Var);
15266  assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15267  "Can't instantiate a partial template specialization.");
15268 
15269  // If this might be a member specialization of a static data member, check
15270  // the specialization is visible. We already did the checks for variable
15271  // template specializations when we created them.
15272  if (NeedDefinition && TSK != TSK_Undeclared &&
15273  !isa<VarTemplateSpecializationDecl>(Var))
15274  SemaRef.checkSpecializationVisibility(Loc, Var);
15275 
15276  // Perform implicit instantiation of static data members, static data member
15277  // templates of class templates, and variable template specializations. Delay
15278  // instantiations of variable templates, except for those that could be used
15279  // in a constant expression.
15280  if (NeedDefinition && isTemplateInstantiation(TSK)) {
15281  // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15282  // instantiation declaration if a variable is usable in a constant
15283  // expression (among other cases).
15284  bool TryInstantiating =
15285  TSK == TSK_ImplicitInstantiation ||
15286  (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15287 
15288  if (TryInstantiating) {
15289  SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15290  bool FirstInstantiation = PointOfInstantiation.isInvalid();
15291  if (FirstInstantiation) {
15292  PointOfInstantiation = Loc;
15293  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15294  }
15295 
15296  bool InstantiationDependent = false;
15297  bool IsNonDependent =
15299  VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15300  : true;
15301 
15302  // Do not instantiate specializations that are still type-dependent.
15303  if (IsNonDependent) {
15304  if (UsableInConstantExpr) {
15305  // Do not defer instantiations of variables that could be used in a
15306  // constant expression.
15307  SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15308  } else if (FirstInstantiation ||
15309  isa<VarTemplateSpecializationDecl>(Var)) {
15310  // FIXME: For a specialization of a variable template, we don't
15311  // distinguish between "declaration and type implicitly instantiated"
15312  // and "implicit instantiation of definition requested", so we have
15313  // no direct way to avoid enqueueing the pending instantiation
15314  // multiple times.
15315  SemaRef.PendingInstantiations
15316  .push_back(std::make_pair(Var, PointOfInstantiation));
15317  }
15318  }
15319  }
15320  }
15321 
15322  // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15323  // the requirements for appearing in a constant expression (5.19) and, if
15324  // it is an object, the lvalue-to-rvalue conversion (4.1)
15325  // is immediately applied." We check the first part here, and
15326  // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15327  // Note that we use the C++11 definition everywhere because nothing in
15328  // C++03 depends on whether we get the C++03 version correct. The second
15329  // part does not apply to references, since they are not objects.
15330  if (OdrUseContext && E &&
15331  IsVariableAConstantExpression(Var, SemaRef.Context)) {
15332  // A reference initialized by a constant expression can never be
15333  // odr-used, so simply ignore it.
15334  if (!Var->getType()->isReferenceType() ||
15335  (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15336  SemaRef.MaybeODRUseExprs.insert(E);
15337  } else if (OdrUseContext) {
15338  MarkVarDeclODRUsed(Var, Loc, SemaRef,
15339  /*MaxFunctionScopeIndex ptr*/ nullptr);
15340  } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15341  // If this is a dependent context, we don't need to mark variables as
15342  // odr-used, but we may still need to track them for lambda capture.
15343  // FIXME: Do we also need to do this inside dependent typeid expressions
15344  // (which are modeled as unevaluated at this point)?
15345  const bool RefersToEnclosingScope =
15346  (SemaRef.CurContext != Var->getDeclContext() &&
15347  Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15348  if (RefersToEnclosingScope) {
15349  LambdaScopeInfo *const LSI =
15350  SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15351  if (LSI && (!LSI->CallOperator ||
15352  !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15353  // If a variable could potentially be odr-used, defer marking it so
15354  // until we finish analyzing the full expression for any
15355  // lvalue-to-rvalue
15356  // or discarded value conversions that would obviate odr-use.
15357  // Add it to the list of potential captures that will be analyzed
15358  // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15359  // unless the variable is a reference that was initialized by a constant
15360  // expression (this will never need to be captured or odr-used).
15361  assert(E && "Capture variable should be used in an expression.");
15362  if (!Var->getType()->isReferenceType() ||
15364  LSI->addPotentialCapture(E->IgnoreParens());
15365  }
15366  }
15367  }
15368 }
15369 
15370 /// Mark a variable referenced, and check whether it is odr-used
15371 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
15372 /// used directly for normal expressions referring to VarDecl.
15374  DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15375 }
15376 
15377 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15378  Decl *D, Expr *E, bool MightBeOdrUse) {
15379  if (SemaRef.isInOpenMPDeclareTargetContext())
15380  SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15381 
15382  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15383  DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15384  return;
15385  }
15386 
15387  SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15388 
15389  // If this is a call to a method via a cast, also mark the method in the
15390  // derived class used in case codegen can devirtualize the call.
15391  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15392  if (!ME)
15393  return;
15394  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15395  if (!MD)
15396  return;
15397  // Only attempt to devirtualize if this is truly a virtual call.
15398  bool IsVirtualCall = MD->isVirtual() &&
15399  ME->performsVirtualDispatch(SemaRef.getLangOpts());
15400  if (!IsVirtualCall)
15401  return;
15402 
15403  // If it's possible to devirtualize the call, mark the called function
15404  // referenced.
15406  ME->getBase(), SemaRef.getLangOpts().AppleKext);
15407  if (DM)
15408  SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15409 }
15410 
15411 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15413  // TODO: update this with DR# once a defect report is filed.
15414  // C++11 defect. The address of a pure member should not be an ODR use, even
15415  // if it's a qualified reference.
15416  bool OdrUse = true;
15417  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15418  if (Method->isVirtual() &&
15419  !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15420  OdrUse = false;
15421  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15422 }
15423 
15424 /// Perform reference-marking and odr-use handling for a MemberExpr.
15426  // C++11 [basic.def.odr]p2:
15427  // A non-overloaded function whose name appears as a potentially-evaluated
15428  // expression or a member of a set of candidate functions, if selected by
15429  // overload resolution when referred to from a potentially-evaluated
15430  // expression, is odr-used, unless it is a pure virtual function and its
15431  // name is not explicitly qualified.
15432  bool MightBeOdrUse = true;
15433  if (E->performsVirtualDispatch(getLangOpts())) {
15434  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15435  if (Method->isPure())
15436  MightBeOdrUse = false;
15437  }
15438  SourceLocation Loc = E->getMemberLoc().isValid() ?
15439  E->getMemberLoc() : E->getLocStart();
15440  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15441 }
15442 
15443 /// Perform marking for a reference to an arbitrary declaration. It
15444 /// marks the declaration referenced, and performs odr-use checking for
15445 /// functions and variables. This method should not be used when building a
15446 /// normal expression which refers to a variable.
15448  bool MightBeOdrUse) {
15449  if (MightBeOdrUse) {
15450  if (auto *VD = dyn_cast<VarDecl>(D)) {
15451  MarkVariableReferenced(Loc, VD);
15452  return;
15453  }
15454  }
15455  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15456  MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15457  return;
15458  }
15459  D->setReferenced();
15460 }
15461 
15462 namespace {
15463  // Mark all of the declarations used by a type as referenced.
15464  // FIXME: Not fully implemented yet! We need to have a better understanding
15465  // of when we're entering a context we should not recurse into.
15466  // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15467  // TreeTransforms rebuilding the type in a new context. Rather than
15468  // duplicating the TreeTransform logic, we should consider reusing it here.
15469  // Currently that causes problems when rebuilding LambdaExprs.
15470  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15471  Sema &S;
15472  SourceLocation Loc;
15473 
15474  public:
15475  typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15476 
15477  MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15478 
15479  bool TraverseTemplateArgument(const TemplateArgument &Arg);
15480  };
15481 }
15482 
15483 bool MarkReferencedDecls::TraverseTemplateArgument(
15484  const TemplateArgument &Arg) {
15485  {
15486  // A non-type template argument is a constant-evaluated context.
15489  if (Arg.getKind() == TemplateArgument::Declaration) {
15490  if (Decl *D = Arg.getAsDecl())
15491  S.MarkAnyDeclReferenced(Loc, D, true);
15492  } else if (Arg.getKind() == TemplateArgument::Expression) {
15494  }
15495  }
15496 
15497  return Inherited::TraverseTemplateArgument(Arg);
15498 }
15499 
15501  MarkReferencedDecls Marker(*this, Loc);
15502  Marker.TraverseType(T);
15503 }
15504 
15505 namespace {
15506  /// Helper class that marks all of the declarations referenced by
15507  /// potentially-evaluated subexpressions as "referenced".
15508  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15509  Sema &S;
15510  bool SkipLocalVariables;
15511 
15512  public:
15514 
15515  EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15516  : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15517 
15518  void VisitDeclRefExpr(DeclRefExpr *E) {
15519  // If we were asked not to visit local variables, don't.
15520  if (SkipLocalVariables) {
15521  if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15522  if (VD->hasLocalStorage())
15523  return;
15524  }
15525 
15526  S.MarkDeclRefReferenced(E);
15527  }
15528 
15529  void VisitMemberExpr(MemberExpr *E) {
15530  S.MarkMemberReferenced(E);
15531  Inherited::VisitMemberExpr(E);
15532  }
15533 
15534  void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15536  const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15537  Visit(E->getSubExpr());
15538  }
15539 
15540  void VisitCXXNewExpr(CXXNewExpr *E) {
15541  if (E->getOperatorNew())
15543  if (E->getOperatorDelete())
15545  Inherited::VisitCXXNewExpr(E);
15546  }
15547 
15548  void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15549  if (E->getOperatorDelete())
15552  if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15553  CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15555  S.LookupDestructor(Record));
15556  }
15557 
15558  Inherited::VisitCXXDeleteExpr(E);
15559  }
15560 
15561  void VisitCXXConstructExpr(CXXConstructExpr *E) {
15563  Inherited::VisitCXXConstructExpr(E);
15564  }
15565 
15566  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15567  Visit(E->getExpr());
15568  }
15569 
15570  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15571  Inherited::VisitImplicitCastExpr(E);
15572 
15573  if (E->getCastKind() == CK_LValueToRValue)
15575  }
15576  };
15577 }
15578 
15579 /// Mark any declarations that appear within this expression or any
15580 /// potentially-evaluated subexpressions as "referenced".
15581 ///
15582 /// \param SkipLocalVariables If true, don't mark local variables as
15583 /// 'referenced'.
15585  bool SkipLocalVariables) {
15586  EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15587 }
15588 
15589 /// Emit a diagnostic that describes an effect on the run-time behavior
15590 /// of the program being compiled.
15591 ///
15592 /// This routine emits the given diagnostic when the code currently being
15593 /// type-checked is "potentially evaluated", meaning that there is a
15594 /// possibility that the code will actually be executable. Code in sizeof()
15595 /// expressions, code used only during overload resolution, etc., are not
15596 /// potentially evaluated. This routine will suppress such diagnostics or,
15597 /// in the absolutely nutty case of potentially potentially evaluated
15598 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15599 /// later.
15600 ///
15601 /// This routine should be used for all diagnostics that describe the run-time
15602 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15603 /// Failure to do so will likely result in spurious diagnostics or failures
15604 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15605 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15606  const PartialDiagnostic &PD) {
15607  switch (ExprEvalContexts.back().Context) {
15608  case ExpressionEvaluationContext::Unevaluated:
15609  case ExpressionEvaluationContext::UnevaluatedList:
15610  case ExpressionEvaluationContext::UnevaluatedAbstract:
15611  case ExpressionEvaluationContext::DiscardedStatement:
15612  // The argument will never be evaluated, so don't complain.
15613  break;
15614 
15615  case ExpressionEvaluationContext::ConstantEvaluated:
15616  // Relevant diagnostics should be produced by constant evaluation.
15617  break;
15618 
15619  case ExpressionEvaluationContext::PotentiallyEvaluated:
15620  case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15621  if (Statement && getCurFunctionOrMethodDecl()) {
15622  FunctionScopes.back()->PossiblyUnreachableDiags.
15623  push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15624  return true;
15625  }
15626 
15627  // The initializer of a constexpr variable or of the first declaration of a
15628  // static data member is not syntactically a constant evaluated constant,
15629  // but nonetheless is always required to be a constant expression, so we
15630  // can skip diagnosing.
15631  // FIXME: Using the mangling context here is a hack.
15632  if (auto *VD = dyn_cast_or_null<VarDecl>(
15633  ExprEvalContexts.back().ManglingContextDecl)) {
15634  if (VD->isConstexpr() ||
15635  (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15636  break;
15637  // FIXME: For any other kind of variable, we should build a CFG for its
15638  // initializer and check whether the context in question is reachable.
15639  }
15640 
15641  Diag(Loc, PD);
15642  return true;
15643  }
15644 
15645  return false;
15646 }
15647 
15649  CallExpr *CE, FunctionDecl *FD) {
15650  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15651  return false;
15652 
15653  // If we're inside a decltype's expression, don't check for a valid return
15654  // type or construct temporaries until we know whether this is the last call.
15655  if (ExprEvalContexts.back().ExprContext ==
15656  ExpressionEvaluationContextRecord::EK_Decltype) {
15657  ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15658  return false;
15659  }
15660 
15661  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15662  FunctionDecl *FD;
15663  CallExpr *CE;
15664 
15665  public:
15666  CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15667  : FD(FD), CE(CE) { }
15668 
15669  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15670  if (!FD) {
15671  S.Diag(Loc, diag::err_call_incomplete_return)
15672  << T << CE->getSourceRange();
15673  return;
15674  }
15675 
15676  S.Diag(Loc, diag::err_call_function_incomplete_return)
15677  << CE->getSourceRange() << FD->getDeclName() << T;
15678  S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15679  << FD->getDeclName();
15680  }
15681  } Diagnoser(FD, CE);
15682 
15683  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15684  return true;
15685 
15686  return false;
15687 }
15688 
15689 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15690 // will prevent this condition from triggering, which is what we want.
15692  SourceLocation Loc;
15693 
15694  unsigned diagnostic = diag::warn_condition_is_assignment;
15695  bool IsOrAssign = false;
15696 
15697  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15698  if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15699  return;
15700 
15701  IsOrAssign = Op->getOpcode() == BO_OrAssign;
15702 
15703  // Greylist some idioms by putting them into a warning subcategory.
15704  if (ObjCMessageExpr *ME
15705  = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15706  Selector Sel = ME->getSelector();
15707 
15708  // self = [<foo> init...]
15709  if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15710  diagnostic = diag::warn_condition_is_idiomatic_assignment;
15711 
15712  // <foo> = [<bar> nextObject]
15713  else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15714  diagnostic = diag::warn_condition_is_idiomatic_assignment;
15715  }
15716 
15717  Loc = Op->getOperatorLoc();
15718  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15719  if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15720  return;
15721 
15722  IsOrAssign = Op->getOperator() == OO_PipeEqual;
15723  Loc = Op->getOperatorLoc();
15724  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15725  return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15726  else {
15727  // Not an assignment.
15728  return;
15729  }
15730 
15731  Diag(Loc, diagnostic) << E->getSourceRange();
15732 
15734  SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15735  Diag(Loc, diag::note_condition_assign_silence)
15736  << FixItHint::CreateInsertion(Open, "(")
15737  << FixItHint::CreateInsertion(Close, ")");
15738 
15739  if (IsOrAssign)
15740  Diag(Loc, diag::note_condition_or_assign_to_comparison)
15741  << FixItHint::CreateReplacement(Loc, "!=");
15742  else
15743  Diag(Loc, diag::note_condition_assign_to_comparison)
15744  << FixItHint::CreateReplacement(Loc, "==");
15745 }
15746 
15747 /// Redundant parentheses over an equality comparison can indicate
15748 /// that the user intended an assignment used as condition.
15750  // Don't warn if the parens came from a macro.
15751  SourceLocation parenLoc = ParenE->getLocStart();
15752  if (parenLoc.isInvalid() || parenLoc.isMacroID())
15753  return;
15754  // Don't warn for dependent expressions.
15755  if (ParenE->isTypeDependent())
15756  return;
15757 
15758  Expr *E = ParenE->IgnoreParens();
15759 
15760  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15761  if (opE->getOpcode() == BO_EQ &&
15762  opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15763  == Expr::MLV_Valid) {
15764  SourceLocation Loc = opE->getOperatorLoc();
15765 
15766  Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15767  SourceRange ParenERange = ParenE->getSourceRange();
15768  Diag(Loc, diag::note_equality_comparison_silence)
15769  << FixItHint::CreateRemoval(ParenERange.getBegin())
15770  << FixItHint::CreateRemoval(ParenERange.getEnd());
15771  Diag(Loc, diag::note_equality_comparison_to_assign)
15772  << FixItHint::CreateReplacement(Loc, "=");
15773  }
15774 }
15775 
15777  bool IsConstexpr) {
15778  DiagnoseAssignmentAsCondition(E);
15779  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15780  DiagnoseEqualityWithExtraParens(parenE);
15781 
15782  ExprResult result = CheckPlaceholderExpr(E);
15783  if (result.isInvalid()) return ExprError();
15784  E = result.get();
15785 
15786  if (!E->isTypeDependent()) {
15787  if (getLangOpts().CPlusPlus)
15788  return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15789 
15790  ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15791  if (ERes.isInvalid())
15792  return ExprError();
15793  E = ERes.get();
15794 
15795  QualType T = E->getType();
15796  if (!T->isScalarType()) { // C99 6.8.4.1p1
15797  Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15798  << T << E->getSourceRange();
15799  return ExprError();
15800  }
15801  CheckBoolLikeConversion(E, Loc);
15802  }
15803 
15804  return E;
15805 }
15806 
15808  Expr *SubExpr, ConditionKind CK) {
15809  // Empty conditions are valid in for-statements.
15810  if (!SubExpr)
15811  return ConditionResult();
15812 
15813  ExprResult Cond;
15814  switch (CK) {
15815  case ConditionKind::Boolean:
15816  Cond = CheckBooleanCondition(Loc, SubExpr);
15817  break;
15818 
15819  case ConditionKind::ConstexprIf:
15820  Cond = CheckBooleanCondition(Loc, SubExpr, true);
15821  break;
15822 
15823  case ConditionKind::Switch:
15824  Cond = CheckSwitchCondition(Loc, SubExpr);
15825  break;
15826  }
15827  if (Cond.isInvalid())
15828  return ConditionError();
15829 
15830  // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15831  FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15832  if (!FullExpr.get())
15833  return ConditionError();
15834 
15835  return ConditionResult(*this, nullptr, FullExpr,
15836  CK == ConditionKind::ConstexprIf);
15837 }
15838 
15839 namespace {
15840  /// A visitor for rebuilding a call to an __unknown_any expression
15841  /// to have an appropriate type.
15842  struct RebuildUnknownAnyFunction
15843  : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15844 
15845  Sema &S;
15846 
15847  RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15848 
15849  ExprResult VisitStmt(Stmt *S) {
15850  llvm_unreachable("unexpected statement!");
15851  }
15852 
15853  ExprResult VisitExpr(Expr *E) {
15854  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15855  << E->getSourceRange();
15856  return ExprError();
15857  }
15858 
15859  /// Rebuild an expression which simply semantically wraps another
15860  /// expression which it shares the type and value kind of.
15861  template <class T> ExprResult rebuildSugarExpr(T *E) {
15862  ExprResult SubResult = Visit(E->getSubExpr());
15863  if (SubResult.isInvalid()) return ExprError();
15864 
15865  Expr *SubExpr = SubResult.get();
15866  E->setSubExpr(SubExpr);
15867  E->setType(SubExpr->getType());
15868  E->setValueKind(SubExpr->getValueKind());
15869  assert(E->getObjectKind() == OK_Ordinary);
15870  return E;
15871  }
15872 
15873  ExprResult VisitParenExpr(ParenExpr *E) {
15874  return rebuildSugarExpr(E);
15875  }
15876 
15877  ExprResult VisitUnaryExtension(UnaryOperator *E) {
15878  return rebuildSugarExpr(E);
15879  }
15880 
15881  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15882  ExprResult SubResult = Visit(E->getSubExpr());
15883  if (SubResult.isInvalid()) return ExprError();
15884 
15885  Expr *SubExpr = SubResult.get();
15886  E->setSubExpr(SubExpr);
15887  E->setType(S.Context.getPointerType(SubExpr->getType()));
15888  assert(E->getValueKind() == VK_RValue);
15889  assert(E->getObjectKind() == OK_Ordinary);
15890  return E;
15891  }
15892 
15893  ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15894  if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15895 
15896  E->setType(VD->getType());
15897 
15898  assert(E->getValueKind() == VK_RValue);
15899  if (S.getLangOpts().CPlusPlus &&
15900  !(isa<CXXMethodDecl>(VD) &&
15901  cast<CXXMethodDecl>(VD)->isInstance()))
15902  E->setValueKind(VK_LValue);
15903 
15904  return E;
15905  }
15906 
15907  ExprResult VisitMemberExpr(MemberExpr *E) {
15908  return resolveDecl(E, E->getMemberDecl());
15909  }
15910 
15911  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15912  return resolveDecl(E, E->getDecl());
15913  }
15914  };
15915 }
15916 
15917 /// Given a function expression of unknown-any type, try to rebuild it
15918 /// to have a function type.
15919 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15920  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15921  if (Result.isInvalid()) return ExprError();
15922  return S.DefaultFunctionArrayConversion(Result.get());
15923 }
15924 
15925 namespace {
15926  /// A visitor for rebuilding an expression of type __unknown_anytype
15927  /// into one which resolves the type directly on the referring
15928  /// expression. Strict preservation of the original source
15929  /// structure is not a goal.
15930  struct RebuildUnknownAnyExpr
15931  : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15932 
15933  Sema &S;
15934 
15935  /// The current destination type.
15936  QualType DestType;
15937 
15938  RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15939  : S(S), DestType(CastType) {}
15940 
15941  ExprResult VisitStmt(Stmt *S) {
15942  llvm_unreachable("unexpected statement!");
15943  }
15944 
15945  ExprResult VisitExpr(Expr *E) {
15946  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15947  << E->getSourceRange();
15948  return ExprError();
15949  }
15950 
15951  ExprResult VisitCallExpr(CallExpr *E);
15952  ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15953 
15954  /// Rebuild an expression which simply semantically wraps another
15955  /// expression which it shares the type and value kind of.
15956  template <class T> ExprResult rebuildSugarExpr(T *E) {
15957  ExprResult SubResult = Visit(E->getSubExpr());
15958  if (SubResult.isInvalid()) return ExprError();
15959  Expr *SubExpr = SubResult.get();
15960  E->setSubExpr(SubExpr);
15961  E->setType(SubExpr->getType());
15962  E->setValueKind(SubExpr->getValueKind());
15963  assert(E->getObjectKind() == OK_Ordinary);
15964  return E;
15965  }
15966 
15967  ExprResult VisitParenExpr(ParenExpr *E) {
15968  return rebuildSugarExpr(E);
15969  }
15970 
15971  ExprResult VisitUnaryExtension(UnaryOperator *E) {
15972  return rebuildSugarExpr(E);
15973  }
15974 
15975  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15976  const PointerType *Ptr = DestType->getAs<PointerType>();
15977  if (!Ptr) {
15978  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15979  << E->getSourceRange();
15980  return ExprError();
15981  }
15982 
15983  if (isa<CallExpr>(E->getSubExpr())) {
15984  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15985  << E->getSourceRange();
15986  return ExprError();
15987  }
15988 
15989  assert(E->getValueKind() == VK_RValue);
15990  assert(E->getObjectKind() == OK_Ordinary);
15991  E->setType(DestType);
15992 
15993  // Build the sub-expression as if it were an object of the pointee type.
15994  DestType = Ptr->getPointeeType();
15995  ExprResult SubResult = Visit(E->getSubExpr());
15996  if (SubResult.isInvalid()) return ExprError();
15997  E->setSubExpr(SubResult.get());
15998  return E;
15999  }
16000 
16001  ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16002 
16003  ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16004 
16005  ExprResult VisitMemberExpr(MemberExpr *E) {
16006  return resolveDecl(E, E->getMemberDecl());
16007  }
16008 
16009  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16010  return resolveDecl(E, E->getDecl());
16011  }
16012  };
16013 }
16014 
16015 /// Rebuilds a call expression which yielded __unknown_anytype.
16016 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16017  Expr *CalleeExpr = E->getCallee();
16018 
16019  enum FnKind {
16020  FK_MemberFunction,
16021  FK_FunctionPointer,
16022  FK_BlockPointer
16023  };
16024 
16025  FnKind Kind;
16026  QualType CalleeType = CalleeExpr->getType();
16027  if (CalleeType == S.Context.BoundMemberTy) {
16028  assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16029  Kind = FK_MemberFunction;
16030  CalleeType = Expr::findBoundMemberType(CalleeExpr);
16031  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16032  CalleeType = Ptr->getPointeeType();
16033  Kind = FK_FunctionPointer;
16034  } else {
16035  CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16036  Kind = FK_BlockPointer;
16037  }
16038  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16039 
16040  // Verify that this is a legal result type of a function.
16041  if (DestType->isArrayType() || DestType->isFunctionType()) {
16042  unsigned diagID = diag::err_func_returning_array_function;
16043  if (Kind == FK_BlockPointer)
16044  diagID = diag::err_block_returning_array_function;
16045 
16046  S.Diag(E->getExprLoc(), diagID)
16047  << DestType->isFunctionType() << DestType;
16048  return ExprError();
16049  }
16050 
16051  // Otherwise, go ahead and set DestType as the call's result.
16052  E->setType(DestType.getNonLValueExprType(S.Context));
16054  assert(E->getObjectKind() == OK_Ordinary);
16055 
16056  // Rebuild the function type, replacing the result type with DestType.
16057  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16058  if (Proto) {
16059  // __unknown_anytype(...) is a special case used by the debugger when
16060  // it has no idea what a function's signature is.
16061  //
16062  // We want to build this call essentially under the K&R
16063  // unprototyped rules, but making a FunctionNoProtoType in C++
16064  // would foul up all sorts of assumptions. However, we cannot
16065  // simply pass all arguments as variadic arguments, nor can we
16066  // portably just call the function under a non-variadic type; see
16067  // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16068  // However, it turns out that in practice it is generally safe to
16069  // call a function declared as "A foo(B,C,D);" under the prototype
16070  // "A foo(B,C,D,...);". The only known exception is with the
16071  // Windows ABI, where any variadic function is implicitly cdecl
16072  // regardless of its normal CC. Therefore we change the parameter
16073  // types to match the types of the arguments.
16074  //
16075  // This is a hack, but it is far superior to moving the
16076  // corresponding target-specific code from IR-gen to Sema/AST.
16077 
16078  ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16079  SmallVector<QualType, 8> ArgTypes;
16080  if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16081  ArgTypes.reserve(E->getNumArgs());
16082  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16083  Expr *Arg = E->getArg(i);
16084  QualType ArgType = Arg->getType();
16085  if (E->isLValue()) {
16086  ArgType = S.Context.getLValueReferenceType(ArgType);
16087  } else if (E->isXValue()) {
16088  ArgType = S.Context.getRValueReferenceType(ArgType);
16089  }
16090  ArgTypes.push_back(ArgType);
16091  }
16092  ParamTypes = ArgTypes;
16093  }
16094  DestType = S.Context.getFunctionType(DestType, ParamTypes,
16095  Proto->getExtProtoInfo());
16096  } else {
16097  DestType = S.Context.getFunctionNoProtoType(DestType,
16098  FnType->getExtInfo());
16099  }
16100 
16101  // Rebuild the appropriate pointer-to-function type.
16102  switch (Kind) {
16103  case FK_MemberFunction:
16104  // Nothing to do.
16105  break;
16106 
16107  case FK_FunctionPointer:
16108  DestType = S.Context.getPointerType(DestType);
16109  break;
16110 
16111  case FK_BlockPointer:
16112  DestType = S.Context.getBlockPointerType(DestType);
16113  break;
16114  }
16115 
16116  // Finally, we can recurse.
16117  ExprResult CalleeResult = Visit(CalleeExpr);
16118  if (!CalleeResult.isUsable()) return ExprError();
16119  E->setCallee(CalleeResult.get());
16120 
16121  // Bind a temporary if necessary.
16122  return S.MaybeBindToTemporary(E);
16123 }
16124 
16125 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16126  // Verify that this is a legal result type of a call.
16127  if (DestType->isArrayType() || DestType->isFunctionType()) {
16128  S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16129  << DestType->isFunctionType() << DestType;
16130  return ExprError();
16131  }
16132 
16133  // Rewrite the method result type if available.
16134  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16135  assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16136  Method->setReturnType(DestType);
16137  }
16138 
16139  // Change the type of the message.
16140  E->setType(DestType.getNonReferenceType());
16142 
16143  return S.MaybeBindToTemporary(E);
16144 }
16145 
16146 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16147  // The only case we should ever see here is a function-to-pointer decay.
16148  if (E->getCastKind() == CK_FunctionToPointerDecay) {
16149  assert(E->getValueKind() == VK_RValue);
16150  assert(E->getObjectKind() == OK_Ordinary);
16151 
16152  E->setType(DestType);
16153 
16154  // Rebuild the sub-expression as the pointee (function) type.
16155  DestType = DestType->castAs<PointerType>()->getPointeeType();
16156 
16157  ExprResult Result = Visit(E->getSubExpr());
16158  if (!Result.isUsable()) return ExprError();
16159 
16160  E->setSubExpr(Result.get());
16161  return E;
16162  } else if (E->getCastKind() == CK_LValueToRValue) {
16163  assert(E->getValueKind() == VK_RValue);
16164  assert(E->getObjectKind() == OK_Ordinary);
16165 
16166  assert(isa<BlockPointerType>(E->getType()));
16167 
16168  E->setType(DestType);
16169 
16170  // The sub-expression has to be a lvalue reference, so rebuild it as such.
16171  DestType = S.Context.getLValueReferenceType(DestType);
16172 
16173  ExprResult Result = Visit(E->getSubExpr());
16174  if (!Result.isUsable()) return ExprError();
16175 
16176  E->setSubExpr(Result.get());
16177  return E;
16178  } else {
16179  llvm_unreachable("Unhandled cast type!");
16180  }
16181 }
16182 
16183 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16184  ExprValueKind ValueKind = VK_LValue;
16185  QualType Type = DestType;
16186 
16187  // We know how to make this work for certain kinds of decls:
16188 
16189  // - functions
16190  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16191  if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16192  DestType = Ptr->getPointeeType();
16193  ExprResult Result = resolveDecl(E, VD);
16194  if (Result.isInvalid()) return ExprError();
16195  return S.ImpCastExprToType(Result.get(), Type,
16196  CK_FunctionToPointerDecay, VK_RValue);
16197  }
16198 
16199  if (!Type->isFunctionType()) {
16200  S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16201  << VD << E->getSourceRange();
16202  return ExprError();
16203  }
16204  if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16205  // We must match the FunctionDecl's type to the hack introduced in
16206  // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16207  // type. See the lengthy commentary in that routine.
16208  QualType FDT = FD->getType();
16209  const FunctionType *FnType = FDT->castAs<FunctionType>();
16210  const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16211  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16212  if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16213  SourceLocation Loc = FD->getLocation();
16214  FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16215  FD->getDeclContext(),
16216  Loc, Loc, FD->getNameInfo().getName(),
16217  DestType, FD->getTypeSourceInfo(),
16218  SC_None, false/*isInlineSpecified*/,
16219  FD->hasPrototype(),
16220  false/*isConstexprSpecified*/);
16221 
16222  if (FD->getQualifier())
16223  NewFD->setQualifierInfo(FD->getQualifierLoc());
16224 
16226  for (const auto &AI : FT->param_types()) {
16227  ParmVarDecl *Param =
16228  S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16229  Param->setScopeInfo(0, Params.size());
16230  Params.push_back(Param);
16231  }
16232  NewFD->setParams(Params);
16233  DRE->setDecl(NewFD);
16234  VD = DRE->getDecl();
16235  }
16236  }
16237 
16238  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16239  if (MD->isInstance()) {
16240  ValueKind = VK_RValue;
16241  Type = S.Context.BoundMemberTy;
16242  }
16243 
16244  // Function references aren't l-values in C.
16245  if (!S.getLangOpts().CPlusPlus)
16246  ValueKind = VK_RValue;
16247 
16248  // - variables
16249  } else if (isa<VarDecl>(VD)) {
16250  if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16251  Type = RefTy->getPointeeType();
16252  } else if (Type->isFunctionType()) {
16253  S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16254  << VD << E->getSourceRange();
16255  return ExprError();
16256  }
16257 
16258  // - nothing else
16259  } else {
16260  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16261  << VD << E->getSourceRange();
16262  return ExprError();
16263  }
16264 
16265  // Modifying the declaration like this is friendly to IR-gen but
16266  // also really dangerous.
16267  VD->setType(DestType);
16268  E->setType(Type);
16269  E->setValueKind(ValueKind);
16270  return E;
16271 }
16272 
16273 /// Check a cast of an unknown-any type. We intentionally only
16274 /// trigger this for C-style casts.
16277  ExprValueKind &VK, CXXCastPath &Path) {
16278  // The type we're casting to must be either void or complete.
16279  if (!CastType->isVoidType() &&
16280  RequireCompleteType(TypeRange.getBegin(), CastType,
16281  diag::err_typecheck_cast_to_incomplete))
16282  return ExprError();
16283 
16284  // Rewrite the casted expression from scratch.
16285  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16286  if (!result.isUsable()) return ExprError();
16287 
16288  CastExpr = result.get();
16289  VK = CastExpr->getValueKind();
16290  CastKind = CK_NoOp;
16291 
16292  return CastExpr;
16293 }
16294 
16296  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16297 }
16298 
16300  Expr *arg, QualType &paramType) {
16301  // If the syntactic form of the argument is not an explicit cast of
16302  // any sort, just do default argument promotion.
16303  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16304  if (!castArg) {
16305  ExprResult result = DefaultArgumentPromotion(arg);
16306  if (result.isInvalid()) return ExprError();
16307  paramType = result.get()->getType();
16308  return result;
16309  }
16310 
16311  // Otherwise, use the type that was written in the explicit cast.
16312  assert(!arg->hasPlaceholderType());
16313  paramType = castArg->getTypeAsWritten();
16314 
16315  // Copy-initialize a parameter of that type.
16316  InitializedEntity entity =
16317  InitializedEntity::InitializeParameter(Context, paramType,
16318  /*consumed*/ false);
16319  return PerformCopyInitialization(entity, callLoc, arg);
16320 }
16321 
16323  Expr *orig = E;
16324  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16325  while (true) {
16326  E = E->IgnoreParenImpCasts();
16327  if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16328  E = call->getCallee();
16329  diagID = diag::err_uncasted_call_of_unknown_any;
16330  } else {
16331  break;
16332  }
16333  }
16334 
16335  SourceLocation loc;
16336  NamedDecl *d;
16337  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16338  loc = ref->getLocation();
16339  d = ref->getDecl();
16340  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16341  loc = mem->getMemberLoc();
16342  d = mem->getMemberDecl();
16343  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16344  diagID = diag::err_uncasted_call_of_unknown_any;
16345  loc = msg->getSelectorStartLoc();
16346  d = msg->getMethodDecl();
16347  if (!d) {
16348  S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16349  << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16350  << orig->getSourceRange();
16351  return ExprError();
16352  }
16353  } else {
16354  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16355  << E->getSourceRange();
16356  return ExprError();
16357  }
16358 
16359  S.Diag(loc, diagID) << d << orig->getSourceRange();
16360 
16361  // Never recoverable.
16362  return ExprError();
16363 }
16364 
16365 /// Check for operands with placeholder types and complain if found.
16366 /// Returns ExprError() if there was an error and no recovery was possible.
16368  if (!getLangOpts().CPlusPlus) {
16369  // C cannot handle TypoExpr nodes on either side of a binop because it
16370  // doesn't handle dependent types properly, so make sure any TypoExprs have
16371  // been dealt with before checking the operands.
16372  ExprResult Result = CorrectDelayedTyposInExpr(E);
16373  if (!Result.isUsable()) return ExprError();
16374  E = Result.get();
16375  }
16376 
16377  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16378  if (!placeholderType) return E;
16379 
16380  switch (placeholderType->getKind()) {
16381 
16382  // Overloaded expressions.
16383  case BuiltinType::Overload: {
16384  // Try to resolve a single function template specialization.
16385  // This is obligatory.
16386  ExprResult Result = E;
16387  if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16388  return Result;
16389 
16390  // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16391  // leaves Result unchanged on failure.
16392  Result = E;
16393  if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16394  return Result;
16395 
16396  // If that failed, try to recover with a call.
16397  tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16398  /*complain*/ true);
16399  return Result;
16400  }
16401 
16402  // Bound member functions.
16403  case BuiltinType::BoundMember: {
16404  ExprResult result = E;
16405  const Expr *BME = E->IgnoreParens();
16406  PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16407  // Try to give a nicer diagnostic if it is a bound member that we recognize.
16408  if (isa<CXXPseudoDestructorExpr>(BME)) {
16409  PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16410  } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16411  if (ME->getMemberNameInfo().getName().getNameKind() ==
16413  PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16414  }
16415  tryToRecoverWithCall(result, PD,
16416  /*complain*/ true);
16417  return result;
16418  }
16419 
16420  // ARC unbridged casts.
16421  case BuiltinType::ARCUnbridgedCast: {
16422  Expr *realCast = stripARCUnbridgedCast(E);
16423  diagnoseARCUnbridgedCast(realCast);
16424  return realCast;
16425  }
16426 
16427  // Expressions of unknown type.
16428  case BuiltinType::UnknownAny:
16429  return diagnoseUnknownAnyExpr(*this, E);
16430 
16431  // Pseudo-objects.
16432  case BuiltinType::PseudoObject:
16433  return checkPseudoObjectRValue(E);
16434 
16435  case BuiltinType::BuiltinFn: {
16436  // Accept __noop without parens by implicitly converting it to a call expr.
16437  auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16438  if (DRE) {
16439  auto *FD = cast<FunctionDecl>(DRE->getDecl());
16440  if (FD->getBuiltinID() == Builtin::BI__noop) {
16441  E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16442  CK_BuiltinFnToFnPtr).get();
16443  return new (Context) CallExpr(Context, E, None, Context.IntTy,
16445  }
16446  }
16447 
16448  Diag(E->getLocStart(), diag::err_builtin_fn_use);
16449  return ExprError();
16450  }
16451 
16452  // Expressions of unknown type.
16453  case BuiltinType::OMPArraySection:
16454  Diag(E->getLocStart(), diag::err_omp_array_section_use);
16455  return ExprError();
16456 
16457  // Everything else should be impossible.
16458 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16459  case BuiltinType::Id:
16460 #include "clang/Basic/OpenCLImageTypes.def"
16461 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16462 #define PLACEHOLDER_TYPE(Id, SingletonId)
16463 #include "clang/AST/BuiltinTypes.def"
16464  break;
16465  }
16466 
16467  llvm_unreachable("invalid placeholder type!");
16468 }
16469 
16471  if (E->isTypeDependent())
16472  return true;
16473  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16474  return E->getType()->isIntegralOrEnumerationType();
16475  return false;
16476 }
16477 
16478 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16479 ExprResult
16481  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16482  "Unknown Objective-C Boolean value!");
16483  QualType BoolT = Context.ObjCBuiltinBoolTy;
16484  if (!Context.getBOOLDecl()) {
16485  LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16487  if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16488  NamedDecl *ND = Result.getFoundDecl();
16489  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16490  Context.setBOOLDecl(TD);
16491  }
16492  }
16493  if (Context.getBOOLDecl())
16494  BoolT = Context.getBOOLType();
16495  return new (Context)
16496  ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16497 }
16498 
16501  SourceLocation RParen) {
16502 
16503  StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16504 
16505  auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16506  [&](const AvailabilitySpec &Spec) {
16507  return Spec.getPlatform() == Platform;
16508  });
16509 
16510  VersionTuple Version;
16511  if (Spec != AvailSpecs.end())
16512  Version = Spec->getVersion();
16513 
16514  // The use of `@available` in the enclosing function should be analyzed to
16515  // warn when it's used inappropriately (i.e. not if(@available)).
16516  if (getCurFunctionOrMethodDecl())
16517  getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16518  else if (getCurBlock() || getCurLambda())
16519  getCurFunction()->HasPotentialAvailabilityViolations = true;
16520 
16521  return new (Context)
16522  ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16523 }
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1484
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:8781
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:1272
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:1544
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:12242
CXXRecordDecl * getNamingClass() const
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1297
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:5065
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1556
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2245
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:15584
VariadicCallType
Definition: Sema.h:9368
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1568
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.
static std::string ComputeName(IdentType IT, const Decl *CurrentDecl)
Definition: Expr.cpp:497
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:15807
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1224
bool isClassMethod() const
Definition: DeclObjC.h:459
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:12598
CanQualType LongLongTy
Definition: ASTContext.h:1013
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void setImplicit(bool I=true)
Definition: DeclBase.h:555
void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt)
Definition: SemaInternal.h:70
Represents a function declaration or definition.
Definition: Decl.h:1716
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:14520
Stmt * body_back()
Definition: Stmt.h:652
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2376
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.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:6150
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Definition: Lookup.h:256
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:141
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:747
bool isSignedOverflowDefined() const
Definition: LangOptions.h:228
CanQualType AccumTy
Definition: ASTContext.h:1017
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
void setKind(UnqualifiedIdKind kind)
Definition: DeclSpec.h:1005
unsigned char getFixedPointIBits(QualType Ty) const
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1834
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
A class which contains all the information about a particular captured value.
Definition: Decl.h:3864
PtrTy get() const
Definition: Ownership.h:81
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:14150
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2393
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
QualType getPointeeType() const
Definition: Type.h:2406
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3191
A (possibly-)qualified type.
Definition: Type.h:655
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:6121
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:6422
Simple class containing the result of Sema::CorrectTypo.
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType)
Definition: SemaExpr.cpp:11102
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:2104
bool isArrayType() const
Definition: Type.h:6162
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:410
bool isMemberPointerType() const
Definition: Type.h:6144
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2596
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter&#39;s...
Definition: Overload.h:79
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:6819
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2331
unsigned char getFixedPointScale(QualType Ty) const
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2385
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:3982
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:11842
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1098
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2833
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:228
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:8765
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1889
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:7283
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:380
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:1174
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3153
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:1003
static CXXDependentScopeMemberExpr * Create(const ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1162
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:6001
CanQualType FractTy
Definition: ASTContext.h:1020
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C...
Definition: Type.h:6069
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3016
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:6323
CanQualType Char32Ty
Definition: ASTContext.h:1012
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:6409
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:16322
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:246
static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, QualType FieldType, QualType DeclRefType, SourceLocation Loc, bool RefersToCapturedVariable)
Create a field within the lambda class for the variable being captured.
Definition: SemaExpr.cpp:14820
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 UnresolvedLookupExpr * Create(const ASTContext &C, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool ADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.h:2869
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3016
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:219
bool isArithmeticType() const
Definition: Type.cpp:1956
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:2373
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:285
Kind getKind() const
Definition: Type.h:2274
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3211
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:497
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1941
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:633
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:114
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:10682
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:472
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4169
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:2974
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.
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:824
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4675
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2090
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:114
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:87
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:9619
bool isAscii() const
Definition: Expr.h:1676
bool isRecordType() const
Definition: Type.h:6186
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Definition: SemaExpr.cpp:8208
Expr * getBase() const
Definition: Expr.h:2590
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentType IT)
Definition: SemaExpr.cpp:3028
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:11057
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6327
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:1918
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:2853
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1281
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:8706
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:591
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:6333
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:13281
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isVariadic() const
Definition: Type.h:3774
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:2130
bool isVirtual() const
Definition: DeclCXX.h:2090
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2015
bool isExtVectorType() const
Definition: Type.h:6202
void setType(QualType t)
Definition: Expr.h:129
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:7607
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:9428
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:2824
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:10696
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3184
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:806
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:6620
Not a narrowing conversion.
Definition: Overload.h:205
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3610
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:711
bool isCopyCapture() const
Definition: ScopeInfo.h:552
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1751
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:6062
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:3848
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:16295
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4390
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1035
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2718
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13529
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:1428
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanQualType LongTy
Definition: ASTContext.h:1013
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:9378
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9096
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:2668
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:64
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1292
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:395
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:234
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
QualType withConst() const
Definition: Type.h:827
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:9477
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr *> Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:5488
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3373
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:679
TemplateNameKind Kind
The kind of template that Template refers to.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
A container of type source information.
Definition: Decl.h:86
static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:947
QualType getLogicalOperationType() const
The result type of logical operations, &#39;<&#39;, &#39;>&#39;, &#39;!=&#39;, etc.
Definition: ASTContext.h:1770
Floating point control options.
Definition: LangOptions.h:263
constexpr XRayInstrMask Function
Definition: XRayInstr.h:39
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:1729
MS property subscript expression.
Definition: ExprCXX.h:834
static StringLiteral * Create(const ASTContext &C, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumStrs)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:888
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2651
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10536
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:10935
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1209
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1232
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition: Decl.cpp:3292
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:9880
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:6759
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2477
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:4555
CanQualType WideCharTy
Definition: ASTContext.h:1008
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr *> Args)
Definition: SemaExpr.cpp:4723
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:14307
size_t param_size() const
Definition: Decl.h:2247
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:12819
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:269
CanQualType HalfTy
Definition: ASTContext.h:1028
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:13644
QualType getElementType() const
Definition: Type.h:2703
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:532
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:13027
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:96
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:1888
This file provides some common utility functions for processing Lambda related AST Constructs...
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:6062
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:9531
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:572
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:2651
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10734
Represents a variable declaration or definition.
Definition: Decl.h:814
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
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:988
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:241
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1752
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC &#39;id&#39; type.
Definition: ExprObjC.h:1460
void removeObjCLifetime()
Definition: Type.h:349
QualType getReturnType() const
Definition: Decl.h:2271
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2752
bool isParamConsumed(unsigned I) const
Definition: Type.h:3857
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:9508
unsigned getNumParams() const
Definition: Type.h:3668
bool isEnumeralType() const
Definition: Type.h:6190
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
QualType getCXXNameType() const
getCXXNameType - If this name is one of the C++ names (of a constructor, destructor, or conversion function), return the type associated with that name.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6526
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:6466
CanQualType Float128Ty
Definition: ASTContext.h:1016
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3551
CanQualType ShortAccumTy
Definition: ASTContext.h:1017
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD)
Retrieve the message suffix that should be added to a diagnostic complaining about the given function...
Definition: SemaExpr.cpp:306
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, const 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:5124
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:8310
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:139
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:431
bool isAmbiguous() const
Definition: Lookup.h:290
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:741
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
static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
If two different enums are compared, raise a warning.
Definition: SemaExpr.cpp:9437
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:925
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:12941
bool isInvalidDecl() const
Definition: DeclBase.h:549
bool isOverloaded() const
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:170
static InitializationKind CreateDirectList(SourceLocation InitLoc)
CanQualType ShortFractTy
Definition: ASTContext.h:1020
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
Definition: SemaExpr.cpp:12856
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:14939
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3092
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:10754
std::vector< FixItHint > Hints
The list of Hints generated so far.
Represents a parameter to a function.
Definition: Decl.h:1535
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
Defines the clang::Expr interface and subclasses for C++ expressions.
tok::TokenKind getKind() const
Definition: Token.h:90
bool isAdditiveOp() const
Definition: Expr.h:3222
bool isEqualityOp() const
Definition: Expr.h:3233
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2021
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:8993
The collection of all-type qualifiers we support.
Definition: Type.h:154
bool isVariableArrayType() const
Definition: Type.h:6174
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:1934
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1356
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5304
bool isXValue() const
Definition: Expr.h:251
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3118
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:15500
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:875
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:3016
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:7567
Represents a struct/union/class.
Definition: Decl.h:3570
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:6705
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:6969
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:340
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:416
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:974
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:662
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4127
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1110
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:370
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3552
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:838
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1010
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:1179
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations. ...
Definition: Decl.cpp:1797
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:11988
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:200
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:5355
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:132
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:330
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:7202
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema &S)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:14759
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:150
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:7478
ExprResult ExprEmpty()
Definition: Ownership.h:289
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:8816
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3675
LineState State
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3958
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
ObjCMethodFamily
A family of Objective-C methods.
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3315
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
Definition: SemaExpr.cpp:7392
bool isCharType() const
Definition: Type.cpp:1791
field_range fields() const
Definition: Decl.h:3786
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
bool isObjCIdType() const
Definition: Type.h:6239
Represents a member of a struct/union/class.
Definition: Decl.h:2534
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:1870
Identity conversion (no conversion)
Definition: Overload.h:81
void setNumArgs(const ASTContext &C, unsigned NumArgs)
setNumArgs - This changes the number of arguments present in this call.
Definition: Expr.cpp:1286
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:97
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:231
CanQualType LongAccumTy
Definition: ASTContext.h:1017
Floating point conversions (C++ [conv.double].
Definition: Overload.h:111
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:3918
bool isReferenceType() const
Definition: Type.h:6125
SourceLocation getLocEnd() const LLVM_READONLY
Definition: ExprObjC.h:579
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2395
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:15749
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:476
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:855
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)
Definition: Expr.cpp:391
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:9456
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:8731
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6307
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1463
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3539
bool isNull() const
Definition: Diagnostic.h:86
void setKind(tok::TokenKind K)
Definition: Token.h:91
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1877
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:4988
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:16480
LookupResultKind getResultKind() const
Definition: Lookup.h:310
Expr * getSubExpr()
Definition: Expr.h:2892
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:6833
bool isObjCQualifiedClassType() const
Definition: Type.h:6233
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:419
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:14168
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
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:6043
bool isAssignmentOp() const
Definition: Expr.h:3271
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6440
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:56
IdentifierTable & Idents
Definition: ASTContext.h:545
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:93
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
bool isInvalidType() const
Definition: DeclSpec.h:2432
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
Values of this type can be null.
bool isUnarySelector() const
CanQualType LongFractTy
Definition: ASTContext.h:1020
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:62
DeclClass * getAsSingle() const
Definition: Lookup.h:496
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:2416
StringRef getOpcodeStr() const
Definition: Expr.h:3205
SourceLocation getOpLoc() const
Definition: ExprObjC.h:582
static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:6372
bool isGLValue() const
Definition: Expr.h:252
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:940
Describes an C or C++ initializer list.
Definition: Expr.h:4050
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
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:5007
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:10732
bool isArrow() const
Definition: ExprObjC.h:567
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:13410
bool isThisCapture() const
Definition: ScopeInfo.h:544
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:3563
BinaryOperatorKind
Expr * getInitExpr() const
Definition: ScopeInfo.h:596
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:922
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:774
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:53
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:9909
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2612
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:558
unsigned getLength() const
Definition: Expr.h:1666
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:522
Represents the results of name lookup.
Definition: Lookup.h:47
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:6650
PtrTy get() const
Definition: Ownership.h:174
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:640
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:8347
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:437
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:2662
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2197
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:6307
static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:14566
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:13253
QualType getOriginalType() const
Definition: Decl.cpp:2510
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1199
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
A convenient class for passing around template argument information.
Definition: TemplateBase.h:552
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
uint32_t Offset
Definition: CacheTokens.cpp:43
const FormatToken & Tok
bool hasAddressSpace() const
Definition: Type.h:368
LabelDecl * getDecl() const
Definition: Stmt.h:892
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:6575
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:7601
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 ==.
SourceLocation getTemplateKeywordLoc() const
Gets the location of the template keyword, if present.
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2078
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:119
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
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...
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:5194
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:15412
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:1982
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:704
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:2406
Represents a declaration of a type.
Definition: Decl.h:2829
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3143
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5959
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:754
CanQualType PseudoObjectTy
Definition: ASTContext.h:1035
LangAS getAddressSpace() const
Definition: Type.h:369
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:6555
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:241
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:16499
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:211
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:1634
CanQualType LongDoubleTy
Definition: ASTContext.h:1016
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2544
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:15153
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:71
Expr * getSizeExpr() const
Definition: Type.h:2847
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:7154
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5889
TypedefDecl * getBOOLDecl() const
Retrieve declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1865
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3581
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:730
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1161
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1645
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:5444
bool isInt() const
Definition: APValue.h:234
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:349
bool isRelationalOp() const
Definition: Expr.h:3230
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:3858
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2827
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc)
CheckIndirectionOperand - Type check unary indirection (prefix &#39;*&#39;).
Definition: SemaExpr.cpp:11718
Helper class for OffsetOfExpr.
Definition: Expr.h:1921
The current expression occurs within a discarded statement.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2085
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1245
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1264
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:3861
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:1649
const LangOptions & getLangOpts() const
Definition: Sema.h:1204
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:752
bool isInstance() const
Definition: DeclCXX.h:2073
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:167
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:628
bool isScalarType() const
Definition: Type.h:6425
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3219
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:8018
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:520
An ordinary object is located at an address in memory.
Definition: Specifiers.h:126
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
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:12334
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:7507
Represents an ObjC class declaration.
Definition: DeclObjC.h:1193
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition: Sema.h:964
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:1836
QualType getReturnType() const
Definition: DeclObjC.h:363
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:415
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:5835
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:5220
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:9452
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:2740
QualType getBOOLType() const
type of &#39;BOOL&#39; type.
Definition: ASTContext.h:1875
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:3269
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
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:16299
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:15373
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2116
CanQualType UnsignedCharTy
Definition: ASTContext.h:1014
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1087
void setStmt(LabelStmt *T)
Definition: Decl.h:493
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, bool isConstexprSpecified=false)
Definition: Decl.h:1911
const LangOptions & LangOpts
Definition: Sema.h:317
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:457
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:1918
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
void ActOnStmtExprError()
Definition: SemaExpr.cpp:12945
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:559
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:331
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:954
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:1909
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:612
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1208
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1776
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas...
Definition: ScopeInfo.h:887
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1140
bool isHalfType() const
Definition: Type.h:6346
NodeId Parent
Definition: ASTDiff.cpp:192
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:3062
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:45
bool hasAttr() const
Definition: DeclBase.h:538
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3429
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:277
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:12409
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2458
void setNamingClass(CXXRecordDecl *Record)
Sets the &#39;naming class&#39; for this lookup.
Definition: Lookup.h:397
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:7181
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:788
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:616
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1627
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:813
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3432
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:7233
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:589
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:15447
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:2194
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2856
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:499
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:11919
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:11998
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3230
Expr * IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY
IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the value (including ptr->int ...
Definition: Expr.cpp:2664
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:473
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:7182
Retains information about a captured region.
Definition: ScopeInfo.h:720
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1355
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:12351
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:205
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:1738
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1785
static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, ExprResult &RHS)
Handle when one or both operands are void type.
Definition: SemaExpr.cpp:6391
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:548
Specifies that the expression should never be value-dependent.
Definition: Expr.h:705
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9003
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:9442
void setSubExpr(Expr *E)
Definition: Expr.h:1833
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2134
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:6334
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:1837
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, std::unique_ptr< CorrectionCandidateCallback > CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr *> Args=None, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:1775
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2523
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5964
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:8942
SourceLocation getLocation() const
Definition: Expr.h:1067
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:1768
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:3954
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param)
Definition: ExprCXX.h:1112
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:208
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:264
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1129
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:1486
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool hasDefinition() const
Determine whether this protocol has a definition.
Definition: DeclObjC.h:2219
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:8741
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:10593
unsigned getValue() const
Definition: Expr.h:1442
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:3033
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:5695
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:155
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:136
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition...
Definition: SemaExpr.cpp:15691
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12444
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true)
Create a binary operation that may resolve to an overloaded operator.
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:694
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1359
VarDecl * isOpenMPCapturedDecl(ValueDecl *D) const
Check if the specified variable is used in one of the private clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP constructs.
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:774
QualType getElementType() const
Definition: Type.h:2346
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4280
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.
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3860
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:637
Expr - This represents one expression.
Definition: Expr.h:106
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:1433
SourceLocation End
Represents a character-granular source range.
static bool isEvaluatableContext(Sema &SemaRef)
Are we within a context in which some evaluation could be performed (be it constant evaluation or run...
Definition: SemaExpr.cpp:14251
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:107
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:12312
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2620
void setCallee(Expr *F)
Definition: Expr.h:2358
std::string Label
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:14551
int Id
Definition: ASTDiff.cpp:191
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1481
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1035
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4295
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:375
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:12297
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1345
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2700
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:1257
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:226
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool isObjCBuiltinType() const
Definition: Type.h:6257
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6589
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:13697
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)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:14837
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5051
static Expr * maybeRebuildARCConsumingStmt(Stmt *Statement)
Given the last statement in a statement-expression, check whether the result is a producing expressio...
Definition: SemaExpr.cpp:12923
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:86
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2700
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1043
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
std::string getAsString() const
getNameAsString - 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:554
const Expr * getCallee() const
Definition: Expr.h:2356
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
Defines the clang::Preprocessor interface.
bool isNullPtrType() const
Definition: Type.h:6365
bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaInternal.h:44
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:13963
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
#define bool
Definition: stdbool.h:31
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:2731
ObjCLifetime getObjCLifetime() const
Definition: Type.h:343
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isObjCClassType() const
Definition: Type.h:6245
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12380
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
DeclContext * getDeclContext()
Definition: DeclBase.h:428
SourceLocation getLParenLoc() const
Definition: Expr.h:4830
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1655
Overload resolution succeeded.
Definition: Overload.h:54
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:5673
bool isAnyComplexType() const
Definition: Type.h:6194
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:7616
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode. ...
Definition: Expr.cpp:1175
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:12458
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:331
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:13716
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
Definition: DeclCXX.cpp:526
CanQualType ShortTy
Definition: ASTContext.h:1013
static ValueDecl * getCompareDecl(Expr *E)
Definition: SemaExpr.cpp:9712
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:5102
static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, ValueDecl *var, DeclContext *DC)
Definition: SemaExpr.cpp:14478
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don&#39;t permit to be...
Definition: Sema.h:9461
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:16367
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:1971
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1185
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:808
Represents a C++ template name within the type system.
Definition: TemplateName.h:178
static DependentScopeDeclRefExpr * Create(const ASTContext &C, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:421
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4161
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7497
Defines the clang::TypeLoc interface and its subclasses.
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:117
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1004
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:14234
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn&#39;t a simple identifier.
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:709
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2626
QualType getType() const
Definition: Expr.h:128
bool isFunctionOrMethod() const
Definition: DeclBase.h:1392
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:947
Capture & getCapture(VarDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:675
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:614
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:10643
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:422
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:297
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:165
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1343
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:389
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:4769
ScalarTypeKind
Definition: Type.h:1925
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:925
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:65
ConditionKind
Definition: Sema.h:9824
bool isInvalid() const
Definition: Ownership.h:170
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:11820
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:1805
bool isInstanceMethod() const
Definition: DeclObjC.h:454
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:1365
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of &#39;F&#39;...
Definition: Expr.h:2700
Represents a GCC generic vector type.
Definition: Type.h:3024
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2705
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13209
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2449
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1040
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:15228
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:6320
ValueDecl * getDecl()
Definition: Expr.h:1059
bool isUsable() const
Definition: Ownership.h:171
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2762
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:1381
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:152
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:178
const Expr * getSubExpr() const
Definition: Expr.h:1767
const Expr * getSubExpr() const
Definition: ExprCXX.h:1268
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:735
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:5709
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:720
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:446
void setBlockMangling(unsigned Number, Decl *Ctx)
Definition: Decl.h:4018
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:298
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level)
Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) for FD based on DSA for the...
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:170
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:5097
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2351
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:122
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2006
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:11967
SourceRange getSourceRange() const
Definition: ExprCXX.h:139
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1535
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:166
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:4989
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:412
A narrowing conversion, because a non-constant-expression variable might have got narrowed...
Definition: Overload.h:215
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing...
Definition: SemaExpr.cpp:5051
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isUnresolvableResult() const
Definition: Lookup.h:306
static CharSourceRange getCharRange(SourceRange R)
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3307
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:84
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5948
bool isVoidPointerType() const
Definition: Type.cpp:461
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3558
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:6027
bool isComparisonOp() const
Definition: Expr.h:3236
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:11471
RecordDecl * getDecl() const
Definition: Type.h:4145
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:126
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:15377
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3226
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:711
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1550
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:1846
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:6581
Wrapper for source info for arrays.
Definition: TypeLoc.h:1529
Expr * IgnoreConversionOperator() LLVM_READONLY
IgnoreConversionOperator - Ignore conversion operator.
Definition: Expr.cpp:2653
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:618
CanQualType OverloadTy
Definition: ASTContext.h:1033
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:8795
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:875
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:1903
Integral conversions (C++ [conv.integral])
Definition: Overload.h:108
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:917
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:1621
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
CanQualType BuiltinFnTy
Definition: ASTContext.h:1034
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:182
Kind
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2636
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:487
QualType getCanonicalType() const
Definition: Type.h:5928
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:16470
not a target-specific vector type
Definition: Type.h:3028
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted, bool IsNested=false)
Definition: SemaExpr.cpp:10879
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
LookupInObjCMethod - The parser has read a name in, and Sema has detected that we&#39;re currently inside...
Definition: SemaExpr.cpp:2356
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5177
param_type_range param_types() const
Definition: Type.h:3796
A stack object to be created when performing template instantiation.
Definition: Sema.h:7352
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:3843
VarDecl * getVariable() const
Definition: ScopeInfo.h:576
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3679
ASTContext & getASTContext() const
Definition: Sema.h:1211
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
unsigned getNumExprs() const
Definition: Expr.h:4812
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:3368
Encodes a location in the source.
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:5473
llvm::SmallPtrSet< Expr *, 2 > MaybeODRUseExprs
Store a list of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) ...
Definition: Sema.h:532
QualType getReturnType() const
Definition: Type.h:3365
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:4161
SourceLocation getOperatorLoc() const
Definition: Expr.h:3181
llvm::SmallPtrSet< Expr *, 2 > SavedMaybeODRUseExprs
Definition: Sema.h:960
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:5820
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6005
This represents &#39;#pragma omp declare reduction ...&#39; directive.
Definition: DeclOpenMP.h:102
Expression is not a Null pointer constant.
Definition: Expr.h:682
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:968
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:763
Expr * getSubExpr() const
Definition: Expr.h:1832
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5555
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:7110
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1958
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:771
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:1647
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11282
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:9999
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:13662
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:490
CastKind getCastKind() const
Definition: Expr.h:2886
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1915
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:11414
void setLastStmt(Stmt *S)
Definition: Stmt.h:656
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:3628
DeclarationName getName() const
getName - Returns the embedded declaration name.
static bool IgnoreCommaOperand(const Expr *E)
Definition: SemaExpr.cpp:11221
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:385
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.h:401
QualType getElementType() const
Definition: Type.h:3059
void setReferenced(bool R=true)
Definition: DeclBase.h:584
Represents the declaration of a label.
Definition: Decl.h:468
IncompatiblePointer - The assignment is between two pointers types that are not compatible, but we accept them as an extension.
Definition: Sema.h:9446
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3096
bool isOverloadedResult() const
Determines if the results are overloaded.
Definition: Lookup.h:302
const Expr * getExpr(unsigned Init) const
Definition: Expr.h:4814
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:124
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:1380
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:2208
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1763
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2045
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:8291
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:186
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2395
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:14139
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:186
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:532
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
CanQualType FloatTy
Definition: ASTContext.h:1016
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2254
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:5779
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:713
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:1004
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
CheckBoolLikeConversion - Check conversion of given expression to boolean.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
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 isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const
Return true if the provided declaration VD should be captured by reference.
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
const TemplateArgumentListInfo & getTemplateArgsInfo() const
Qualifiers withoutObjCLifetime() const
Definition: Type.h:336
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:7966
CanQualType Float16Ty
Definition: ASTContext.h:1029
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:135
bool isAnyPointerType() const
Definition: Type.h:6117
bool isObjCObjectPointerType() const
Definition: Type.h:6210
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3037
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:625
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion...
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:958
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:748
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2961
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1173
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2489
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:249
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:3031
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1649
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR)
Definition: SemaExpr.cpp:13957
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.h:403
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc)
Definition: SemaExpr.cpp:4244
bool isAddressSpaceOverlapping(const PointerType &other) const
Returns true if address spaces of pointers overlap.
Definition: Type.h:2416
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:892
TypeClass getTypeClass() const
Definition: Type.h:1691
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:2992
QualType getAttributedType(AttributedType::Kind attrKind, QualType modifiedType, QualType equivalentType)
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:397
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:149
bool typesAreBlockPointerCompatible(QualType, QualType)
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1827
EnumDecl * getDecl() const
Definition: Type.h:4168
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1324
bool isVectorType() const
Definition: Type.h:6198
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:141
Assigning into this object requires a lifetime extension.
Definition: Type.h:188
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3654
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:830
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:163
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:14242
bool isCanonical() const
Definition: Type.h:5933
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:571
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2275
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:592
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:9292
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2017
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag)
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:12954
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3703
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
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:9211
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1111
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:11934
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:16275
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3351
A POD class for pairing a NamedDecl* with an access specifier.
bool isRealType() const
Definition: Type.cpp:1947
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:6314
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we&#39;re in ARC.
Definition: SemaExpr.cpp:5805
Represents a C11 generic selection.
Definition: Expr.h:4880
ReuseLambdaContextDecl_t
Definition: Sema.h:4015
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:2461
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:3608
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:15425
CanQualType CharTy
Definition: ASTContext.h:1006
Represents a template argument.
Definition: TemplateBase.h:51
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:8992
bool isPipeType() const
Definition: Type.h:6294
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:1716
static bool isInvalid(LocType Loc, bool *Invalid)
NonConstCaptureKind
Is the given expression (which must be &#39;const&#39;) a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:10695
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:7947
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2501
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...
void setBody(CompoundStmt *B)
Definition: Decl.h:3943
bool isValid() const
Return true if this is a valid SourceLocation object.
ExtInfo getExtInfo() const
Definition: Type.h:3376
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:12413
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:9205
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1208
UnaryOperatorKind
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1264
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input)
Definition: SemaExpr.cpp:12904
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:10633
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2145
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:3990
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:8903
bool isSentinelNullExpr(const Expr *E)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1251
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:10461
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:470
typedef char* __builtin_va_list;
Definition: TargetInfo.h:183
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:1073
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:130
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:10501
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3488
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
static bool CheckAlignOfExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:3791
bool isShiftOp() const
Definition: Expr.h:3224
bool isRecord() const
Definition: DeclBase.h:1417
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:9577
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:2112
static bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaExpr.cpp:15172
Represents a field injected from an anonymous union/struct into the parent scope. ...
Definition: Decl.h:2780
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:8244
void setSubExpr(Expr *E)
Definition: Expr.h:2894
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:5452
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:15605
BinaryOperator::Opcode getOpcode(const SymExpr *SE)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:8635
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1015
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:1757
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:9727
const Expr * getInit() const
Definition: Decl.h:1219
A runtime availability query.
Definition: ExprObjC.h:1670
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:87
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:160
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:2733
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of &#39;this&#39;; zero if &#39;this&#39; is not captured...
Definition: ScopeInfo.h:622
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:3651
DeclarationName - The name of a declaration.
StmtClass getStmtClass() const
Definition: Stmt.h:391
VectorKind getVectorKind() const
Definition: Type.h:3069
const char * getCastKindName() const
Definition: Expr.h:2890
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:506
Expr * getDefaultArg()
Definition: Decl.cpp:2539
void setInstantiationIsPending(bool IC)
Definition: Decl.h:2100
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:988
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:345
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2165
const Expr * getExpr() const
Definition: ExprCXX.h:1122
bool isBooleanType() const
Definition: Type.h:6453
Kind getKind() const
Definition: DeclBase.h:422
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:15919
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:689
U cast(CodeGen::Address addr)
Definition: Address.h:109
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:2455
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6082
A set of unresolved declarations.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:739
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:9479
Expression is a C++11 nullptr.
Definition: Expr.h:695
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:9669
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:3383
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:12284
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:146
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Expr * get() const
Definition: Sema.h:3658
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1392
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: DeclCXX.h:2143
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3039
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4147
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3079
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4168
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:15214
unsigned getLength() const
Definition: Token.h:127
IdentifierInfo * getCorrectionAsIdentifierInfo() const
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1073
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:4884
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> Types, ArrayRef< Expr *> Exprs)
Definition: SemaExpr.cpp:1332
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2631
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:5611
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:150
Pointer to a block type.
Definition: Type.h:2495
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1037
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:3621
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:12305
unsigned getIntWidth(QualType T) const
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:8671
Not an overloaded operator.
Definition: OperatorKinds.h:23
RecordDecl * TheRecordDecl
The captured record type.
Definition: ScopeInfo.h:726
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:4073
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:544
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4135
Complex values, per C99 6.2.5p11.
Definition: Type.h:2333
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2581
CanQualType UnknownAnyTy
Definition: ASTContext.h:1033
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3505
bool body_empty() const
Definition: Stmt.h:641
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:5667
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2226
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:1918
ObjCLiteralKind
Definition: Sema.h:2696
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:6787
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6374
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:2273
CanQualType UnsignedLongTy
Definition: ASTContext.h:1014
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1751
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:534
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:6115
SourceLocation getLocation() const
Definition: ExprObjC.h:572
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:12366
const llvm::APInt & getSize() const
Definition: Type.h:2746
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2056
CanQualType DependentTy
Definition: ASTContext.h:1033
bool isImageType() const
Definition: Type.h:6287
void setSubExpr(Expr *E)
As with any mutator of the AST, be very careful when modifying an existing AST to preserve its invari...
Definition: ExprCXX.h:3141
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:1194
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:8848
bool isAtomicType() const
Definition: Type.h:6223
Represents a call to a CUDA kernel function.
Definition: ExprCXX.h:205
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:9866
bool isFunctionType() const
Definition: Type.h:6109
bool isAddressSpaceSupersetOf(Qualifiers other) const
Returns true if this address space is a superset of the other one.
Definition: Type.h:486
bool isObjCQualifiedIdType() const
Definition: Type.h:6227
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:1478
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:716
ExtVectorType - Extended vector type.
Definition: Type.h:3143
Opcode getOpcode() const
Definition: Expr.h:1829
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2529
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1675
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2251
CanQualType BoundMemberTy
Definition: ASTContext.h:1033
LValueClassification
Definition: Expr.h:254
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1017
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:7516
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:8752
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:12608
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:2703
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:11318
qual_range quals() const
Definition: Type.h:5734
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:1771
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:32
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:2709
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
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1460
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:251
const Expr * getBase() const
Definition: ExprObjC.h:563
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3711
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2804
bool isConstantArrayType() const
Definition: Type.h:6166
llvm::DenseMap< VarDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:618
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:13190
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:129
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:8389
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:412
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2052
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:529
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:9466
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:8181
bool isObjCObjectType() const
Definition: Type.h:6214
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2034
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2023
CanQualType Char8Ty
Definition: ASTContext.h:1010
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2321
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:847
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1351
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2235
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:239
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:392
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:4328
Reading or writing from this object requires a barrier call.
Definition: Type.h:185
bool isQueueT() const
Definition: Type.h:6279
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:3984
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:235
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4190
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
getCXXLiteralOperatorName - Get the name of the literal operator function with II as the identifier...
QualType getParamType(unsigned i) const
Definition: Type.h:3670
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:862
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:692
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups, surround it with a ExprWithCleanups node.
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1643
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:15250
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:90
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:997
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr *> ArgExprs)
Definition: SemaExpr.cpp:1306
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2500
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:942
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10558
Describes the sequence of initializations required to initialize a given object or reference with a s...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:267
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5969
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3261
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:1034
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2551
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:9518
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:1878
Represents a C++ struct/union/class.
Definition: DeclCXX.h:302
Compatible - the types are compatible according to the standard.
Definition: Sema.h:9430
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:6340
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2910
CUDAFunctionTarget
Definition: Sema.h:10059
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:574
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1331
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4166
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3836
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:2824
bool isNested() const
Definition: ScopeInfo.h:568
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:7135
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3504
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:1737
SourceLocation getRParenLoc() const
Definition: Expr.h:4831
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5916
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:1966
CanQualType Char16Ty
Definition: ASTContext.h:1011
bool isMultiplicativeOp() const
Definition: Expr.h:3220
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:6054
TryCaptureKind
Definition: Sema.h:4051
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:15145
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10028
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:8683
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:547
Location information for a TemplateArgument.
Definition: TemplateBase.h:393
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:331
bool isSamplerT() const
Definition: Type.h:6267
bool isCXXThisCaptured() const
Determine whether the C++ &#39;this&#39; is captured.
Definition: ScopeInfo.h:657
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:182
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
Definition: Expr.h:214
bool isRValue() const
Definition: Expr.h:250
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:2250
void addVLATypeCapture(SourceLocation Loc, QualType CaptureType)
Definition: ScopeInfo.h:643
SourceManager & getSourceManager() const
Definition: Sema.h:1209
iterator end() const
Definition: Lookup.h:325
A template-id, e.g., f<int>.
static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A)
checkUnusedDeclAttributes - Check a list of attributes to see if it contains any decl attributes that...
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:266
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11236
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all...
Definition: Sema.h:895
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3159
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1585
Defines the clang::TargetInfo interface.
bool isComplexIntegerType() const
Definition: Type.cpp:479
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2316
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:9829
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion)
type checking for vector binary operators.
Definition: SemaExpr.cpp:8464
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
void UpdateMarkingForLValueToRValue(Expr *E)
Definition: SemaExpr.cpp:15189
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3567
unsigned getCVRQualifiers() const
Definition: Type.h:293
ExprResult ExprError()
Definition: Ownership.h:283
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:2503
uint64_t Width
Definition: ASTContext.h:139
CanQualType IntTy
Definition: ASTContext.h:1013
static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S)
Definition: SemaExpr.cpp:14634
unsigned getNumElements() const
Definition: Type.h:3060
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:84
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
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:1942
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:5262
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:974
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:818
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:3949
The class facilities generation and storage of conversion FixIts.
Expr * getRHS() const
Definition: Expr.h:3189
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13536
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2125
bool isPointerType() const
Definition: Type.h:6113
bool isBitwiseOp() const
Definition: Expr.h:3227
bool isIncrementDecrementOp() const
Definition: Expr.h:1876
static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses=true)
Are we within a context in which references to resolved functions or to variables result in odr-use...
Definition: SemaExpr.cpp:14276
void setSubStmt(Stmt *SS)
Definition: Stmt.h:898
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e.g.
Definition: SemaExpr.cpp:1522
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:1884
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 addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, Expr *Cpy)
Definition: ScopeInfo.h:635
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:197
DeclaratorContext getContext() const
Definition: DeclSpec.h:1866
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:572
void setLocation(SourceLocation L)
Definition: Token.h:132
QualType getType() const
Definition: Decl.h:648
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:328
bool isFloatingType() const
Definition: Type.cpp:1925
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:4162
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:319
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< 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...
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2899
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:9484
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:15776
This represents a decl that may have a name.
Definition: Decl.h:248
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1011
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:160
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:6224
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1088
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:458
CanQualType BoolTy
Definition: ASTContext.h:1005
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2827
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:15648
No keyword precedes the qualified type name.
Definition: Type.h:4887
bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1481
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12492
APSInt & getInt()
Definition: APValue.h:252
AccessControl getAccessControl() const
Definition: DeclObjC.h:2005
iterator begin() const
Definition: Lookup.h:324
CanQualType DoubleTy
Definition: ASTContext.h:1016
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:595
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2032
Describes an entity that is being initialized.
bool isFunctionPointerType() const
Definition: Type.h:6137
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:3692
unsigned NumArgs
NumArgs - The number of template arguments.
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:513
ComparisonCategoryType
An enumeration representing the different comparison categories types.
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:318
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:306
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:78
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:6739
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:2971
void setType(QualType newType)
Definition: Decl.h:649
void removeAddressSpace()
Definition: Type.h:394
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3235
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:92
bool hasInit() const
Definition: Decl.cpp:2144
SourceLocation getBegin() const
AssignmentAction
Definition: Sema.h:2483
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:102
const LangOptions & getLangOpts() const
Definition: ASTContext.h:696
void WillReplaceSpecifier(bool ForceReplacement)
bool isBlockCapture() const
Definition: ScopeInfo.h:560
An implicit &#39;self&#39; parameter.
No in-class initializer.
Definition: Specifiers.h:230
The lookup resulted in an error.
Definition: Sema.h:3088
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:11878
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2728
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:7125
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types...
Definition: Sema.h:9467
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
Declaration of a template function.
Definition: DeclTemplate.h:968
void clear()
Clears out any current state.
Definition: Lookup.h:543
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3236
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:14299
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:680
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprObjC.h:575
One specifier in an expression.
Definition: Availability.h:31
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2012
Attr - This represents one attribute.
Definition: Attr.h:43
SourceLocation getLocation() const
Definition: DeclBase.h:419
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1741
CastType
Definition: SemaCast.cpp:46
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign=false)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6...
Definition: SemaExpr.cpp:1226
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:12910
bool isExternallyVisible() const
Definition: Decl.h:379
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:11483
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
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:407
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:8754
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:13398
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:138
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1234
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form, which contains extra information on the evaluated value of the initializer.
Definition: Decl.cpp:2224
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2513
OriginalExprKind
Definition: SemaExpr.cpp:10873
CanQualType UnsignedIntTy
Definition: ASTContext.h:1014
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:3532
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:1079
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:11699
Structure used to store a statement, the constant value to which it was evaluated (if any)...
Definition: Decl.h:785
A RAII object to temporarily push a declaration context.
Definition: Sema.h:706
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:4683
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5627
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:230
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4090