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