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