1252723Sdim//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file provides Sema routines for C++ overloading.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14252723Sdim#include "clang/Sema/Overload.h"
15193326Sed#include "clang/AST/ASTContext.h"
16198092Srdivacky#include "clang/AST/CXXInheritance.h"
17212904Sdim#include "clang/AST/DeclObjC.h"
18193326Sed#include "clang/AST/Expr.h"
19193326Sed#include "clang/AST/ExprCXX.h"
20218893Sdim#include "clang/AST/ExprObjC.h"
21193326Sed#include "clang/AST/TypeOrdering.h"
22252723Sdim#include "clang/Basic/Diagnostic.h"
23198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
24263509Sdim#include "clang/Basic/TargetInfo.h"
25252723Sdim#include "clang/Lex/Preprocessor.h"
26252723Sdim#include "clang/Sema/Initialization.h"
27252723Sdim#include "clang/Sema/Lookup.h"
28252723Sdim#include "clang/Sema/SemaInternal.h"
29252723Sdim#include "clang/Sema/Template.h"
30252723Sdim#include "clang/Sema/TemplateDeduction.h"
31218893Sdim#include "llvm/ADT/DenseSet.h"
32252723Sdim#include "llvm/ADT/STLExtras.h"
33193326Sed#include "llvm/ADT/SmallPtrSet.h"
34245431Sdim#include "llvm/ADT/SmallString.h"
35193326Sed#include <algorithm>
36193326Sed
37193326Sednamespace clang {
38212904Sdimusing namespace sema;
39193326Sed
40252723Sdim/// A convenience routine for creating a decayed reference to a function.
41221345Sdimstatic ExprResult
42252723SdimCreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43252723Sdim                      bool HadMultipleCandidates,
44224145Sdim                      SourceLocation Loc = SourceLocation(),
45224145Sdim                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
46252723Sdim  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
47263509Sdim    return ExprError();
48263509Sdim  // If FoundDecl is different from Fn (such as if one is a template
49263509Sdim  // and the other a specialization), make sure DiagnoseUseOfDecl is
50263509Sdim  // called on both.
51263509Sdim  // FIXME: This would be more comprehensively addressed by modifying
52263509Sdim  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53263509Sdim  // being used.
54263509Sdim  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
55252723Sdim    return ExprError();
56235633Sdim  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
57226890Sdim                                                 VK_LValue, Loc, LocInfo);
58226890Sdim  if (HadMultipleCandidates)
59226890Sdim    DRE->setHadMultipleCandidates(true);
60252723Sdim
61252723Sdim  S.MarkDeclRefReferenced(DRE);
62252723Sdim
63226890Sdim  ExprResult E = S.Owned(DRE);
64221345Sdim  E = S.DefaultFunctionArrayConversion(E.take());
65221345Sdim  if (E.isInvalid())
66221345Sdim    return ExprError();
67245431Sdim  return E;
68218893Sdim}
69218893Sdim
70212904Sdimstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
71212904Sdim                                 bool InOverloadResolution,
72218893Sdim                                 StandardConversionSequence &SCS,
73224145Sdim                                 bool CStyle,
74224145Sdim                                 bool AllowObjCWritebackConversion);
75245431Sdim
76221345Sdimstatic bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
77221345Sdim                                                 QualType &ToType,
78221345Sdim                                                 bool InOverloadResolution,
79221345Sdim                                                 StandardConversionSequence &SCS,
80221345Sdim                                                 bool CStyle);
81212904Sdimstatic OverloadingResult
82212904SdimIsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
83212904Sdim                        UserDefinedConversionSequence& User,
84212904Sdim                        OverloadCandidateSet& Conversions,
85263509Sdim                        bool AllowExplicit,
86263509Sdim                        bool AllowObjCConversionOnExplicit);
87212904Sdim
88212904Sdim
89212904Sdimstatic ImplicitConversionSequence::CompareKind
90212904SdimCompareStandardConversionSequences(Sema &S,
91212904Sdim                                   const StandardConversionSequence& SCS1,
92212904Sdim                                   const StandardConversionSequence& SCS2);
93212904Sdim
94212904Sdimstatic ImplicitConversionSequence::CompareKind
95212904SdimCompareQualificationConversions(Sema &S,
96212904Sdim                                const StandardConversionSequence& SCS1,
97212904Sdim                                const StandardConversionSequence& SCS2);
98212904Sdim
99212904Sdimstatic ImplicitConversionSequence::CompareKind
100212904SdimCompareDerivedToBaseConversions(Sema &S,
101212904Sdim                                const StandardConversionSequence& SCS1,
102212904Sdim                                const StandardConversionSequence& SCS2);
103212904Sdim
104212904Sdim
105212904Sdim
106193326Sed/// GetConversionCategory - Retrieve the implicit conversion
107193326Sed/// category corresponding to the given implicit conversion kind.
108198092SrdivackyImplicitConversionCategory
109193326SedGetConversionCategory(ImplicitConversionKind Kind) {
110193326Sed  static const ImplicitConversionCategory
111193326Sed    Category[(int)ICK_Num_Conversion_Kinds] = {
112193326Sed    ICC_Identity,
113193326Sed    ICC_Lvalue_Transformation,
114193326Sed    ICC_Lvalue_Transformation,
115193326Sed    ICC_Lvalue_Transformation,
116200583Srdivacky    ICC_Identity,
117193326Sed    ICC_Qualification_Adjustment,
118193326Sed    ICC_Promotion,
119193326Sed    ICC_Promotion,
120193326Sed    ICC_Promotion,
121193326Sed    ICC_Conversion,
122193326Sed    ICC_Conversion,
123193326Sed    ICC_Conversion,
124193326Sed    ICC_Conversion,
125193326Sed    ICC_Conversion,
126193326Sed    ICC_Conversion,
127193326Sed    ICC_Conversion,
128193326Sed    ICC_Conversion,
129193326Sed    ICC_Conversion,
130208600Srdivacky    ICC_Conversion,
131208600Srdivacky    ICC_Conversion,
132224145Sdim    ICC_Conversion,
133193326Sed    ICC_Conversion
134193326Sed  };
135193326Sed  return Category[(int)Kind];
136193326Sed}
137193326Sed
138193326Sed/// GetConversionRank - Retrieve the implicit conversion rank
139193326Sed/// corresponding to the given implicit conversion kind.
140193326SedImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
141193326Sed  static const ImplicitConversionRank
142193326Sed    Rank[(int)ICK_Num_Conversion_Kinds] = {
143193326Sed    ICR_Exact_Match,
144193326Sed    ICR_Exact_Match,
145193326Sed    ICR_Exact_Match,
146193326Sed    ICR_Exact_Match,
147193326Sed    ICR_Exact_Match,
148200583Srdivacky    ICR_Exact_Match,
149193326Sed    ICR_Promotion,
150193326Sed    ICR_Promotion,
151193326Sed    ICR_Promotion,
152193326Sed    ICR_Conversion,
153193326Sed    ICR_Conversion,
154193326Sed    ICR_Conversion,
155193326Sed    ICR_Conversion,
156193326Sed    ICR_Conversion,
157193326Sed    ICR_Conversion,
158193326Sed    ICR_Conversion,
159193326Sed    ICR_Conversion,
160193326Sed    ICR_Conversion,
161208600Srdivacky    ICR_Conversion,
162208600Srdivacky    ICR_Conversion,
163221345Sdim    ICR_Complex_Real_Conversion,
164221345Sdim    ICR_Conversion,
165224145Sdim    ICR_Conversion,
166224145Sdim    ICR_Writeback_Conversion
167193326Sed  };
168193326Sed  return Rank[(int)Kind];
169193326Sed}
170193326Sed
171193326Sed/// GetImplicitConversionName - Return the name of this kind of
172193326Sed/// implicit conversion.
173193326Sedconst char* GetImplicitConversionName(ImplicitConversionKind Kind) {
174201361Srdivacky  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
175193326Sed    "No conversion",
176193326Sed    "Lvalue-to-rvalue",
177193326Sed    "Array-to-pointer",
178193326Sed    "Function-to-pointer",
179200583Srdivacky    "Noreturn adjustment",
180193326Sed    "Qualification",
181193326Sed    "Integral promotion",
182193326Sed    "Floating point promotion",
183193326Sed    "Complex promotion",
184193326Sed    "Integral conversion",
185193326Sed    "Floating conversion",
186193326Sed    "Complex conversion",
187193326Sed    "Floating-integral conversion",
188193326Sed    "Pointer conversion",
189193326Sed    "Pointer-to-member conversion",
190193326Sed    "Boolean conversion",
191193326Sed    "Compatible-types conversion",
192208600Srdivacky    "Derived-to-base conversion",
193208600Srdivacky    "Vector conversion",
194208600Srdivacky    "Vector splat",
195221345Sdim    "Complex-real conversion",
196221345Sdim    "Block Pointer conversion",
197221345Sdim    "Transparent Union Conversion"
198224145Sdim    "Writeback conversion"
199193326Sed  };
200193326Sed  return Name[Kind];
201193326Sed}
202193326Sed
203193326Sed/// StandardConversionSequence - Set the standard conversion
204193326Sed/// sequence to the identity conversion.
205193326Sedvoid StandardConversionSequence::setAsIdentityConversion() {
206193326Sed  First = ICK_Identity;
207193326Sed  Second = ICK_Identity;
208193326Sed  Third = ICK_Identity;
209204643Srdivacky  DeprecatedStringLiteralToCharPtr = false;
210224145Sdim  QualificationIncludesObjCLifetime = false;
211193326Sed  ReferenceBinding = false;
212193326Sed  DirectBinding = false;
213218893Sdim  IsLvalueReference = true;
214218893Sdim  BindsToFunctionLvalue = false;
215218893Sdim  BindsToRvalue = false;
216218893Sdim  BindsImplicitObjectArgumentWithoutRefQualifier = false;
217224145Sdim  ObjCLifetimeConversionBinding = false;
218193326Sed  CopyConstructor = 0;
219193326Sed}
220193326Sed
221193326Sed/// getRank - Retrieve the rank of this standard conversion sequence
222193326Sed/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
223193326Sed/// implicit conversions.
224193326SedImplicitConversionRank StandardConversionSequence::getRank() const {
225193326Sed  ImplicitConversionRank Rank = ICR_Exact_Match;
226193326Sed  if  (GetConversionRank(First) > Rank)
227193326Sed    Rank = GetConversionRank(First);
228193326Sed  if  (GetConversionRank(Second) > Rank)
229193326Sed    Rank = GetConversionRank(Second);
230193326Sed  if  (GetConversionRank(Third) > Rank)
231193326Sed    Rank = GetConversionRank(Third);
232193326Sed  return Rank;
233193326Sed}
234193326Sed
235193326Sed/// isPointerConversionToBool - Determines whether this conversion is
236193326Sed/// a conversion of a pointer or pointer-to-member to bool. This is
237198092Srdivacky/// used as part of the ranking of standard conversion sequences
238193326Sed/// (C++ 13.3.3.2p4).
239198092Srdivackybool StandardConversionSequence::isPointerConversionToBool() const {
240193326Sed  // Note that FromType has not necessarily been transformed by the
241193326Sed  // array-to-pointer or function-to-pointer implicit conversions, so
242193326Sed  // check for their presence as well as checking whether FromType is
243193326Sed  // a pointer.
244203955Srdivacky  if (getToType(1)->isBooleanType() &&
245210299Sed      (getFromType()->isPointerType() ||
246210299Sed       getFromType()->isObjCObjectPointerType() ||
247210299Sed       getFromType()->isBlockPointerType() ||
248218893Sdim       getFromType()->isNullPtrType() ||
249193326Sed       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
250193326Sed    return true;
251193326Sed
252193326Sed  return false;
253193326Sed}
254193326Sed
255193326Sed/// isPointerConversionToVoidPointer - Determines whether this
256193326Sed/// conversion is a conversion of a pointer to a void pointer. This is
257193326Sed/// used as part of the ranking of standard conversion sequences (C++
258193326Sed/// 13.3.3.2p4).
259198092Srdivackybool
260193326SedStandardConversionSequence::
261198092SrdivackyisPointerConversionToVoidPointer(ASTContext& Context) const {
262202379Srdivacky  QualType FromType = getFromType();
263203955Srdivacky  QualType ToType = getToType(1);
264193326Sed
265193326Sed  // Note that FromType has not necessarily been transformed by the
266193326Sed  // array-to-pointer implicit conversion, so check for its presence
267193326Sed  // and redo the conversion to get a pointer.
268193326Sed  if (First == ICK_Array_To_Pointer)
269193326Sed    FromType = Context.getArrayDecayedType(FromType);
270193326Sed
271221345Sdim  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
272198092Srdivacky    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
273193326Sed      return ToPtrType->getPointeeType()->isVoidType();
274193326Sed
275193326Sed  return false;
276193326Sed}
277193326Sed
278235633Sdim/// Skip any implicit casts which could be either part of a narrowing conversion
279235633Sdim/// or after one in an implicit conversion.
280235633Sdimstatic const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
281235633Sdim  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
282235633Sdim    switch (ICE->getCastKind()) {
283235633Sdim    case CK_NoOp:
284235633Sdim    case CK_IntegralCast:
285235633Sdim    case CK_IntegralToBoolean:
286235633Sdim    case CK_IntegralToFloating:
287235633Sdim    case CK_FloatingToIntegral:
288235633Sdim    case CK_FloatingToBoolean:
289235633Sdim    case CK_FloatingCast:
290235633Sdim      Converted = ICE->getSubExpr();
291235633Sdim      continue;
292235633Sdim
293235633Sdim    default:
294235633Sdim      return Converted;
295235633Sdim    }
296235633Sdim  }
297235633Sdim
298235633Sdim  return Converted;
299235633Sdim}
300235633Sdim
301235633Sdim/// Check if this standard conversion sequence represents a narrowing
302235633Sdim/// conversion, according to C++11 [dcl.init.list]p7.
303235633Sdim///
304235633Sdim/// \param Ctx  The AST context.
305235633Sdim/// \param Converted  The result of applying this standard conversion sequence.
306235633Sdim/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
307235633Sdim///        value of the expression prior to the narrowing conversion.
308235633Sdim/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
309235633Sdim///        type of the expression prior to the narrowing conversion.
310235633SdimNarrowingKind
311235633SdimStandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
312235633Sdim                                             const Expr *Converted,
313235633Sdim                                             APValue &ConstantValue,
314235633Sdim                                             QualType &ConstantType) const {
315235633Sdim  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
316235633Sdim
317235633Sdim  // C++11 [dcl.init.list]p7:
318235633Sdim  //   A narrowing conversion is an implicit conversion ...
319235633Sdim  QualType FromType = getToType(0);
320235633Sdim  QualType ToType = getToType(1);
321235633Sdim  switch (Second) {
322235633Sdim  // -- from a floating-point type to an integer type, or
323235633Sdim  //
324235633Sdim  // -- from an integer type or unscoped enumeration type to a floating-point
325235633Sdim  //    type, except where the source is a constant expression and the actual
326235633Sdim  //    value after conversion will fit into the target type and will produce
327235633Sdim  //    the original value when converted back to the original type, or
328235633Sdim  case ICK_Floating_Integral:
329235633Sdim    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330235633Sdim      return NK_Type_Narrowing;
331235633Sdim    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
332235633Sdim      llvm::APSInt IntConstantValue;
333235633Sdim      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334235633Sdim      if (Initializer &&
335235633Sdim          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
336235633Sdim        // Convert the integer to the floating type.
337235633Sdim        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
338235633Sdim        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
339235633Sdim                                llvm::APFloat::rmNearestTiesToEven);
340235633Sdim        // And back.
341235633Sdim        llvm::APSInt ConvertedValue = IntConstantValue;
342235633Sdim        bool ignored;
343235633Sdim        Result.convertToInteger(ConvertedValue,
344235633Sdim                                llvm::APFloat::rmTowardZero, &ignored);
345235633Sdim        // If the resulting value is different, this was a narrowing conversion.
346235633Sdim        if (IntConstantValue != ConvertedValue) {
347235633Sdim          ConstantValue = APValue(IntConstantValue);
348235633Sdim          ConstantType = Initializer->getType();
349235633Sdim          return NK_Constant_Narrowing;
350235633Sdim        }
351235633Sdim      } else {
352235633Sdim        // Variables are always narrowings.
353235633Sdim        return NK_Variable_Narrowing;
354235633Sdim      }
355235633Sdim    }
356235633Sdim    return NK_Not_Narrowing;
357235633Sdim
358235633Sdim  // -- from long double to double or float, or from double to float, except
359235633Sdim  //    where the source is a constant expression and the actual value after
360235633Sdim  //    conversion is within the range of values that can be represented (even
361235633Sdim  //    if it cannot be represented exactly), or
362235633Sdim  case ICK_Floating_Conversion:
363235633Sdim    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
364235633Sdim        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
365235633Sdim      // FromType is larger than ToType.
366235633Sdim      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
367235633Sdim      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
368235633Sdim        // Constant!
369235633Sdim        assert(ConstantValue.isFloat());
370235633Sdim        llvm::APFloat FloatVal = ConstantValue.getFloat();
371235633Sdim        // Convert the source value into the target type.
372235633Sdim        bool ignored;
373235633Sdim        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
374235633Sdim          Ctx.getFloatTypeSemantics(ToType),
375235633Sdim          llvm::APFloat::rmNearestTiesToEven, &ignored);
376235633Sdim        // If there was no overflow, the source value is within the range of
377235633Sdim        // values that can be represented.
378235633Sdim        if (ConvertStatus & llvm::APFloat::opOverflow) {
379235633Sdim          ConstantType = Initializer->getType();
380235633Sdim          return NK_Constant_Narrowing;
381235633Sdim        }
382235633Sdim      } else {
383235633Sdim        return NK_Variable_Narrowing;
384235633Sdim      }
385235633Sdim    }
386235633Sdim    return NK_Not_Narrowing;
387235633Sdim
388235633Sdim  // -- from an integer type or unscoped enumeration type to an integer type
389235633Sdim  //    that cannot represent all the values of the original type, except where
390235633Sdim  //    the source is a constant expression and the actual value after
391235633Sdim  //    conversion will fit into the target type and will produce the original
392235633Sdim  //    value when converted back to the original type.
393235633Sdim  case ICK_Boolean_Conversion:  // Bools are integers too.
394235633Sdim    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
395235633Sdim      // Boolean conversions can be from pointers and pointers to members
396235633Sdim      // [conv.bool], and those aren't considered narrowing conversions.
397235633Sdim      return NK_Not_Narrowing;
398235633Sdim    }  // Otherwise, fall through to the integral case.
399235633Sdim  case ICK_Integral_Conversion: {
400235633Sdim    assert(FromType->isIntegralOrUnscopedEnumerationType());
401235633Sdim    assert(ToType->isIntegralOrUnscopedEnumerationType());
402235633Sdim    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
403235633Sdim    const unsigned FromWidth = Ctx.getIntWidth(FromType);
404235633Sdim    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
405235633Sdim    const unsigned ToWidth = Ctx.getIntWidth(ToType);
406235633Sdim
407235633Sdim    if (FromWidth > ToWidth ||
408245431Sdim        (FromWidth == ToWidth && FromSigned != ToSigned) ||
409245431Sdim        (FromSigned && !ToSigned)) {
410235633Sdim      // Not all values of FromType can be represented in ToType.
411235633Sdim      llvm::APSInt InitializerValue;
412235633Sdim      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
413245431Sdim      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
414245431Sdim        // Such conversions on variables are always narrowing.
415245431Sdim        return NK_Variable_Narrowing;
416245431Sdim      }
417245431Sdim      bool Narrowing = false;
418245431Sdim      if (FromWidth < ToWidth) {
419245431Sdim        // Negative -> unsigned is narrowing. Otherwise, more bits is never
420245431Sdim        // narrowing.
421245431Sdim        if (InitializerValue.isSigned() && InitializerValue.isNegative())
422245431Sdim          Narrowing = true;
423245431Sdim      } else {
424235633Sdim        // Add a bit to the InitializerValue so we don't have to worry about
425235633Sdim        // signed vs. unsigned comparisons.
426235633Sdim        InitializerValue = InitializerValue.extend(
427235633Sdim          InitializerValue.getBitWidth() + 1);
428235633Sdim        // Convert the initializer to and from the target width and signed-ness.
429235633Sdim        llvm::APSInt ConvertedValue = InitializerValue;
430235633Sdim        ConvertedValue = ConvertedValue.trunc(ToWidth);
431235633Sdim        ConvertedValue.setIsSigned(ToSigned);
432235633Sdim        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
433235633Sdim        ConvertedValue.setIsSigned(InitializerValue.isSigned());
434235633Sdim        // If the result is different, this was a narrowing conversion.
435245431Sdim        if (ConvertedValue != InitializerValue)
436245431Sdim          Narrowing = true;
437235633Sdim      }
438245431Sdim      if (Narrowing) {
439245431Sdim        ConstantType = Initializer->getType();
440245431Sdim        ConstantValue = APValue(InitializerValue);
441245431Sdim        return NK_Constant_Narrowing;
442245431Sdim      }
443235633Sdim    }
444235633Sdim    return NK_Not_Narrowing;
445235633Sdim  }
446235633Sdim
447235633Sdim  default:
448235633Sdim    // Other kinds of conversions are not narrowings.
449235633Sdim    return NK_Not_Narrowing;
450235633Sdim  }
451235633Sdim}
452235633Sdim
453263509Sdim/// dump - Print this standard conversion sequence to standard
454193326Sed/// error. Useful for debugging overloading issues.
455263509Sdimvoid StandardConversionSequence::dump() const {
456226890Sdim  raw_ostream &OS = llvm::errs();
457193326Sed  bool PrintedSomething = false;
458193326Sed  if (First != ICK_Identity) {
459202879Srdivacky    OS << GetImplicitConversionName(First);
460193326Sed    PrintedSomething = true;
461193326Sed  }
462193326Sed
463193326Sed  if (Second != ICK_Identity) {
464193326Sed    if (PrintedSomething) {
465202879Srdivacky      OS << " -> ";
466193326Sed    }
467202879Srdivacky    OS << GetImplicitConversionName(Second);
468193326Sed
469193326Sed    if (CopyConstructor) {
470202879Srdivacky      OS << " (by copy constructor)";
471193326Sed    } else if (DirectBinding) {
472202879Srdivacky      OS << " (direct reference binding)";
473193326Sed    } else if (ReferenceBinding) {
474202879Srdivacky      OS << " (reference binding)";
475193326Sed    }
476193326Sed    PrintedSomething = true;
477193326Sed  }
478193326Sed
479193326Sed  if (Third != ICK_Identity) {
480193326Sed    if (PrintedSomething) {
481202879Srdivacky      OS << " -> ";
482193326Sed    }
483202879Srdivacky    OS << GetImplicitConversionName(Third);
484193326Sed    PrintedSomething = true;
485193326Sed  }
486193326Sed
487193326Sed  if (!PrintedSomething) {
488202879Srdivacky    OS << "No conversions required";
489193326Sed  }
490193326Sed}
491193326Sed
492263509Sdim/// dump - Print this user-defined conversion sequence to standard
493193326Sed/// error. Useful for debugging overloading issues.
494263509Sdimvoid UserDefinedConversionSequence::dump() const {
495226890Sdim  raw_ostream &OS = llvm::errs();
496193326Sed  if (Before.First || Before.Second || Before.Third) {
497263509Sdim    Before.dump();
498202879Srdivacky    OS << " -> ";
499193326Sed  }
500235633Sdim  if (ConversionFunction)
501235633Sdim    OS << '\'' << *ConversionFunction << '\'';
502235633Sdim  else
503235633Sdim    OS << "aggregate initialization";
504193326Sed  if (After.First || After.Second || After.Third) {
505202879Srdivacky    OS << " -> ";
506263509Sdim    After.dump();
507193326Sed  }
508193326Sed}
509193326Sed
510263509Sdim/// dump - Print this implicit conversion sequence to standard
511193326Sed/// error. Useful for debugging overloading issues.
512263509Sdimvoid ImplicitConversionSequence::dump() const {
513226890Sdim  raw_ostream &OS = llvm::errs();
514263509Sdim  if (isStdInitializerListElement())
515263509Sdim    OS << "Worst std::initializer_list element conversion: ";
516193326Sed  switch (ConversionKind) {
517193326Sed  case StandardConversion:
518202879Srdivacky    OS << "Standard conversion: ";
519263509Sdim    Standard.dump();
520193326Sed    break;
521193326Sed  case UserDefinedConversion:
522202879Srdivacky    OS << "User-defined conversion: ";
523263509Sdim    UserDefined.dump();
524193326Sed    break;
525193326Sed  case EllipsisConversion:
526202879Srdivacky    OS << "Ellipsis conversion";
527193326Sed    break;
528202379Srdivacky  case AmbiguousConversion:
529202879Srdivacky    OS << "Ambiguous conversion";
530202379Srdivacky    break;
531193326Sed  case BadConversion:
532202879Srdivacky    OS << "Bad conversion";
533193326Sed    break;
534193326Sed  }
535193326Sed
536202879Srdivacky  OS << "\n";
537193326Sed}
538193326Sed
539202379Srdivackyvoid AmbiguousConversionSequence::construct() {
540202379Srdivacky  new (&conversions()) ConversionSet();
541202379Srdivacky}
542202379Srdivacky
543202379Srdivackyvoid AmbiguousConversionSequence::destruct() {
544202379Srdivacky  conversions().~ConversionSet();
545202379Srdivacky}
546202379Srdivacky
547202379Srdivackyvoid
548202379SrdivackyAmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
549202379Srdivacky  FromTypePtr = O.FromTypePtr;
550202379Srdivacky  ToTypePtr = O.ToTypePtr;
551202379Srdivacky  new (&conversions()) ConversionSet(O.conversions());
552202379Srdivacky}
553202379Srdivacky
554208600Srdivackynamespace {
555263509Sdim  // Structure used by DeductionFailureInfo to store
556252723Sdim  // template argument information.
557252723Sdim  struct DFIArguments {
558208600Srdivacky    TemplateArgument FirstArg;
559208600Srdivacky    TemplateArgument SecondArg;
560208600Srdivacky  };
561263509Sdim  // Structure used by DeductionFailureInfo to store
562252723Sdim  // template parameter and template argument information.
563252723Sdim  struct DFIParamWithArguments : DFIArguments {
564252723Sdim    TemplateParameter Param;
565252723Sdim  };
566208600Srdivacky}
567218893Sdim
568208600Srdivacky/// \brief Convert from Sema's representation of template deduction information
569208600Srdivacky/// to the form used in overload-candidate information.
570263509SdimDeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
571263509Sdim                                              Sema::TemplateDeductionResult TDK,
572263509Sdim                                              TemplateDeductionInfo &Info) {
573263509Sdim  DeductionFailureInfo Result;
574208600Srdivacky  Result.Result = static_cast<unsigned>(TDK);
575245431Sdim  Result.HasDiagnostic = false;
576208600Srdivacky  Result.Data = 0;
577208600Srdivacky  switch (TDK) {
578208600Srdivacky  case Sema::TDK_Success:
579245431Sdim  case Sema::TDK_Invalid:
580208600Srdivacky  case Sema::TDK_InstantiationDepth:
581208600Srdivacky  case Sema::TDK_TooManyArguments:
582208600Srdivacky  case Sema::TDK_TooFewArguments:
583208600Srdivacky    break;
584218893Sdim
585208600Srdivacky  case Sema::TDK_Incomplete:
586208600Srdivacky  case Sema::TDK_InvalidExplicitArguments:
587208600Srdivacky    Result.Data = Info.Param.getOpaqueValue();
588208600Srdivacky    break;
589218893Sdim
590252723Sdim  case Sema::TDK_NonDeducedMismatch: {
591252723Sdim    // FIXME: Should allocate from normal heap so that we can free this later.
592252723Sdim    DFIArguments *Saved = new (Context) DFIArguments;
593252723Sdim    Saved->FirstArg = Info.FirstArg;
594252723Sdim    Saved->SecondArg = Info.SecondArg;
595252723Sdim    Result.Data = Saved;
596252723Sdim    break;
597252723Sdim  }
598252723Sdim
599208600Srdivacky  case Sema::TDK_Inconsistent:
600212904Sdim  case Sema::TDK_Underqualified: {
601208600Srdivacky    // FIXME: Should allocate from normal heap so that we can free this later.
602208600Srdivacky    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
603208600Srdivacky    Saved->Param = Info.Param;
604208600Srdivacky    Saved->FirstArg = Info.FirstArg;
605208600Srdivacky    Saved->SecondArg = Info.SecondArg;
606208600Srdivacky    Result.Data = Saved;
607208600Srdivacky    break;
608208600Srdivacky  }
609218893Sdim
610208600Srdivacky  case Sema::TDK_SubstitutionFailure:
611208600Srdivacky    Result.Data = Info.take();
612245431Sdim    if (Info.hasSFINAEDiagnostic()) {
613245431Sdim      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614245431Sdim          SourceLocation(), PartialDiagnostic::NullDiagnostic());
615245431Sdim      Info.takeSFINAEDiagnostic(*Diag);
616245431Sdim      Result.HasDiagnostic = true;
617245431Sdim    }
618208600Srdivacky    break;
619218893Sdim
620208600Srdivacky  case Sema::TDK_FailedOverloadResolution:
621252723Sdim    Result.Data = Info.Expression;
622218893Sdim    break;
623252723Sdim
624252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
625252723Sdim    break;
626208600Srdivacky  }
627218893Sdim
628208600Srdivacky  return Result;
629208600Srdivacky}
630202379Srdivacky
631263509Sdimvoid DeductionFailureInfo::Destroy() {
632208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
633208600Srdivacky  case Sema::TDK_Success:
634245431Sdim  case Sema::TDK_Invalid:
635208600Srdivacky  case Sema::TDK_InstantiationDepth:
636208600Srdivacky  case Sema::TDK_Incomplete:
637208600Srdivacky  case Sema::TDK_TooManyArguments:
638208600Srdivacky  case Sema::TDK_TooFewArguments:
639208600Srdivacky  case Sema::TDK_InvalidExplicitArguments:
640252723Sdim  case Sema::TDK_FailedOverloadResolution:
641208600Srdivacky    break;
642218893Sdim
643208600Srdivacky  case Sema::TDK_Inconsistent:
644212904Sdim  case Sema::TDK_Underqualified:
645252723Sdim  case Sema::TDK_NonDeducedMismatch:
646208600Srdivacky    // FIXME: Destroy the data?
647208600Srdivacky    Data = 0;
648208600Srdivacky    break;
649208600Srdivacky
650208600Srdivacky  case Sema::TDK_SubstitutionFailure:
651245431Sdim    // FIXME: Destroy the template argument list?
652208600Srdivacky    Data = 0;
653245431Sdim    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
654245431Sdim      Diag->~PartialDiagnosticAt();
655245431Sdim      HasDiagnostic = false;
656245431Sdim    }
657208600Srdivacky    break;
658218893Sdim
659208600Srdivacky  // Unhandled
660252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
661208600Srdivacky    break;
662208600Srdivacky  }
663208600Srdivacky}
664218893Sdim
665263509SdimPartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
666245431Sdim  if (HasDiagnostic)
667245431Sdim    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
668245431Sdim  return 0;
669245431Sdim}
670245431Sdim
671263509SdimTemplateParameter DeductionFailureInfo::getTemplateParameter() {
672208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
673208600Srdivacky  case Sema::TDK_Success:
674245431Sdim  case Sema::TDK_Invalid:
675208600Srdivacky  case Sema::TDK_InstantiationDepth:
676208600Srdivacky  case Sema::TDK_TooManyArguments:
677208600Srdivacky  case Sema::TDK_TooFewArguments:
678208600Srdivacky  case Sema::TDK_SubstitutionFailure:
679252723Sdim  case Sema::TDK_NonDeducedMismatch:
680252723Sdim  case Sema::TDK_FailedOverloadResolution:
681208600Srdivacky    return TemplateParameter();
682218893Sdim
683208600Srdivacky  case Sema::TDK_Incomplete:
684208600Srdivacky  case Sema::TDK_InvalidExplicitArguments:
685218893Sdim    return TemplateParameter::getFromOpaqueValue(Data);
686208600Srdivacky
687208600Srdivacky  case Sema::TDK_Inconsistent:
688212904Sdim  case Sema::TDK_Underqualified:
689208600Srdivacky    return static_cast<DFIParamWithArguments*>(Data)->Param;
690218893Sdim
691208600Srdivacky  // Unhandled
692252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
693208600Srdivacky    break;
694208600Srdivacky  }
695218893Sdim
696208600Srdivacky  return TemplateParameter();
697208600Srdivacky}
698218893Sdim
699263509SdimTemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
700208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701252723Sdim  case Sema::TDK_Success:
702252723Sdim  case Sema::TDK_Invalid:
703252723Sdim  case Sema::TDK_InstantiationDepth:
704252723Sdim  case Sema::TDK_TooManyArguments:
705252723Sdim  case Sema::TDK_TooFewArguments:
706252723Sdim  case Sema::TDK_Incomplete:
707252723Sdim  case Sema::TDK_InvalidExplicitArguments:
708252723Sdim  case Sema::TDK_Inconsistent:
709252723Sdim  case Sema::TDK_Underqualified:
710252723Sdim  case Sema::TDK_NonDeducedMismatch:
711252723Sdim  case Sema::TDK_FailedOverloadResolution:
712252723Sdim    return 0;
713208600Srdivacky
714252723Sdim  case Sema::TDK_SubstitutionFailure:
715252723Sdim    return static_cast<TemplateArgumentList*>(Data);
716218893Sdim
717252723Sdim  // Unhandled
718252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
719252723Sdim    break;
720208600Srdivacky  }
721208600Srdivacky
722208600Srdivacky  return 0;
723208600Srdivacky}
724208600Srdivacky
725263509Sdimconst TemplateArgument *DeductionFailureInfo::getFirstArg() {
726208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727208600Srdivacky  case Sema::TDK_Success:
728245431Sdim  case Sema::TDK_Invalid:
729208600Srdivacky  case Sema::TDK_InstantiationDepth:
730208600Srdivacky  case Sema::TDK_Incomplete:
731208600Srdivacky  case Sema::TDK_TooManyArguments:
732208600Srdivacky  case Sema::TDK_TooFewArguments:
733208600Srdivacky  case Sema::TDK_InvalidExplicitArguments:
734208600Srdivacky  case Sema::TDK_SubstitutionFailure:
735252723Sdim  case Sema::TDK_FailedOverloadResolution:
736208600Srdivacky    return 0;
737208600Srdivacky
738208600Srdivacky  case Sema::TDK_Inconsistent:
739212904Sdim  case Sema::TDK_Underqualified:
740252723Sdim  case Sema::TDK_NonDeducedMismatch:
741252723Sdim    return &static_cast<DFIArguments*>(Data)->FirstArg;
742208600Srdivacky
743208600Srdivacky  // Unhandled
744252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
745208600Srdivacky    break;
746208600Srdivacky  }
747218893Sdim
748208600Srdivacky  return 0;
749218893Sdim}
750208600Srdivacky
751263509Sdimconst TemplateArgument *DeductionFailureInfo::getSecondArg() {
752208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
753208600Srdivacky  case Sema::TDK_Success:
754245431Sdim  case Sema::TDK_Invalid:
755208600Srdivacky  case Sema::TDK_InstantiationDepth:
756208600Srdivacky  case Sema::TDK_Incomplete:
757208600Srdivacky  case Sema::TDK_TooManyArguments:
758208600Srdivacky  case Sema::TDK_TooFewArguments:
759208600Srdivacky  case Sema::TDK_InvalidExplicitArguments:
760208600Srdivacky  case Sema::TDK_SubstitutionFailure:
761252723Sdim  case Sema::TDK_FailedOverloadResolution:
762208600Srdivacky    return 0;
763208600Srdivacky
764208600Srdivacky  case Sema::TDK_Inconsistent:
765212904Sdim  case Sema::TDK_Underqualified:
766252723Sdim  case Sema::TDK_NonDeducedMismatch:
767252723Sdim    return &static_cast<DFIArguments*>(Data)->SecondArg;
768208600Srdivacky
769208600Srdivacky  // Unhandled
770252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
771208600Srdivacky    break;
772208600Srdivacky  }
773218893Sdim
774208600Srdivacky  return 0;
775208600Srdivacky}
776208600Srdivacky
777263509SdimExpr *DeductionFailureInfo::getExpr() {
778252723Sdim  if (static_cast<Sema::TemplateDeductionResult>(Result) ==
779252723Sdim        Sema::TDK_FailedOverloadResolution)
780252723Sdim    return static_cast<Expr*>(Data);
781252723Sdim
782252723Sdim  return 0;
783252723Sdim}
784252723Sdim
785245431Sdimvoid OverloadCandidateSet::destroyCandidates() {
786245431Sdim  for (iterator i = begin(), e = end(); i != e; ++i) {
787235633Sdim    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
788235633Sdim      i->Conversions[ii].~ImplicitConversionSequence();
789245431Sdim    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
790245431Sdim      i->DeductionFailure.Destroy();
791245431Sdim  }
792245431Sdim}
793245431Sdim
794245431Sdimvoid OverloadCandidateSet::clear() {
795245431Sdim  destroyCandidates();
796235633Sdim  NumInlineSequences = 0;
797235633Sdim  Candidates.clear();
798208600Srdivacky  Functions.clear();
799208600Srdivacky}
800218893Sdim
801235633Sdimnamespace {
802235633Sdim  class UnbridgedCastsSet {
803235633Sdim    struct Entry {
804235633Sdim      Expr **Addr;
805235633Sdim      Expr *Saved;
806235633Sdim    };
807235633Sdim    SmallVector<Entry, 2> Entries;
808235633Sdim
809235633Sdim  public:
810235633Sdim    void save(Sema &S, Expr *&E) {
811235633Sdim      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
812235633Sdim      Entry entry = { &E, E };
813235633Sdim      Entries.push_back(entry);
814235633Sdim      E = S.stripARCUnbridgedCast(E);
815235633Sdim    }
816235633Sdim
817235633Sdim    void restore() {
818235633Sdim      for (SmallVectorImpl<Entry>::iterator
819235633Sdim             i = Entries.begin(), e = Entries.end(); i != e; ++i)
820235633Sdim        *i->Addr = i->Saved;
821235633Sdim    }
822235633Sdim  };
823235633Sdim}
824235633Sdim
825235633Sdim/// checkPlaceholderForOverload - Do any interesting placeholder-like
826235633Sdim/// preprocessing on the given expression.
827235633Sdim///
828235633Sdim/// \param unbridgedCasts a collection to which to add unbridged casts;
829235633Sdim///   without this, they will be immediately diagnosed as errors
830235633Sdim///
831235633Sdim/// Return true on unrecoverable error.
832235633Sdimstatic bool checkPlaceholderForOverload(Sema &S, Expr *&E,
833235633Sdim                                        UnbridgedCastsSet *unbridgedCasts = 0) {
834235633Sdim  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
835235633Sdim    // We can't handle overloaded expressions here because overload
836235633Sdim    // resolution might reasonably tweak them.
837235633Sdim    if (placeholder->getKind() == BuiltinType::Overload) return false;
838235633Sdim
839235633Sdim    // If the context potentially accepts unbridged ARC casts, strip
840235633Sdim    // the unbridged cast and add it to the collection for later restoration.
841235633Sdim    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
842235633Sdim        unbridgedCasts) {
843235633Sdim      unbridgedCasts->save(S, E);
844235633Sdim      return false;
845235633Sdim    }
846235633Sdim
847235633Sdim    // Go ahead and check everything else.
848235633Sdim    ExprResult result = S.CheckPlaceholderExpr(E);
849235633Sdim    if (result.isInvalid())
850235633Sdim      return true;
851235633Sdim
852235633Sdim    E = result.take();
853235633Sdim    return false;
854235633Sdim  }
855235633Sdim
856235633Sdim  // Nothing to do.
857235633Sdim  return false;
858235633Sdim}
859235633Sdim
860235633Sdim/// checkArgPlaceholdersForOverload - Check a set of call operands for
861235633Sdim/// placeholders.
862263509Sdimstatic bool checkArgPlaceholdersForOverload(Sema &S,
863263509Sdim                                            MultiExprArg Args,
864235633Sdim                                            UnbridgedCastsSet &unbridged) {
865263509Sdim  for (unsigned i = 0, e = Args.size(); i != e; ++i)
866263509Sdim    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
867235633Sdim      return true;
868235633Sdim
869235633Sdim  return false;
870235633Sdim}
871235633Sdim
872193326Sed// IsOverload - Determine whether the given New declaration is an
873200583Srdivacky// overload of the declarations in Old. This routine returns false if
874200583Srdivacky// New and Old cannot be overloaded, e.g., if New has the same
875200583Srdivacky// signature as some function in Old (C++ 1.3.10) or if the Old
876200583Srdivacky// declarations aren't functions (or function templates) at all. When
877200583Srdivacky// it does return false, MatchedDecl will point to the decl that New
878200583Srdivacky// cannot be overloaded with.  This decl may be a UsingShadowDecl on
879200583Srdivacky// top of the underlying declaration.
880193326Sed//
881193326Sed// Example: Given the following input:
882193326Sed//
883193326Sed//   void f(int, float); // #1
884193326Sed//   void f(int, int); // #2
885193326Sed//   int f(int, int); // #3
886193326Sed//
887193326Sed// When we process #1, there is no previous declaration of "f",
888198092Srdivacky// so IsOverload will not be used.
889193326Sed//
890200583Srdivacky// When we process #2, Old contains only the FunctionDecl for #1.  By
891200583Srdivacky// comparing the parameter types, we see that #1 and #2 are overloaded
892200583Srdivacky// (since they have different signatures), so this routine returns
893200583Srdivacky// false; MatchedDecl is unchanged.
894193326Sed//
895200583Srdivacky// When we process #3, Old is an overload set containing #1 and #2. We
896200583Srdivacky// compare the signatures of #3 to #1 (they're overloaded, so we do
897200583Srdivacky// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
898200583Srdivacky// identical (return types of functions are not part of the
899193326Sed// signature), IsOverload returns false and MatchedDecl will be set to
900193326Sed// point to the FunctionDecl for #2.
901210299Sed//
902210299Sed// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
903210299Sed// into a class by a using declaration.  The rules for whether to hide
904210299Sed// shadow declarations ignore some properties which otherwise figure
905210299Sed// into a function template's signature.
906200583SrdivackySema::OverloadKind
907210299SedSema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
908210299Sed                    NamedDecl *&Match, bool NewIsUsingDecl) {
909200583Srdivacky  for (LookupResult::iterator I = Old.begin(), E = Old.end();
910199512Srdivacky         I != E; ++I) {
911210299Sed    NamedDecl *OldD = *I;
912210299Sed
913210299Sed    bool OldIsUsingDecl = false;
914210299Sed    if (isa<UsingShadowDecl>(OldD)) {
915210299Sed      OldIsUsingDecl = true;
916210299Sed
917210299Sed      // We can always introduce two using declarations into the same
918210299Sed      // context, even if they have identical signatures.
919210299Sed      if (NewIsUsingDecl) continue;
920210299Sed
921210299Sed      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
922210299Sed    }
923210299Sed
924210299Sed    // If either declaration was introduced by a using declaration,
925210299Sed    // we'll need to use slightly different rules for matching.
926210299Sed    // Essentially, these rules are the normal rules, except that
927210299Sed    // function templates hide function templates with different
928210299Sed    // return types or template parameter lists.
929210299Sed    bool UseMemberUsingDeclRules =
930252723Sdim      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
931252723Sdim      !New->getFriendObjectKind();
932210299Sed
933200583Srdivacky    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
934210299Sed      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
935210299Sed        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
936210299Sed          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
937210299Sed          continue;
938210299Sed        }
939210299Sed
940200583Srdivacky        Match = *I;
941200583Srdivacky        return Ovl_Match;
942193326Sed      }
943200583Srdivacky    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
944210299Sed      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
945210299Sed        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
946210299Sed          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
947210299Sed          continue;
948210299Sed        }
949210299Sed
950252723Sdim        if (!shouldLinkPossiblyHiddenDecl(*I, New))
951252723Sdim          continue;
952252723Sdim
953200583Srdivacky        Match = *I;
954200583Srdivacky        return Ovl_Match;
955199512Srdivacky      }
956218893Sdim    } else if (isa<UsingDecl>(OldD)) {
957200583Srdivacky      // We can overload with these, which can show up when doing
958200583Srdivacky      // redeclaration checks for UsingDecls.
959200583Srdivacky      assert(Old.getLookupKind() == LookupUsingDeclName);
960218893Sdim    } else if (isa<TagDecl>(OldD)) {
961218893Sdim      // We can always overload with tags by hiding them.
962200583Srdivacky    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
963200583Srdivacky      // Optimistically assume that an unresolved using decl will
964200583Srdivacky      // overload; if it doesn't, we'll have to diagnose during
965200583Srdivacky      // template instantiation.
966199512Srdivacky    } else {
967199512Srdivacky      // (C++ 13p1):
968199512Srdivacky      //   Only function declarations can be overloaded; object and type
969199512Srdivacky      //   declarations cannot be overloaded.
970200583Srdivacky      Match = *I;
971200583Srdivacky      return Ovl_NonFunction;
972193326Sed    }
973199512Srdivacky  }
974193326Sed
975200583Srdivacky  return Ovl_Overload;
976199512Srdivacky}
977198092Srdivacky
978263509Sdimbool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
979263509Sdim                      bool UseUsingDeclRules) {
980263509Sdim  // C++ [basic.start.main]p2: This function shall not be overloaded.
981263509Sdim  if (New->isMain())
982212904Sdim    return false;
983212904Sdim
984263509Sdim  // MSVCRT user defined entry points cannot be overloaded.
985263509Sdim  if (New->isMSVCRTEntryPoint())
986252723Sdim    return false;
987252723Sdim
988199512Srdivacky  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989199512Srdivacky  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
990195099Sed
991199512Srdivacky  // C++ [temp.fct]p2:
992199512Srdivacky  //   A function template can be overloaded with other function templates
993199512Srdivacky  //   and with normal (non-template) functions.
994199512Srdivacky  if ((OldTemplate == 0) != (NewTemplate == 0))
995199512Srdivacky    return true;
996193326Sed
997199512Srdivacky  // Is the function New an overload of the function Old?
998263509Sdim  QualType OldQType = Context.getCanonicalType(Old->getType());
999263509Sdim  QualType NewQType = Context.getCanonicalType(New->getType());
1000193326Sed
1001199512Srdivacky  // Compare the signatures (C++ 1.3.10) of the two functions to
1002199512Srdivacky  // determine whether they are overloads. If we find any mismatch
1003199512Srdivacky  // in the signature, they are overloads.
1004193326Sed
1005199512Srdivacky  // If either of these functions is a K&R-style function (no
1006199512Srdivacky  // prototype), then we consider them to have matching signatures.
1007199512Srdivacky  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008199512Srdivacky      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1009199512Srdivacky    return false;
1010193326Sed
1011218893Sdim  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1012218893Sdim  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1013193326Sed
1014199512Srdivacky  // The signature of a function includes the types of its
1015199512Srdivacky  // parameters (C++ 1.3.10), which includes the presence or absence
1016199512Srdivacky  // of the ellipsis; see C++ DR 357).
1017199512Srdivacky  if (OldQType != NewQType &&
1018199512Srdivacky      (OldType->getNumArgs() != NewType->getNumArgs() ||
1019199512Srdivacky       OldType->isVariadic() != NewType->isVariadic() ||
1020263509Sdim       !FunctionArgTypesAreEqual(OldType, NewType)))
1021199512Srdivacky    return true;
1022198092Srdivacky
1023199512Srdivacky  // C++ [temp.over.link]p4:
1024199512Srdivacky  //   The signature of a function template consists of its function
1025199512Srdivacky  //   signature, its return type and its template parameter list. The names
1026199512Srdivacky  //   of the template parameters are significant only for establishing the
1027199512Srdivacky  //   relationship between the template parameters and the rest of the
1028199512Srdivacky  //   signature.
1029199512Srdivacky  //
1030199512Srdivacky  // We check the return type and template parameter lists for function
1031199512Srdivacky  // templates first; the remaining checks follow.
1032210299Sed  //
1033210299Sed  // However, we don't consider either of these when deciding whether
1034210299Sed  // a member introduced by a shadow declaration is hidden.
1035210299Sed  if (!UseUsingDeclRules && NewTemplate &&
1036263509Sdim      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037263509Sdim                                       OldTemplate->getTemplateParameters(),
1038263509Sdim                                       false, TPL_TemplateMatch) ||
1039199512Srdivacky       OldType->getResultType() != NewType->getResultType()))
1040199512Srdivacky    return true;
1041193326Sed
1042199512Srdivacky  // If the function is a class member, its signature includes the
1043218893Sdim  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1044199512Srdivacky  //
1045199512Srdivacky  // As part of this, also check whether one of the member functions
1046199512Srdivacky  // is static, in which case they are not overloads (C++
1047199512Srdivacky  // 13.1p2). While not part of the definition of the signature,
1048199512Srdivacky  // this check is important to determine whether these functions
1049199512Srdivacky  // can be overloaded.
1050252723Sdim  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051252723Sdim  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1052199512Srdivacky  if (OldMethod && NewMethod &&
1053252723Sdim      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054252723Sdim    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055252723Sdim      if (!UseUsingDeclRules &&
1056252723Sdim          (OldMethod->getRefQualifier() == RQ_None ||
1057252723Sdim           NewMethod->getRefQualifier() == RQ_None)) {
1058252723Sdim        // C++0x [over.load]p2:
1059252723Sdim        //   - Member function declarations with the same name and the same
1060252723Sdim        //     parameter-type-list as well as member function template
1061252723Sdim        //     declarations with the same name, the same parameter-type-list, and
1062252723Sdim        //     the same template parameter lists cannot be overloaded if any of
1063252723Sdim        //     them, but not all, have a ref-qualifier (8.3.5).
1064263509Sdim        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1065252723Sdim          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1066263509Sdim        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1067252723Sdim      }
1068252723Sdim      return true;
1069218893Sdim    }
1070218893Sdim
1071252723Sdim    // We may not have applied the implicit const for a constexpr member
1072252723Sdim    // function yet (because we haven't yet resolved whether this is a static
1073252723Sdim    // or non-static member function). Add it now, on the assumption that this
1074252723Sdim    // is a redeclaration of OldMethod.
1075263509Sdim    unsigned OldQuals = OldMethod->getTypeQualifiers();
1076252723Sdim    unsigned NewQuals = NewMethod->getTypeQualifiers();
1077263509Sdim    if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1078263509Sdim        !isa<CXXConstructorDecl>(NewMethod))
1079252723Sdim      NewQuals |= Qualifiers::Const;
1080263509Sdim
1081263509Sdim    // We do not allow overloading based off of '__restrict'.
1082263509Sdim    OldQuals &= ~Qualifiers::Restrict;
1083263509Sdim    NewQuals &= ~Qualifiers::Restrict;
1084263509Sdim    if (OldQuals != NewQuals)
1085252723Sdim      return true;
1086218893Sdim  }
1087218893Sdim
1088199512Srdivacky  // The signatures match; this is not an overload.
1089199512Srdivacky  return false;
1090193326Sed}
1091193326Sed
1092224145Sdim/// \brief Checks availability of the function depending on the current
1093224145Sdim/// function context. Inside an unavailable function, unavailability is ignored.
1094224145Sdim///
1095224145Sdim/// \returns true if \arg FD is unavailable and current context is inside
1096224145Sdim/// an available function, false otherwise.
1097224145Sdimbool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1098224145Sdim  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1099224145Sdim}
1100224145Sdim
1101235633Sdim/// \brief Tries a user-defined conversion from From to ToType.
1102235633Sdim///
1103235633Sdim/// Produces an implicit conversion sequence for when a standard conversion
1104235633Sdim/// is not an option. See TryImplicitConversion for more information.
1105235633Sdimstatic ImplicitConversionSequence
1106235633SdimTryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1107235633Sdim                         bool SuppressUserConversions,
1108235633Sdim                         bool AllowExplicit,
1109235633Sdim                         bool InOverloadResolution,
1110235633Sdim                         bool CStyle,
1111263509Sdim                         bool AllowObjCWritebackConversion,
1112263509Sdim                         bool AllowObjCConversionOnExplicit) {
1113235633Sdim  ImplicitConversionSequence ICS;
1114235633Sdim
1115235633Sdim  if (SuppressUserConversions) {
1116235633Sdim    // We're not in the case above, so there is no conversion that
1117235633Sdim    // we can perform.
1118235633Sdim    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1119235633Sdim    return ICS;
1120235633Sdim  }
1121235633Sdim
1122235633Sdim  // Attempt user-defined conversion.
1123235633Sdim  OverloadCandidateSet Conversions(From->getExprLoc());
1124235633Sdim  OverloadingResult UserDefResult
1125235633Sdim    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1126263509Sdim                              AllowExplicit, AllowObjCConversionOnExplicit);
1127235633Sdim
1128235633Sdim  if (UserDefResult == OR_Success) {
1129235633Sdim    ICS.setUserDefined();
1130235633Sdim    // C++ [over.ics.user]p4:
1131235633Sdim    //   A conversion of an expression of class type to the same class
1132235633Sdim    //   type is given Exact Match rank, and a conversion of an
1133235633Sdim    //   expression of class type to a base class of that type is
1134235633Sdim    //   given Conversion rank, in spite of the fact that a copy
1135235633Sdim    //   constructor (i.e., a user-defined conversion function) is
1136235633Sdim    //   called for those cases.
1137235633Sdim    if (CXXConstructorDecl *Constructor
1138235633Sdim          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1139235633Sdim      QualType FromCanon
1140235633Sdim        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1141235633Sdim      QualType ToCanon
1142235633Sdim        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1143235633Sdim      if (Constructor->isCopyConstructor() &&
1144235633Sdim          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1145235633Sdim        // Turn this into a "standard" conversion sequence, so that it
1146235633Sdim        // gets ranked with standard conversion sequences.
1147235633Sdim        ICS.setStandard();
1148235633Sdim        ICS.Standard.setAsIdentityConversion();
1149235633Sdim        ICS.Standard.setFromType(From->getType());
1150235633Sdim        ICS.Standard.setAllToTypes(ToType);
1151235633Sdim        ICS.Standard.CopyConstructor = Constructor;
1152235633Sdim        if (ToCanon != FromCanon)
1153235633Sdim          ICS.Standard.Second = ICK_Derived_To_Base;
1154235633Sdim      }
1155235633Sdim    }
1156235633Sdim
1157235633Sdim    // C++ [over.best.ics]p4:
1158235633Sdim    //   However, when considering the argument of a user-defined
1159235633Sdim    //   conversion function that is a candidate by 13.3.1.3 when
1160235633Sdim    //   invoked for the copying of the temporary in the second step
1161235633Sdim    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1162235633Sdim    //   13.3.1.6 in all cases, only standard conversion sequences and
1163235633Sdim    //   ellipsis conversion sequences are allowed.
1164235633Sdim    if (SuppressUserConversions && ICS.isUserDefined()) {
1165235633Sdim      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1166235633Sdim    }
1167235633Sdim  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1168235633Sdim    ICS.setAmbiguous();
1169235633Sdim    ICS.Ambiguous.setFromType(From->getType());
1170235633Sdim    ICS.Ambiguous.setToType(ToType);
1171235633Sdim    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172235633Sdim         Cand != Conversions.end(); ++Cand)
1173235633Sdim      if (Cand->Viable)
1174235633Sdim        ICS.Ambiguous.addConversion(Cand->Function);
1175235633Sdim  } else {
1176235633Sdim    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1177235633Sdim  }
1178235633Sdim
1179235633Sdim  return ICS;
1180235633Sdim}
1181235633Sdim
1182193326Sed/// TryImplicitConversion - Attempt to perform an implicit conversion
1183193326Sed/// from the given expression (Expr) to the given type (ToType). This
1184193326Sed/// function returns an implicit conversion sequence that can be used
1185193326Sed/// to perform the initialization. Given
1186193326Sed///
1187193326Sed///   void f(float f);
1188193326Sed///   void g(int i) { f(i); }
1189193326Sed///
1190193326Sed/// this routine would produce an implicit conversion sequence to
1191193326Sed/// describe the initialization of f from i, which will be a standard
1192193326Sed/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1193193326Sed/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1194193326Sed//
1195193326Sed/// Note that this routine only determines how the conversion can be
1196193326Sed/// performed; it does not actually perform the conversion. As such,
1197193326Sed/// it will not produce any diagnostics if no conversion is available,
1198193326Sed/// but will instead return an implicit conversion sequence of kind
1199193326Sed/// "BadConversion".
1200193326Sed///
1201193326Sed/// If @p SuppressUserConversions, then user-defined conversions are
1202193326Sed/// not permitted.
1203193326Sed/// If @p AllowExplicit, then explicit user-defined conversions are
1204193326Sed/// permitted.
1205224145Sdim///
1206224145Sdim/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1207224145Sdim/// writeback conversion, which allows __autoreleasing id* parameters to
1208224145Sdim/// be initialized with __strong id* or __weak id* arguments.
1209212904Sdimstatic ImplicitConversionSequence
1210212904SdimTryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1211212904Sdim                      bool SuppressUserConversions,
1212218893Sdim                      bool AllowExplicit,
1213218893Sdim                      bool InOverloadResolution,
1214224145Sdim                      bool CStyle,
1215263509Sdim                      bool AllowObjCWritebackConversion,
1216263509Sdim                      bool AllowObjCConversionOnExplicit) {
1217193326Sed  ImplicitConversionSequence ICS;
1218212904Sdim  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1219224145Sdim                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1220202379Srdivacky    ICS.setStandard();
1221203955Srdivacky    return ICS;
1222203955Srdivacky  }
1223203955Srdivacky
1224235633Sdim  if (!S.getLangOpts().CPlusPlus) {
1225204643Srdivacky    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1226203955Srdivacky    return ICS;
1227203955Srdivacky  }
1228203955Srdivacky
1229212904Sdim  // C++ [over.ics.user]p4:
1230212904Sdim  //   A conversion of an expression of class type to the same class
1231212904Sdim  //   type is given Exact Match rank, and a conversion of an
1232212904Sdim  //   expression of class type to a base class of that type is
1233212904Sdim  //   given Conversion rank, in spite of the fact that a copy/move
1234212904Sdim  //   constructor (i.e., a user-defined conversion function) is
1235212904Sdim  //   called for those cases.
1236212904Sdim  QualType FromType = From->getType();
1237212904Sdim  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1238212904Sdim      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1239212904Sdim       S.IsDerivedFrom(FromType, ToType))) {
1240207619Srdivacky    ICS.setStandard();
1241207619Srdivacky    ICS.Standard.setAsIdentityConversion();
1242207619Srdivacky    ICS.Standard.setFromType(FromType);
1243207619Srdivacky    ICS.Standard.setAllToTypes(ToType);
1244218893Sdim
1245207619Srdivacky    // We don't actually check at this point whether there is a valid
1246207619Srdivacky    // copy/move constructor, since overloading just assumes that it
1247207619Srdivacky    // exists. When we actually perform initialization, we'll find the
1248207619Srdivacky    // appropriate constructor to copy the returned object, if needed.
1249207619Srdivacky    ICS.Standard.CopyConstructor = 0;
1250218893Sdim
1251207619Srdivacky    // Determine whether this is considered a derived-to-base conversion.
1252212904Sdim    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1253207619Srdivacky      ICS.Standard.Second = ICK_Derived_To_Base;
1254218893Sdim
1255207619Srdivacky    return ICS;
1256207619Srdivacky  }
1257218893Sdim
1258235633Sdim  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1259235633Sdim                                  AllowExplicit, InOverloadResolution, CStyle,
1260263509Sdim                                  AllowObjCWritebackConversion,
1261263509Sdim                                  AllowObjCConversionOnExplicit);
1262193326Sed}
1263193326Sed
1264224145SdimImplicitConversionSequence
1265224145SdimSema::TryImplicitConversion(Expr *From, QualType ToType,
1266224145Sdim                            bool SuppressUserConversions,
1267224145Sdim                            bool AllowExplicit,
1268224145Sdim                            bool InOverloadResolution,
1269224145Sdim                            bool CStyle,
1270224145Sdim                            bool AllowObjCWritebackConversion) {
1271224145Sdim  return clang::TryImplicitConversion(*this, From, ToType,
1272224145Sdim                                      SuppressUserConversions, AllowExplicit,
1273224145Sdim                                      InOverloadResolution, CStyle,
1274263509Sdim                                      AllowObjCWritebackConversion,
1275263509Sdim                                      /*AllowObjCConversionOnExplicit=*/false);
1276212904Sdim}
1277212904Sdim
1278207619Srdivacky/// PerformImplicitConversion - Perform an implicit conversion of the
1279221345Sdim/// expression From to the type ToType. Returns the
1280207619Srdivacky/// converted expression. Flavor is the kind of conversion we're
1281207619Srdivacky/// performing, used in the error message. If @p AllowExplicit,
1282207619Srdivacky/// explicit user-defined conversions are permitted.
1283221345SdimExprResult
1284221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType,
1285235633Sdim                                AssignmentAction Action, bool AllowExplicit) {
1286207619Srdivacky  ImplicitConversionSequence ICS;
1287235633Sdim  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1288207619Srdivacky}
1289207619Srdivacky
1290221345SdimExprResult
1291221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType,
1292207619Srdivacky                                AssignmentAction Action, bool AllowExplicit,
1293235633Sdim                                ImplicitConversionSequence& ICS) {
1294235633Sdim  if (checkPlaceholderForOverload(*this, From))
1295235633Sdim    return ExprError();
1296235633Sdim
1297224145Sdim  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1298224145Sdim  bool AllowObjCWritebackConversion
1299235633Sdim    = getLangOpts().ObjCAutoRefCount &&
1300224145Sdim      (Action == AA_Passing || Action == AA_Sending);
1301224145Sdim
1302212904Sdim  ICS = clang::TryImplicitConversion(*this, From, ToType,
1303212904Sdim                                     /*SuppressUserConversions=*/false,
1304212904Sdim                                     AllowExplicit,
1305218893Sdim                                     /*InOverloadResolution=*/false,
1306224145Sdim                                     /*CStyle=*/false,
1307263509Sdim                                     AllowObjCWritebackConversion,
1308263509Sdim                                     /*AllowObjCConversionOnExplicit=*/false);
1309207619Srdivacky  return PerformImplicitConversion(From, ToType, ICS, Action);
1310207619Srdivacky}
1311218893Sdim
1312218893Sdim/// \brief Determine whether the conversion from FromType to ToType is a valid
1313200583Srdivacky/// conversion that strips "noreturn" off the nested function type.
1314224145Sdimbool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1315224145Sdim                                QualType &ResultTy) {
1316200583Srdivacky  if (Context.hasSameUnqualifiedType(FromType, ToType))
1317200583Srdivacky    return false;
1318200583Srdivacky
1319218893Sdim  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1320218893Sdim  // where F adds one of the following at most once:
1321218893Sdim  //   - a pointer
1322218893Sdim  //   - a member pointer
1323218893Sdim  //   - a block pointer
1324218893Sdim  CanQualType CanTo = Context.getCanonicalType(ToType);
1325218893Sdim  CanQualType CanFrom = Context.getCanonicalType(FromType);
1326218893Sdim  Type::TypeClass TyClass = CanTo->getTypeClass();
1327218893Sdim  if (TyClass != CanFrom->getTypeClass()) return false;
1328218893Sdim  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1329218893Sdim    if (TyClass == Type::Pointer) {
1330218893Sdim      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1331218893Sdim      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1332218893Sdim    } else if (TyClass == Type::BlockPointer) {
1333218893Sdim      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1334218893Sdim      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1335218893Sdim    } else if (TyClass == Type::MemberPointer) {
1336218893Sdim      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1337218893Sdim      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1338218893Sdim    } else {
1339218893Sdim      return false;
1340218893Sdim    }
1341218893Sdim
1342218893Sdim    TyClass = CanTo->getTypeClass();
1343218893Sdim    if (TyClass != CanFrom->getTypeClass()) return false;
1344218893Sdim    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1345218893Sdim      return false;
1346218893Sdim  }
1347218893Sdim
1348218893Sdim  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1349218893Sdim  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1350218893Sdim  if (!EInfo.getNoReturn()) return false;
1351218893Sdim
1352218893Sdim  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1353218893Sdim  assert(QualType(FromFn, 0).isCanonical());
1354218893Sdim  if (QualType(FromFn, 0) != CanTo) return false;
1355218893Sdim
1356218893Sdim  ResultTy = ToType;
1357200583Srdivacky  return true;
1358200583Srdivacky}
1359218893Sdim
1360208600Srdivacky/// \brief Determine whether the conversion from FromType to ToType is a valid
1361208600Srdivacky/// vector conversion.
1362208600Srdivacky///
1363208600Srdivacky/// \param ICK Will be set to the vector conversion kind, if this is a vector
1364208600Srdivacky/// conversion.
1365218893Sdimstatic bool IsVectorConversion(ASTContext &Context, QualType FromType,
1366218893Sdim                               QualType ToType, ImplicitConversionKind &ICK) {
1367208600Srdivacky  // We need at least one of these types to be a vector type to have a vector
1368208600Srdivacky  // conversion.
1369208600Srdivacky  if (!ToType->isVectorType() && !FromType->isVectorType())
1370208600Srdivacky    return false;
1371208600Srdivacky
1372208600Srdivacky  // Identical types require no conversions.
1373208600Srdivacky  if (Context.hasSameUnqualifiedType(FromType, ToType))
1374208600Srdivacky    return false;
1375208600Srdivacky
1376208600Srdivacky  // There are no conversions between extended vector types, only identity.
1377208600Srdivacky  if (ToType->isExtVectorType()) {
1378208600Srdivacky    // There are no conversions between extended vector types other than the
1379208600Srdivacky    // identity conversion.
1380208600Srdivacky    if (FromType->isExtVectorType())
1381208600Srdivacky      return false;
1382218893Sdim
1383208600Srdivacky    // Vector splat from any arithmetic type to a vector.
1384210299Sed    if (FromType->isArithmeticType()) {
1385208600Srdivacky      ICK = ICK_Vector_Splat;
1386208600Srdivacky      return true;
1387208600Srdivacky    }
1388208600Srdivacky  }
1389212904Sdim
1390212904Sdim  // We can perform the conversion between vector types in the following cases:
1391212904Sdim  // 1)vector types are equivalent AltiVec and GCC vector types
1392212904Sdim  // 2)lax vector conversions are permitted and the vector types are of the
1393212904Sdim  //   same size
1394212904Sdim  if (ToType->isVectorType() && FromType->isVectorType()) {
1395212904Sdim    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1396235633Sdim        (Context.getLangOpts().LaxVectorConversions &&
1397212904Sdim         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1398212904Sdim      ICK = ICK_Vector_Conversion;
1399212904Sdim      return true;
1400212904Sdim    }
1401208600Srdivacky  }
1402212904Sdim
1403208600Srdivacky  return false;
1404208600Srdivacky}
1405218893Sdim
1406235633Sdimstatic bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1407235633Sdim                                bool InOverloadResolution,
1408235633Sdim                                StandardConversionSequence &SCS,
1409235633Sdim                                bool CStyle);
1410235633Sdim
1411193326Sed/// IsStandardConversion - Determines whether there is a standard
1412193326Sed/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1413193326Sed/// expression From to the type ToType. Standard conversion sequences
1414193326Sed/// only consider non-class types; for conversions that involve class
1415193326Sed/// types, use TryImplicitConversion. If a conversion exists, SCS will
1416193326Sed/// contain the standard conversion sequence required to perform this
1417193326Sed/// conversion and this routine will return true. Otherwise, this
1418193326Sed/// routine will return false and the value of SCS is unspecified.
1419212904Sdimstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1420212904Sdim                                 bool InOverloadResolution,
1421218893Sdim                                 StandardConversionSequence &SCS,
1422224145Sdim                                 bool CStyle,
1423224145Sdim                                 bool AllowObjCWritebackConversion) {
1424193326Sed  QualType FromType = From->getType();
1425218893Sdim
1426193326Sed  // Standard conversions (C++ [conv])
1427193326Sed  SCS.setAsIdentityConversion();
1428204643Srdivacky  SCS.DeprecatedStringLiteralToCharPtr = false;
1429193326Sed  SCS.IncompatibleObjC = false;
1430202379Srdivacky  SCS.setFromType(FromType);
1431193326Sed  SCS.CopyConstructor = 0;
1432193326Sed
1433193326Sed  // There are no standard conversions for class types in C++, so
1434198092Srdivacky  // abort early. When overloading in C, however, we do permit
1435193326Sed  if (FromType->isRecordType() || ToType->isRecordType()) {
1436235633Sdim    if (S.getLangOpts().CPlusPlus)
1437193326Sed      return false;
1438193326Sed
1439198092Srdivacky    // When we're overloading in C, we allow, as standard conversions,
1440193326Sed  }
1441193326Sed
1442193326Sed  // The first conversion can be an lvalue-to-rvalue conversion,
1443193326Sed  // array-to-pointer conversion, or function-to-pointer conversion
1444193326Sed  // (C++ 4p1).
1445193326Sed
1446212904Sdim  if (FromType == S.Context.OverloadTy) {
1447207619Srdivacky    DeclAccessPair AccessPair;
1448207619Srdivacky    if (FunctionDecl *Fn
1449218893Sdim          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1450212904Sdim                                                 AccessPair)) {
1451207619Srdivacky      // We were able to resolve the address of the overloaded function,
1452207619Srdivacky      // so we can convert to the type of that function.
1453207619Srdivacky      FromType = Fn->getType();
1454218893Sdim
1455218893Sdim      // we can sometimes resolve &foo<int> regardless of ToType, so check
1456218893Sdim      // if the type matches (identity) or we are converting to bool
1457218893Sdim      if (!S.Context.hasSameUnqualifiedType(
1458218893Sdim                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1459218893Sdim        QualType resultTy;
1460218893Sdim        // if the function type matches except for [[noreturn]], it's ok
1461224145Sdim        if (!S.IsNoReturnConversion(FromType,
1462218893Sdim              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1463218893Sdim          // otherwise, only a boolean conversion is standard
1464218893Sdim          if (!ToType->isBooleanType())
1465218893Sdim            return false;
1466221345Sdim      }
1467218893Sdim
1468221345Sdim      // Check if the "from" expression is taking the address of an overloaded
1469221345Sdim      // function and recompute the FromType accordingly. Take advantage of the
1470221345Sdim      // fact that non-static member functions *must* have such an address-of
1471221345Sdim      // expression.
1472221345Sdim      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1473221345Sdim      if (Method && !Method->isStatic()) {
1474221345Sdim        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1475221345Sdim               "Non-unary operator on non-static member address");
1476221345Sdim        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1477221345Sdim               == UO_AddrOf &&
1478221345Sdim               "Non-address-of operator on non-static member address");
1479221345Sdim        const Type *ClassType
1480221345Sdim          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1481221345Sdim        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1482221345Sdim      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1483221345Sdim        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1484221345Sdim               UO_AddrOf &&
1485221345Sdim               "Non-address-of operator for overloaded function expression");
1486221345Sdim        FromType = S.Context.getPointerType(FromType);
1487218893Sdim      }
1488218893Sdim
1489207619Srdivacky      // Check that we've computed the proper type after overload resolution.
1490221345Sdim      assert(S.Context.hasSameType(
1491221345Sdim        FromType,
1492221345Sdim        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1493207619Srdivacky    } else {
1494207619Srdivacky      return false;
1495207619Srdivacky    }
1496218893Sdim  }
1497226890Sdim  // Lvalue-to-rvalue conversion (C++11 4.1):
1498226890Sdim  //   A glvalue (3.10) of a non-function, non-array type T can
1499226890Sdim  //   be converted to a prvalue.
1500226890Sdim  bool argIsLValue = From->isGLValue();
1501218893Sdim  if (argIsLValue &&
1502193326Sed      !FromType->isFunctionType() && !FromType->isArrayType() &&
1503212904Sdim      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1504193326Sed    SCS.First = ICK_Lvalue_To_Rvalue;
1505193326Sed
1506235633Sdim    // C11 6.3.2.1p2:
1507235633Sdim    //   ... if the lvalue has atomic type, the value has the non-atomic version
1508235633Sdim    //   of the type of the lvalue ...
1509235633Sdim    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1510235633Sdim      FromType = Atomic->getValueType();
1511235633Sdim
1512193326Sed    // If T is a non-class type, the type of the rvalue is the
1513193326Sed    // cv-unqualified version of T. Otherwise, the type of the rvalue
1514193326Sed    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1515193326Sed    // just strip the qualifiers because they don't matter.
1516193326Sed    FromType = FromType.getUnqualifiedType();
1517198092Srdivacky  } else if (FromType->isArrayType()) {
1518198092Srdivacky    // Array-to-pointer conversion (C++ 4.2)
1519193326Sed    SCS.First = ICK_Array_To_Pointer;
1520193326Sed
1521193326Sed    // An lvalue or rvalue of type "array of N T" or "array of unknown
1522193326Sed    // bound of T" can be converted to an rvalue of type "pointer to
1523193326Sed    // T" (C++ 4.2p1).
1524212904Sdim    FromType = S.Context.getArrayDecayedType(FromType);
1525193326Sed
1526212904Sdim    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1527193326Sed      // This conversion is deprecated. (C++ D.4).
1528204643Srdivacky      SCS.DeprecatedStringLiteralToCharPtr = true;
1529193326Sed
1530193326Sed      // For the purpose of ranking in overload resolution
1531193326Sed      // (13.3.3.1.1), this conversion is considered an
1532193326Sed      // array-to-pointer conversion followed by a qualification
1533193326Sed      // conversion (4.4). (C++ 4.2p2)
1534193326Sed      SCS.Second = ICK_Identity;
1535193326Sed      SCS.Third = ICK_Qualification;
1536224145Sdim      SCS.QualificationIncludesObjCLifetime = false;
1537203955Srdivacky      SCS.setAllToTypes(FromType);
1538193326Sed      return true;
1539193326Sed    }
1540218893Sdim  } else if (FromType->isFunctionType() && argIsLValue) {
1541198092Srdivacky    // Function-to-pointer conversion (C++ 4.3).
1542193326Sed    SCS.First = ICK_Function_To_Pointer;
1543193326Sed
1544193326Sed    // An lvalue of function type T can be converted to an rvalue of
1545193326Sed    // type "pointer to T." The result is a pointer to the
1546193326Sed    // function. (C++ 4.3p1).
1547212904Sdim    FromType = S.Context.getPointerType(FromType);
1548198092Srdivacky  } else {
1549198092Srdivacky    // We don't require any conversions for the first step.
1550193326Sed    SCS.First = ICK_Identity;
1551193326Sed  }
1552203955Srdivacky  SCS.setToType(0, FromType);
1553193326Sed
1554193326Sed  // The second conversion can be an integral promotion, floating
1555193326Sed  // point promotion, integral conversion, floating point conversion,
1556193326Sed  // floating-integral conversion, pointer conversion,
1557193326Sed  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1558193326Sed  // For overloading in C, this can also be a "compatible-type"
1559193326Sed  // conversion.
1560193326Sed  bool IncompatibleObjC = false;
1561208600Srdivacky  ImplicitConversionKind SecondICK = ICK_Identity;
1562212904Sdim  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1563193326Sed    // The unqualified versions of the types are the same: there's no
1564193326Sed    // conversion to do.
1565193326Sed    SCS.Second = ICK_Identity;
1566212904Sdim  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1567198092Srdivacky    // Integral promotion (C++ 4.5).
1568193326Sed    SCS.Second = ICK_Integral_Promotion;
1569193326Sed    FromType = ToType.getUnqualifiedType();
1570212904Sdim  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1571198092Srdivacky    // Floating point promotion (C++ 4.6).
1572193326Sed    SCS.Second = ICK_Floating_Promotion;
1573193326Sed    FromType = ToType.getUnqualifiedType();
1574212904Sdim  } else if (S.IsComplexPromotion(FromType, ToType)) {
1575198092Srdivacky    // Complex promotion (Clang extension)
1576193326Sed    SCS.Second = ICK_Complex_Promotion;
1577193326Sed    FromType = ToType.getUnqualifiedType();
1578218893Sdim  } else if (ToType->isBooleanType() &&
1579218893Sdim             (FromType->isArithmeticType() ||
1580218893Sdim              FromType->isAnyPointerType() ||
1581218893Sdim              FromType->isBlockPointerType() ||
1582218893Sdim              FromType->isMemberPointerType() ||
1583218893Sdim              FromType->isNullPtrType())) {
1584218893Sdim    // Boolean conversions (C++ 4.12).
1585218893Sdim    SCS.Second = ICK_Boolean_Conversion;
1586218893Sdim    FromType = S.Context.BoolTy;
1587218893Sdim  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1588212904Sdim             ToType->isIntegralType(S.Context)) {
1589198092Srdivacky    // Integral conversions (C++ 4.7).
1590193326Sed    SCS.Second = ICK_Integral_Conversion;
1591193326Sed    FromType = ToType.getUnqualifiedType();
1592263509Sdim  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1593204643Srdivacky    // Complex conversions (C99 6.3.1.6)
1594204643Srdivacky    SCS.Second = ICK_Complex_Conversion;
1595204643Srdivacky    FromType = ToType.getUnqualifiedType();
1596218893Sdim  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1597218893Sdim             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1598204643Srdivacky    // Complex-real conversions (C99 6.3.1.7)
1599204643Srdivacky    SCS.Second = ICK_Complex_Real;
1600204643Srdivacky    FromType = ToType.getUnqualifiedType();
1601210299Sed  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1602198092Srdivacky    // Floating point conversions (C++ 4.8).
1603193326Sed    SCS.Second = ICK_Floating_Conversion;
1604193326Sed    FromType = ToType.getUnqualifiedType();
1605218893Sdim  } else if ((FromType->isRealFloatingType() &&
1606218893Sdim              ToType->isIntegralType(S.Context)) ||
1607218893Sdim             (FromType->isIntegralOrUnscopedEnumerationType() &&
1608210299Sed              ToType->isRealFloatingType())) {
1609198092Srdivacky    // Floating-integral conversions (C++ 4.9).
1610193326Sed    SCS.Second = ICK_Floating_Integral;
1611193326Sed    FromType = ToType.getUnqualifiedType();
1612218893Sdim  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1613224145Sdim    SCS.Second = ICK_Block_Pointer_Conversion;
1614224145Sdim  } else if (AllowObjCWritebackConversion &&
1615224145Sdim             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1616224145Sdim    SCS.Second = ICK_Writeback_Conversion;
1617212904Sdim  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1618212904Sdim                                   FromType, IncompatibleObjC)) {
1619198092Srdivacky    // Pointer conversions (C++ 4.10).
1620193326Sed    SCS.Second = ICK_Pointer_Conversion;
1621193326Sed    SCS.IncompatibleObjC = IncompatibleObjC;
1622221345Sdim    FromType = FromType.getUnqualifiedType();
1623218893Sdim  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1624212904Sdim                                         InOverloadResolution, FromType)) {
1625198092Srdivacky    // Pointer to member conversions (4.11).
1626193326Sed    SCS.Second = ICK_Pointer_Member;
1627212904Sdim  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1628208600Srdivacky    SCS.Second = SecondICK;
1629208600Srdivacky    FromType = ToType.getUnqualifiedType();
1630235633Sdim  } else if (!S.getLangOpts().CPlusPlus &&
1631212904Sdim             S.Context.typesAreCompatible(ToType, FromType)) {
1632198092Srdivacky    // Compatible conversions (Clang extension for C function overloading)
1633193326Sed    SCS.Second = ICK_Compatible_Conversion;
1634208600Srdivacky    FromType = ToType.getUnqualifiedType();
1635224145Sdim  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1636200583Srdivacky    // Treat a conversion that strips "noreturn" as an identity conversion.
1637200583Srdivacky    SCS.Second = ICK_NoReturn_Adjustment;
1638221345Sdim  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1639221345Sdim                                             InOverloadResolution,
1640221345Sdim                                             SCS, CStyle)) {
1641221345Sdim    SCS.Second = ICK_TransparentUnionConversion;
1642221345Sdim    FromType = ToType;
1643235633Sdim  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1644235633Sdim                                 CStyle)) {
1645235633Sdim    // tryAtomicConversion has updated the standard conversion sequence
1646235633Sdim    // appropriately.
1647235633Sdim    return true;
1648252723Sdim  } else if (ToType->isEventT() &&
1649252723Sdim             From->isIntegerConstantExpr(S.getASTContext()) &&
1650252723Sdim             (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1651252723Sdim    SCS.Second = ICK_Zero_Event_Conversion;
1652252723Sdim    FromType = ToType;
1653193326Sed  } else {
1654193326Sed    // No second conversion required.
1655193326Sed    SCS.Second = ICK_Identity;
1656193326Sed  }
1657203955Srdivacky  SCS.setToType(1, FromType);
1658193326Sed
1659193326Sed  QualType CanonFrom;
1660193326Sed  QualType CanonTo;
1661193326Sed  // The third conversion can be a qualification conversion (C++ 4p1).
1662224145Sdim  bool ObjCLifetimeConversion;
1663224145Sdim  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1664224145Sdim                                  ObjCLifetimeConversion)) {
1665193326Sed    SCS.Third = ICK_Qualification;
1666224145Sdim    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1667193326Sed    FromType = ToType;
1668212904Sdim    CanonFrom = S.Context.getCanonicalType(FromType);
1669212904Sdim    CanonTo = S.Context.getCanonicalType(ToType);
1670193326Sed  } else {
1671193326Sed    // No conversion required
1672193326Sed    SCS.Third = ICK_Identity;
1673193326Sed
1674198092Srdivacky    // C++ [over.best.ics]p6:
1675193326Sed    //   [...] Any difference in top-level cv-qualification is
1676193326Sed    //   subsumed by the initialization itself and does not constitute
1677193326Sed    //   a conversion. [...]
1678212904Sdim    CanonFrom = S.Context.getCanonicalType(FromType);
1679212904Sdim    CanonTo = S.Context.getCanonicalType(ToType);
1680218893Sdim    if (CanonFrom.getLocalUnqualifiedType()
1681199482Srdivacky                                       == CanonTo.getLocalUnqualifiedType() &&
1682252723Sdim        CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1683193326Sed      FromType = ToType;
1684193326Sed      CanonFrom = CanonTo;
1685193326Sed    }
1686193326Sed  }
1687203955Srdivacky  SCS.setToType(2, FromType);
1688193326Sed
1689193326Sed  // If we have not converted the argument type to the parameter type,
1690193326Sed  // this is a bad conversion sequence.
1691193326Sed  if (CanonFrom != CanonTo)
1692193326Sed    return false;
1693193326Sed
1694193326Sed  return true;
1695193326Sed}
1696221345Sdim
1697221345Sdimstatic bool
1698221345SdimIsTransparentUnionStandardConversion(Sema &S, Expr* From,
1699221345Sdim                                     QualType &ToType,
1700221345Sdim                                     bool InOverloadResolution,
1701221345Sdim                                     StandardConversionSequence &SCS,
1702221345Sdim                                     bool CStyle) {
1703221345Sdim
1704221345Sdim  const RecordType *UT = ToType->getAsUnionType();
1705221345Sdim  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1706221345Sdim    return false;
1707221345Sdim  // The field to initialize within the transparent union.
1708221345Sdim  RecordDecl *UD = UT->getDecl();
1709221345Sdim  // It's compatible if the expression matches any of the fields.
1710221345Sdim  for (RecordDecl::field_iterator it = UD->field_begin(),
1711221345Sdim       itend = UD->field_end();
1712221345Sdim       it != itend; ++it) {
1713224145Sdim    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1714224145Sdim                             CStyle, /*ObjCWritebackConversion=*/false)) {
1715221345Sdim      ToType = it->getType();
1716221345Sdim      return true;
1717221345Sdim    }
1718221345Sdim  }
1719221345Sdim  return false;
1720221345Sdim}
1721193326Sed
1722193326Sed/// IsIntegralPromotion - Determines whether the conversion from the
1723193326Sed/// expression From (whose potentially-adjusted type is FromType) to
1724193326Sed/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1725193326Sed/// sets PromotedType to the promoted type.
1726198092Srdivackybool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1727198092Srdivacky  const BuiltinType *To = ToType->getAs<BuiltinType>();
1728193326Sed  // All integers are built-in.
1729193326Sed  if (!To) {
1730193326Sed    return false;
1731193326Sed  }
1732193326Sed
1733193326Sed  // An rvalue of type char, signed char, unsigned char, short int, or
1734193326Sed  // unsigned short int can be converted to an rvalue of type int if
1735193326Sed  // int can represent all the values of the source type; otherwise,
1736193326Sed  // the source rvalue can be converted to an rvalue of type unsigned
1737193326Sed  // int (C++ 4.5p1).
1738203955Srdivacky  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1739203955Srdivacky      !FromType->isEnumeralType()) {
1740193326Sed    if (// We can promote any signed, promotable integer type to an int
1741193326Sed        (FromType->isSignedIntegerType() ||
1742193326Sed         // We can promote any unsigned integer type whose size is
1743193326Sed         // less than int to an int.
1744198092Srdivacky         (!FromType->isSignedIntegerType() &&
1745193326Sed          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1746193326Sed      return To->getKind() == BuiltinType::Int;
1747193326Sed    }
1748193326Sed
1749193326Sed    return To->getKind() == BuiltinType::UInt;
1750193326Sed  }
1751193326Sed
1752245431Sdim  // C++11 [conv.prom]p3:
1753218893Sdim  //   A prvalue of an unscoped enumeration type whose underlying type is not
1754218893Sdim  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1755218893Sdim  //   following types that can represent all the values of the enumeration
1756218893Sdim  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1757218893Sdim  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1758218893Sdim  //   long long int. If none of the types in that list can represent all the
1759218893Sdim  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1760218893Sdim  //   type can be converted to an rvalue a prvalue of the extended integer type
1761218893Sdim  //   with lowest integer conversion rank (4.13) greater than the rank of long
1762218893Sdim  //   long in which all the values of the enumeration can be represented. If
1763218893Sdim  //   there are two such extended types, the signed one is chosen.
1764245431Sdim  // C++11 [conv.prom]p4:
1765245431Sdim  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1766245431Sdim  //   can be converted to a prvalue of its underlying type. Moreover, if
1767245431Sdim  //   integral promotion can be applied to its underlying type, a prvalue of an
1768245431Sdim  //   unscoped enumeration type whose underlying type is fixed can also be
1769245431Sdim  //   converted to a prvalue of the promoted underlying type.
1770218893Sdim  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1771218893Sdim    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1772218893Sdim    // provided for a scoped enumeration.
1773218893Sdim    if (FromEnumType->getDecl()->isScoped())
1774218893Sdim      return false;
1775200583Srdivacky
1776245431Sdim    // We can perform an integral promotion to the underlying type of the enum,
1777245431Sdim    // even if that's not the promoted type.
1778245431Sdim    if (FromEnumType->getDecl()->isFixed()) {
1779245431Sdim      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1780245431Sdim      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1781245431Sdim             IsIntegralPromotion(From, Underlying, ToType);
1782245431Sdim    }
1783245431Sdim
1784218893Sdim    // We have already pre-calculated the promotion type, so this is trivial.
1785218893Sdim    if (ToType->isIntegerType() &&
1786245431Sdim        !RequireCompleteType(From->getLocStart(), FromType, 0))
1787200583Srdivacky      return Context.hasSameUnqualifiedType(ToType,
1788200583Srdivacky                                FromEnumType->getDecl()->getPromotionType());
1789218893Sdim  }
1790200583Srdivacky
1791218893Sdim  // C++0x [conv.prom]p2:
1792218893Sdim  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1793218893Sdim  //   to an rvalue a prvalue of the first of the following types that can
1794218893Sdim  //   represent all the values of its underlying type: int, unsigned int,
1795218893Sdim  //   long int, unsigned long int, long long int, or unsigned long long int.
1796218893Sdim  //   If none of the types in that list can represent all the values of its
1797218893Sdim  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1798218893Sdim  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1799218893Sdim  //   type.
1800218893Sdim  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1801218893Sdim      ToType->isIntegerType()) {
1802193326Sed    // Determine whether the type we're converting from is signed or
1803193326Sed    // unsigned.
1804226890Sdim    bool FromIsSigned = FromType->isSignedIntegerType();
1805193326Sed    uint64_t FromSize = Context.getTypeSize(FromType);
1806218893Sdim
1807193326Sed    // The types we'll try to promote to, in the appropriate
1808193326Sed    // order. Try each of these types.
1809198092Srdivacky    QualType PromoteTypes[6] = {
1810198092Srdivacky      Context.IntTy, Context.UnsignedIntTy,
1811193326Sed      Context.LongTy, Context.UnsignedLongTy ,
1812193326Sed      Context.LongLongTy, Context.UnsignedLongLongTy
1813193326Sed    };
1814193326Sed    for (int Idx = 0; Idx < 6; ++Idx) {
1815193326Sed      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1816193326Sed      if (FromSize < ToSize ||
1817198092Srdivacky          (FromSize == ToSize &&
1818193326Sed           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1819193326Sed        // We found the type that we can promote to. If this is the
1820193326Sed        // type we wanted, we have a promotion. Otherwise, no
1821193326Sed        // promotion.
1822199482Srdivacky        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1823193326Sed      }
1824193326Sed    }
1825193326Sed  }
1826193326Sed
1827193326Sed  // An rvalue for an integral bit-field (9.6) can be converted to an
1828193326Sed  // rvalue of type int if int can represent all the values of the
1829193326Sed  // bit-field; otherwise, it can be converted to unsigned int if
1830193326Sed  // unsigned int can represent all the values of the bit-field. If
1831193326Sed  // the bit-field is larger yet, no integral promotion applies to
1832193326Sed  // it. If the bit-field has an enumerated type, it is treated as any
1833193326Sed  // other value of that type for promotion purposes (C++ 4.5p3).
1834193326Sed  // FIXME: We should delay checking of bit-fields until we actually perform the
1835193326Sed  // conversion.
1836193326Sed  using llvm::APSInt;
1837193326Sed  if (From)
1838252723Sdim    if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1839193326Sed      APSInt BitWidth;
1840210299Sed      if (FromType->isIntegralType(Context) &&
1841193326Sed          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1842193326Sed        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1843193326Sed        ToSize = Context.getTypeSize(ToType);
1844198092Srdivacky
1845193326Sed        // Are we promoting to an int from a bitfield that fits in an int?
1846193326Sed        if (BitWidth < ToSize ||
1847193326Sed            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1848193326Sed          return To->getKind() == BuiltinType::Int;
1849193326Sed        }
1850198092Srdivacky
1851193326Sed        // Are we promoting to an unsigned int from an unsigned bitfield
1852193326Sed        // that fits into an unsigned int?
1853193326Sed        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1854193326Sed          return To->getKind() == BuiltinType::UInt;
1855193326Sed        }
1856198092Srdivacky
1857193326Sed        return false;
1858193326Sed      }
1859193326Sed    }
1860198092Srdivacky
1861193326Sed  // An rvalue of type bool can be converted to an rvalue of type int,
1862193326Sed  // with false becoming zero and true becoming one (C++ 4.5p4).
1863193326Sed  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1864193326Sed    return true;
1865193326Sed  }
1866193326Sed
1867193326Sed  return false;
1868193326Sed}
1869193326Sed
1870193326Sed/// IsFloatingPointPromotion - Determines whether the conversion from
1871193326Sed/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1872193326Sed/// returns true and sets PromotedType to the promoted type.
1873198092Srdivackybool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1874198092Srdivacky  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1875198092Srdivacky    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1876226890Sdim      /// An rvalue of type float can be converted to an rvalue of type
1877226890Sdim      /// double. (C++ 4.6p1).
1878193326Sed      if (FromBuiltin->getKind() == BuiltinType::Float &&
1879193326Sed          ToBuiltin->getKind() == BuiltinType::Double)
1880193326Sed        return true;
1881193326Sed
1882193326Sed      // C99 6.3.1.5p1:
1883193326Sed      //   When a float is promoted to double or long double, or a
1884193326Sed      //   double is promoted to long double [...].
1885235633Sdim      if (!getLangOpts().CPlusPlus &&
1886193326Sed          (FromBuiltin->getKind() == BuiltinType::Float ||
1887193326Sed           FromBuiltin->getKind() == BuiltinType::Double) &&
1888193326Sed          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1889193326Sed        return true;
1890226890Sdim
1891226890Sdim      // Half can be promoted to float.
1892252723Sdim      if (!getLangOpts().NativeHalfType &&
1893252723Sdim           FromBuiltin->getKind() == BuiltinType::Half &&
1894226890Sdim          ToBuiltin->getKind() == BuiltinType::Float)
1895226890Sdim        return true;
1896193326Sed    }
1897193326Sed
1898193326Sed  return false;
1899193326Sed}
1900193326Sed
1901193326Sed/// \brief Determine if a conversion is a complex promotion.
1902193326Sed///
1903193326Sed/// A complex promotion is defined as a complex -> complex conversion
1904193326Sed/// where the conversion between the underlying real types is a
1905193326Sed/// floating-point or integral promotion.
1906193326Sedbool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1907198092Srdivacky  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1908193326Sed  if (!FromComplex)
1909193326Sed    return false;
1910193326Sed
1911198092Srdivacky  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1912193326Sed  if (!ToComplex)
1913193326Sed    return false;
1914193326Sed
1915193326Sed  return IsFloatingPointPromotion(FromComplex->getElementType(),
1916193326Sed                                  ToComplex->getElementType()) ||
1917193326Sed    IsIntegralPromotion(0, FromComplex->getElementType(),
1918193326Sed                        ToComplex->getElementType());
1919193326Sed}
1920193326Sed
1921193326Sed/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1922193326Sed/// the pointer type FromPtr to a pointer to type ToPointee, with the
1923193326Sed/// same type qualifiers as FromPtr has on its pointee type. ToType,
1924193326Sed/// if non-empty, will be a pointer to ToType that may or may not have
1925193326Sed/// the right set of qualifiers on its pointee.
1926224145Sdim///
1927198092Srdivackystatic QualType
1928218893SdimBuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1929193326Sed                                   QualType ToPointee, QualType ToType,
1930224145Sdim                                   ASTContext &Context,
1931224145Sdim                                   bool StripObjCLifetime = false) {
1932218893Sdim  assert((FromPtr->getTypeClass() == Type::Pointer ||
1933218893Sdim          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1934218893Sdim         "Invalid similarly-qualified pointer type");
1935218893Sdim
1936224145Sdim  /// Conversions to 'id' subsume cv-qualifier conversions.
1937224145Sdim  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1938218893Sdim    return ToType.getUnqualifiedType();
1939218893Sdim
1940218893Sdim  QualType CanonFromPointee
1941218893Sdim    = Context.getCanonicalType(FromPtr->getPointeeType());
1942193326Sed  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1943198092Srdivacky  Qualifiers Quals = CanonFromPointee.getQualifiers();
1944198092Srdivacky
1945224145Sdim  if (StripObjCLifetime)
1946224145Sdim    Quals.removeObjCLifetime();
1947224145Sdim
1948198092Srdivacky  // Exact qualifier match -> return the pointer type we're converting to.
1949199482Srdivacky  if (CanonToPointee.getLocalQualifiers() == Quals) {
1950193326Sed    // ToType is exactly what we need. Return it.
1951198092Srdivacky    if (!ToType.isNull())
1952208600Srdivacky      return ToType.getUnqualifiedType();
1953193326Sed
1954193326Sed    // Build a pointer to ToPointee. It has the right qualifiers
1955193326Sed    // already.
1956218893Sdim    if (isa<ObjCObjectPointerType>(ToType))
1957218893Sdim      return Context.getObjCObjectPointerType(ToPointee);
1958193326Sed    return Context.getPointerType(ToPointee);
1959193326Sed  }
1960193326Sed
1961193326Sed  // Just build a canonical type that has the right qualifiers.
1962218893Sdim  QualType QualifiedCanonToPointee
1963218893Sdim    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1964218893Sdim
1965218893Sdim  if (isa<ObjCObjectPointerType>(ToType))
1966218893Sdim    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1967218893Sdim  return Context.getPointerType(QualifiedCanonToPointee);
1968193326Sed}
1969193326Sed
1970198092Srdivackystatic bool isNullPointerConstantForConversion(Expr *Expr,
1971198092Srdivacky                                               bool InOverloadResolution,
1972198092Srdivacky                                               ASTContext &Context) {
1973198092Srdivacky  // Handle value-dependent integral null pointer constants correctly.
1974198092Srdivacky  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1975198092Srdivacky  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1976210299Sed      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1977198092Srdivacky    return !InOverloadResolution;
1978198092Srdivacky
1979198092Srdivacky  return Expr->isNullPointerConstant(Context,
1980198092Srdivacky                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1981198092Srdivacky                                        : Expr::NPC_ValueDependentIsNull);
1982198092Srdivacky}
1983198092Srdivacky
1984193326Sed/// IsPointerConversion - Determines whether the conversion of the
1985193326Sed/// expression From, which has the (possibly adjusted) type FromType,
1986193326Sed/// can be converted to the type ToType via a pointer conversion (C++
1987193326Sed/// 4.10). If so, returns true and places the converted type (that
1988193326Sed/// might differ from ToType in its cv-qualifiers at some level) into
1989193326Sed/// ConvertedType.
1990193326Sed///
1991193326Sed/// This routine also supports conversions to and from block pointers
1992193326Sed/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1993193326Sed/// pointers to interfaces. FIXME: Once we've determined the
1994193326Sed/// appropriate overloading rules for Objective-C, we may want to
1995193326Sed/// split the Objective-C checks into a different routine; however,
1996193326Sed/// GCC seems to consider all of these conversions to be pointer
1997193326Sed/// conversions, so for now they live here. IncompatibleObjC will be
1998193326Sed/// set if the conversion is an allowed Objective-C conversion that
1999193326Sed/// should result in a warning.
2000193326Sedbool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2001198092Srdivacky                               bool InOverloadResolution,
2002193326Sed                               QualType& ConvertedType,
2003198092Srdivacky                               bool &IncompatibleObjC) {
2004193326Sed  IncompatibleObjC = false;
2005218893Sdim  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2006218893Sdim                              IncompatibleObjC))
2007193326Sed    return true;
2008193326Sed
2009198092Srdivacky  // Conversion from a null pointer constant to any Objective-C pointer type.
2010198092Srdivacky  if (ToType->isObjCObjectPointerType() &&
2011198092Srdivacky      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2012193326Sed    ConvertedType = ToType;
2013193326Sed    return true;
2014193326Sed  }
2015193326Sed
2016193326Sed  // Blocks: Block pointers can be converted to void*.
2017193326Sed  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2018198092Srdivacky      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2019193326Sed    ConvertedType = ToType;
2020193326Sed    return true;
2021193326Sed  }
2022193326Sed  // Blocks: A null pointer constant can be converted to a block
2023193326Sed  // pointer type.
2024198092Srdivacky  if (ToType->isBlockPointerType() &&
2025198092Srdivacky      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2026193326Sed    ConvertedType = ToType;
2027193326Sed    return true;
2028193326Sed  }
2029193326Sed
2030193326Sed  // If the left-hand-side is nullptr_t, the right side can be a null
2031193326Sed  // pointer constant.
2032198092Srdivacky  if (ToType->isNullPtrType() &&
2033198092Srdivacky      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2034193326Sed    ConvertedType = ToType;
2035193326Sed    return true;
2036193326Sed  }
2037193326Sed
2038198092Srdivacky  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2039193326Sed  if (!ToTypePtr)
2040193326Sed    return false;
2041193326Sed
2042193326Sed  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2043198092Srdivacky  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2044193326Sed    ConvertedType = ToType;
2045193326Sed    return true;
2046193326Sed  }
2047193326Sed
2048218893Sdim  // Beyond this point, both types need to be pointers
2049201361Srdivacky  // , including objective-c pointers.
2050201361Srdivacky  QualType ToPointeeType = ToTypePtr->getPointeeType();
2051224145Sdim  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2052235633Sdim      !getLangOpts().ObjCAutoRefCount) {
2053218893Sdim    ConvertedType = BuildSimilarlyQualifiedPointerType(
2054218893Sdim                                      FromType->getAs<ObjCObjectPointerType>(),
2055218893Sdim                                                       ToPointeeType,
2056201361Srdivacky                                                       ToType, Context);
2057201361Srdivacky    return true;
2058201361Srdivacky  }
2059198092Srdivacky  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2060193326Sed  if (!FromTypePtr)
2061193326Sed    return false;
2062193326Sed
2063193326Sed  QualType FromPointeeType = FromTypePtr->getPointeeType();
2064193326Sed
2065218893Sdim  // If the unqualified pointee types are the same, this can't be a
2066212904Sdim  // pointer conversion, so don't do all of the work below.
2067212904Sdim  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2068212904Sdim    return false;
2069212904Sdim
2070193326Sed  // An rvalue of type "pointer to cv T," where T is an object type,
2071193326Sed  // can be converted to an rvalue of type "pointer to cv void" (C++
2072193326Sed  // 4.10p2).
2073212904Sdim  if (FromPointeeType->isIncompleteOrObjectType() &&
2074212904Sdim      ToPointeeType->isVoidType()) {
2075198092Srdivacky    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2076193326Sed                                                       ToPointeeType,
2077224145Sdim                                                       ToType, Context,
2078224145Sdim                                                   /*StripObjCLifetime=*/true);
2079193326Sed    return true;
2080193326Sed  }
2081193326Sed
2082223017Sdim  // MSVC allows implicit function to void* type conversion.
2083235633Sdim  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2084223017Sdim      ToPointeeType->isVoidType()) {
2085223017Sdim    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2086223017Sdim                                                       ToPointeeType,
2087223017Sdim                                                       ToType, Context);
2088223017Sdim    return true;
2089223017Sdim  }
2090223017Sdim
2091193326Sed  // When we're overloading in C, we allow a special kind of pointer
2092193326Sed  // conversion for compatible-but-not-identical pointee types.
2093235633Sdim  if (!getLangOpts().CPlusPlus &&
2094193326Sed      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2095198092Srdivacky    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2096193326Sed                                                       ToPointeeType,
2097198092Srdivacky                                                       ToType, Context);
2098193326Sed    return true;
2099193326Sed  }
2100193326Sed
2101193326Sed  // C++ [conv.ptr]p3:
2102198092Srdivacky  //
2103193326Sed  //   An rvalue of type "pointer to cv D," where D is a class type,
2104193326Sed  //   can be converted to an rvalue of type "pointer to cv B," where
2105193326Sed  //   B is a base class (clause 10) of D. If B is an inaccessible
2106193326Sed  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2107193326Sed  //   necessitates this conversion is ill-formed. The result of the
2108193326Sed  //   conversion is a pointer to the base class sub-object of the
2109193326Sed  //   derived class object. The null pointer value is converted to
2110193326Sed  //   the null pointer value of the destination type.
2111193326Sed  //
2112193326Sed  // Note that we do not check for ambiguity or inaccessibility
2113193326Sed  // here. That is handled by CheckPointerConversion.
2114235633Sdim  if (getLangOpts().CPlusPlus &&
2115193326Sed      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2116204643Srdivacky      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2117245431Sdim      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2118193326Sed      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2119198092Srdivacky    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2120193326Sed                                                       ToPointeeType,
2121193326Sed                                                       ToType, Context);
2122193326Sed    return true;
2123193326Sed  }
2124193326Sed
2125221345Sdim  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2126221345Sdim      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2127221345Sdim    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2128221345Sdim                                                       ToPointeeType,
2129221345Sdim                                                       ToType, Context);
2130221345Sdim    return true;
2131221345Sdim  }
2132221345Sdim
2133193326Sed  return false;
2134193326Sed}
2135221345Sdim
2136221345Sdim/// \brief Adopt the given qualifiers for the given type.
2137221345Sdimstatic QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2138221345Sdim  Qualifiers TQs = T.getQualifiers();
2139221345Sdim
2140221345Sdim  // Check whether qualifiers already match.
2141221345Sdim  if (TQs == Qs)
2142221345Sdim    return T;
2143221345Sdim
2144221345Sdim  if (Qs.compatiblyIncludes(TQs))
2145221345Sdim    return Context.getQualifiedType(T, Qs);
2146221345Sdim
2147221345Sdim  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2148221345Sdim}
2149193326Sed
2150193326Sed/// isObjCPointerConversion - Determines whether this is an
2151193326Sed/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2152193326Sed/// with the same arguments and return values.
2153198092Srdivackybool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2154193326Sed                                   QualType& ConvertedType,
2155193326Sed                                   bool &IncompatibleObjC) {
2156235633Sdim  if (!getLangOpts().ObjC1)
2157193326Sed    return false;
2158218893Sdim
2159221345Sdim  // The set of qualifiers on the type we're converting from.
2160221345Sdim  Qualifiers FromQualifiers = FromType.getQualifiers();
2161221345Sdim
2162198092Srdivacky  // First, we handle all conversions on ObjC object pointer types.
2163218893Sdim  const ObjCObjectPointerType* ToObjCPtr =
2164218893Sdim    ToType->getAs<ObjCObjectPointerType>();
2165198092Srdivacky  const ObjCObjectPointerType *FromObjCPtr =
2166198092Srdivacky    FromType->getAs<ObjCObjectPointerType>();
2167198092Srdivacky
2168198092Srdivacky  if (ToObjCPtr && FromObjCPtr) {
2169218893Sdim    // If the pointee types are the same (ignoring qualifications),
2170218893Sdim    // then this is not a pointer conversion.
2171218893Sdim    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2172218893Sdim                                       FromObjCPtr->getPointeeType()))
2173218893Sdim      return false;
2174218893Sdim
2175221345Sdim    // Check for compatible
2176198092Srdivacky    // Objective C++: We're able to convert between "id" or "Class" and a
2177198092Srdivacky    // pointer to any interface (in both directions).
2178198092Srdivacky    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2179221345Sdim      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2180198092Srdivacky      return true;
2181198092Srdivacky    }
2182198092Srdivacky    // Conversions with Objective-C's id<...>.
2183198092Srdivacky    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2184198092Srdivacky         ToObjCPtr->isObjCQualifiedIdType()) &&
2185198092Srdivacky        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2186198092Srdivacky                                                  /*compare=*/false)) {
2187221345Sdim      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2188198092Srdivacky      return true;
2189198092Srdivacky    }
2190198092Srdivacky    // Objective C++: We're able to convert from a pointer to an
2191198092Srdivacky    // interface to a pointer to a different interface.
2192198092Srdivacky    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2193205219Srdivacky      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2194205219Srdivacky      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2195235633Sdim      if (getLangOpts().CPlusPlus && LHS && RHS &&
2196205219Srdivacky          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2197205219Srdivacky                                                FromObjCPtr->getPointeeType()))
2198205219Srdivacky        return false;
2199218893Sdim      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2200218893Sdim                                                   ToObjCPtr->getPointeeType(),
2201218893Sdim                                                         ToType, Context);
2202221345Sdim      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2203198092Srdivacky      return true;
2204198092Srdivacky    }
2205198092Srdivacky
2206198092Srdivacky    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2207198092Srdivacky      // Okay: this is some kind of implicit downcast of Objective-C
2208198092Srdivacky      // interfaces, which is permitted. However, we're going to
2209198092Srdivacky      // complain about it.
2210198092Srdivacky      IncompatibleObjC = true;
2211218893Sdim      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2212218893Sdim                                                   ToObjCPtr->getPointeeType(),
2213218893Sdim                                                         ToType, Context);
2214221345Sdim      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2215198092Srdivacky      return true;
2216198092Srdivacky    }
2217193326Sed  }
2218198092Srdivacky  // Beyond this point, both types need to be C pointers or block pointers.
2219193326Sed  QualType ToPointeeType;
2220198092Srdivacky  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2221198092Srdivacky    ToPointeeType = ToCPtr->getPointeeType();
2222218893Sdim  else if (const BlockPointerType *ToBlockPtr =
2223202879Srdivacky            ToType->getAs<BlockPointerType>()) {
2224202879Srdivacky    // Objective C++: We're able to convert from a pointer to any object
2225202879Srdivacky    // to a block pointer type.
2226202879Srdivacky    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2227221345Sdim      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2228202879Srdivacky      return true;
2229202879Srdivacky    }
2230193326Sed    ToPointeeType = ToBlockPtr->getPointeeType();
2231202879Srdivacky  }
2232218893Sdim  else if (FromType->getAs<BlockPointerType>() &&
2233202879Srdivacky           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2234218893Sdim    // Objective C++: We're able to convert from a block pointer type to a
2235202879Srdivacky    // pointer to any object.
2236221345Sdim    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2237202879Srdivacky    return true;
2238202879Srdivacky  }
2239193326Sed  else
2240193326Sed    return false;
2241193326Sed
2242193326Sed  QualType FromPointeeType;
2243198092Srdivacky  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2244198092Srdivacky    FromPointeeType = FromCPtr->getPointeeType();
2245218893Sdim  else if (const BlockPointerType *FromBlockPtr =
2246218893Sdim           FromType->getAs<BlockPointerType>())
2247193326Sed    FromPointeeType = FromBlockPtr->getPointeeType();
2248193326Sed  else
2249193326Sed    return false;
2250193326Sed
2251193326Sed  // If we have pointers to pointers, recursively check whether this
2252193326Sed  // is an Objective-C conversion.
2253193326Sed  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2254193326Sed      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2255193326Sed                              IncompatibleObjC)) {
2256193326Sed    // We always complain about this conversion.
2257193326Sed    IncompatibleObjC = true;
2258218893Sdim    ConvertedType = Context.getPointerType(ConvertedType);
2259221345Sdim    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2260193326Sed    return true;
2261193326Sed  }
2262202879Srdivacky  // Allow conversion of pointee being objective-c pointer to another one;
2263202879Srdivacky  // as in I* to id.
2264202879Srdivacky  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2265202879Srdivacky      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2266202879Srdivacky      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2267202879Srdivacky                              IncompatibleObjC)) {
2268224145Sdim
2269218893Sdim    ConvertedType = Context.getPointerType(ConvertedType);
2270221345Sdim    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2271202879Srdivacky    return true;
2272202879Srdivacky  }
2273218893Sdim
2274193326Sed  // If we have pointers to functions or blocks, check whether the only
2275193326Sed  // differences in the argument and result types are in Objective-C
2276193326Sed  // pointer conversions. If so, we permit the conversion (but
2277193326Sed  // complain about it).
2278198092Srdivacky  const FunctionProtoType *FromFunctionType
2279198092Srdivacky    = FromPointeeType->getAs<FunctionProtoType>();
2280193326Sed  const FunctionProtoType *ToFunctionType
2281198092Srdivacky    = ToPointeeType->getAs<FunctionProtoType>();
2282193326Sed  if (FromFunctionType && ToFunctionType) {
2283193326Sed    // If the function types are exactly the same, this isn't an
2284193326Sed    // Objective-C pointer conversion.
2285193326Sed    if (Context.getCanonicalType(FromPointeeType)
2286193326Sed          == Context.getCanonicalType(ToPointeeType))
2287193326Sed      return false;
2288193326Sed
2289193326Sed    // Perform the quick checks that will tell us whether these
2290193326Sed    // function types are obviously different.
2291193326Sed    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2292193326Sed        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2293193326Sed        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2294193326Sed      return false;
2295193326Sed
2296193326Sed    bool HasObjCConversion = false;
2297193326Sed    if (Context.getCanonicalType(FromFunctionType->getResultType())
2298193326Sed          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2299193326Sed      // Okay, the types match exactly. Nothing to do.
2300193326Sed    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2301193326Sed                                       ToFunctionType->getResultType(),
2302193326Sed                                       ConvertedType, IncompatibleObjC)) {
2303193326Sed      // Okay, we have an Objective-C pointer conversion.
2304193326Sed      HasObjCConversion = true;
2305193326Sed    } else {
2306193326Sed      // Function types are too different. Abort.
2307193326Sed      return false;
2308193326Sed    }
2309198092Srdivacky
2310193326Sed    // Check argument types.
2311193326Sed    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2312193326Sed         ArgIdx != NumArgs; ++ArgIdx) {
2313193326Sed      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2314193326Sed      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2315193326Sed      if (Context.getCanonicalType(FromArgType)
2316193326Sed            == Context.getCanonicalType(ToArgType)) {
2317193326Sed        // Okay, the types match exactly. Nothing to do.
2318193326Sed      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2319193326Sed                                         ConvertedType, IncompatibleObjC)) {
2320193326Sed        // Okay, we have an Objective-C pointer conversion.
2321193326Sed        HasObjCConversion = true;
2322193326Sed      } else {
2323193326Sed        // Argument types are too different. Abort.
2324193326Sed        return false;
2325193326Sed      }
2326193326Sed    }
2327193326Sed
2328193326Sed    if (HasObjCConversion) {
2329193326Sed      // We had an Objective-C conversion. Allow this pointer
2330193326Sed      // conversion, but complain about it.
2331221345Sdim      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2332193326Sed      IncompatibleObjC = true;
2333193326Sed      return true;
2334193326Sed    }
2335193326Sed  }
2336193326Sed
2337193326Sed  return false;
2338193326Sed}
2339218893Sdim
2340224145Sdim/// \brief Determine whether this is an Objective-C writeback conversion,
2341224145Sdim/// used for parameter passing when performing automatic reference counting.
2342224145Sdim///
2343224145Sdim/// \param FromType The type we're converting form.
2344224145Sdim///
2345224145Sdim/// \param ToType The type we're converting to.
2346224145Sdim///
2347224145Sdim/// \param ConvertedType The type that will be produced after applying
2348224145Sdim/// this conversion.
2349224145Sdimbool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2350224145Sdim                                     QualType &ConvertedType) {
2351235633Sdim  if (!getLangOpts().ObjCAutoRefCount ||
2352224145Sdim      Context.hasSameUnqualifiedType(FromType, ToType))
2353224145Sdim    return false;
2354224145Sdim
2355224145Sdim  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2356224145Sdim  QualType ToPointee;
2357224145Sdim  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2358224145Sdim    ToPointee = ToPointer->getPointeeType();
2359224145Sdim  else
2360224145Sdim    return false;
2361224145Sdim
2362224145Sdim  Qualifiers ToQuals = ToPointee.getQualifiers();
2363224145Sdim  if (!ToPointee->isObjCLifetimeType() ||
2364224145Sdim      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2365235633Sdim      !ToQuals.withoutObjCLifetime().empty())
2366224145Sdim    return false;
2367224145Sdim
2368224145Sdim  // Argument must be a pointer to __strong to __weak.
2369224145Sdim  QualType FromPointee;
2370224145Sdim  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2371224145Sdim    FromPointee = FromPointer->getPointeeType();
2372224145Sdim  else
2373224145Sdim    return false;
2374224145Sdim
2375224145Sdim  Qualifiers FromQuals = FromPointee.getQualifiers();
2376224145Sdim  if (!FromPointee->isObjCLifetimeType() ||
2377224145Sdim      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2378224145Sdim       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2379224145Sdim    return false;
2380224145Sdim
2381224145Sdim  // Make sure that we have compatible qualifiers.
2382224145Sdim  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2383224145Sdim  if (!ToQuals.compatiblyIncludes(FromQuals))
2384224145Sdim    return false;
2385224145Sdim
2386224145Sdim  // Remove qualifiers from the pointee type we're converting from; they
2387224145Sdim  // aren't used in the compatibility check belong, and we'll be adding back
2388224145Sdim  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2389224145Sdim  FromPointee = FromPointee.getUnqualifiedType();
2390224145Sdim
2391224145Sdim  // The unqualified form of the pointee types must be compatible.
2392224145Sdim  ToPointee = ToPointee.getUnqualifiedType();
2393224145Sdim  bool IncompatibleObjC;
2394224145Sdim  if (Context.typesAreCompatible(FromPointee, ToPointee))
2395224145Sdim    FromPointee = ToPointee;
2396224145Sdim  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2397224145Sdim                                    IncompatibleObjC))
2398224145Sdim    return false;
2399224145Sdim
2400224145Sdim  /// \brief Construct the type we're converting to, which is a pointer to
2401224145Sdim  /// __autoreleasing pointee.
2402224145Sdim  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2403224145Sdim  ConvertedType = Context.getPointerType(FromPointee);
2404224145Sdim  return true;
2405224145Sdim}
2406224145Sdim
2407218893Sdimbool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2408218893Sdim                                    QualType& ConvertedType) {
2409218893Sdim  QualType ToPointeeType;
2410218893Sdim  if (const BlockPointerType *ToBlockPtr =
2411218893Sdim        ToType->getAs<BlockPointerType>())
2412218893Sdim    ToPointeeType = ToBlockPtr->getPointeeType();
2413218893Sdim  else
2414218893Sdim    return false;
2415218893Sdim
2416218893Sdim  QualType FromPointeeType;
2417218893Sdim  if (const BlockPointerType *FromBlockPtr =
2418218893Sdim      FromType->getAs<BlockPointerType>())
2419218893Sdim    FromPointeeType = FromBlockPtr->getPointeeType();
2420218893Sdim  else
2421218893Sdim    return false;
2422218893Sdim  // We have pointer to blocks, check whether the only
2423218893Sdim  // differences in the argument and result types are in Objective-C
2424218893Sdim  // pointer conversions. If so, we permit the conversion.
2425218893Sdim
2426218893Sdim  const FunctionProtoType *FromFunctionType
2427218893Sdim    = FromPointeeType->getAs<FunctionProtoType>();
2428218893Sdim  const FunctionProtoType *ToFunctionType
2429218893Sdim    = ToPointeeType->getAs<FunctionProtoType>();
2430218893Sdim
2431218893Sdim  if (!FromFunctionType || !ToFunctionType)
2432218893Sdim    return false;
2433218893Sdim
2434218893Sdim  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2435218893Sdim    return true;
2436218893Sdim
2437218893Sdim  // Perform the quick checks that will tell us whether these
2438218893Sdim  // function types are obviously different.
2439218893Sdim  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2440218893Sdim      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2441218893Sdim    return false;
2442218893Sdim
2443218893Sdim  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2444218893Sdim  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2445218893Sdim  if (FromEInfo != ToEInfo)
2446218893Sdim    return false;
2447218893Sdim
2448218893Sdim  bool IncompatibleObjC = false;
2449218893Sdim  if (Context.hasSameType(FromFunctionType->getResultType(),
2450218893Sdim                          ToFunctionType->getResultType())) {
2451218893Sdim    // Okay, the types match exactly. Nothing to do.
2452218893Sdim  } else {
2453218893Sdim    QualType RHS = FromFunctionType->getResultType();
2454218893Sdim    QualType LHS = ToFunctionType->getResultType();
2455235633Sdim    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2456218893Sdim        !RHS.hasQualifiers() && LHS.hasQualifiers())
2457218893Sdim       LHS = LHS.getUnqualifiedType();
2458218893Sdim
2459218893Sdim     if (Context.hasSameType(RHS,LHS)) {
2460218893Sdim       // OK exact match.
2461218893Sdim     } else if (isObjCPointerConversion(RHS, LHS,
2462218893Sdim                                        ConvertedType, IncompatibleObjC)) {
2463218893Sdim     if (IncompatibleObjC)
2464218893Sdim       return false;
2465218893Sdim     // Okay, we have an Objective-C pointer conversion.
2466218893Sdim     }
2467218893Sdim     else
2468218893Sdim       return false;
2469218893Sdim   }
2470218893Sdim
2471218893Sdim   // Check argument types.
2472218893Sdim   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2473218893Sdim        ArgIdx != NumArgs; ++ArgIdx) {
2474218893Sdim     IncompatibleObjC = false;
2475218893Sdim     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2476218893Sdim     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2477218893Sdim     if (Context.hasSameType(FromArgType, ToArgType)) {
2478218893Sdim       // Okay, the types match exactly. Nothing to do.
2479218893Sdim     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2480218893Sdim                                        ConvertedType, IncompatibleObjC)) {
2481218893Sdim       if (IncompatibleObjC)
2482218893Sdim         return false;
2483218893Sdim       // Okay, we have an Objective-C pointer conversion.
2484218893Sdim     } else
2485218893Sdim       // Argument types are too different. Abort.
2486218893Sdim       return false;
2487218893Sdim   }
2488226890Sdim   if (LangOpts.ObjCAutoRefCount &&
2489226890Sdim       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2490226890Sdim                                                    ToFunctionType))
2491226890Sdim     return false;
2492226890Sdim
2493218893Sdim   ConvertedType = ToType;
2494218893Sdim   return true;
2495218893Sdim}
2496218893Sdim
2497235633Sdimenum {
2498235633Sdim  ft_default,
2499235633Sdim  ft_different_class,
2500235633Sdim  ft_parameter_arity,
2501235633Sdim  ft_parameter_mismatch,
2502235633Sdim  ft_return_type,
2503235633Sdim  ft_qualifer_mismatch
2504235633Sdim};
2505235633Sdim
2506235633Sdim/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2507235633Sdim/// function types.  Catches different number of parameter, mismatch in
2508235633Sdim/// parameter types, and different return types.
2509235633Sdimvoid Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2510235633Sdim                                      QualType FromType, QualType ToType) {
2511235633Sdim  // If either type is not valid, include no extra info.
2512235633Sdim  if (FromType.isNull() || ToType.isNull()) {
2513235633Sdim    PDiag << ft_default;
2514235633Sdim    return;
2515235633Sdim  }
2516235633Sdim
2517235633Sdim  // Get the function type from the pointers.
2518235633Sdim  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2519235633Sdim    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2520235633Sdim                            *ToMember = ToType->getAs<MemberPointerType>();
2521235633Sdim    if (FromMember->getClass() != ToMember->getClass()) {
2522235633Sdim      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2523235633Sdim            << QualType(FromMember->getClass(), 0);
2524235633Sdim      return;
2525235633Sdim    }
2526235633Sdim    FromType = FromMember->getPointeeType();
2527235633Sdim    ToType = ToMember->getPointeeType();
2528235633Sdim  }
2529235633Sdim
2530235633Sdim  if (FromType->isPointerType())
2531235633Sdim    FromType = FromType->getPointeeType();
2532235633Sdim  if (ToType->isPointerType())
2533235633Sdim    ToType = ToType->getPointeeType();
2534235633Sdim
2535235633Sdim  // Remove references.
2536235633Sdim  FromType = FromType.getNonReferenceType();
2537235633Sdim  ToType = ToType.getNonReferenceType();
2538235633Sdim
2539235633Sdim  // Don't print extra info for non-specialized template functions.
2540235633Sdim  if (FromType->isInstantiationDependentType() &&
2541235633Sdim      !FromType->getAs<TemplateSpecializationType>()) {
2542235633Sdim    PDiag << ft_default;
2543235633Sdim    return;
2544235633Sdim  }
2545235633Sdim
2546235633Sdim  // No extra info for same types.
2547235633Sdim  if (Context.hasSameType(FromType, ToType)) {
2548235633Sdim    PDiag << ft_default;
2549235633Sdim    return;
2550235633Sdim  }
2551235633Sdim
2552235633Sdim  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2553235633Sdim                          *ToFunction = ToType->getAs<FunctionProtoType>();
2554235633Sdim
2555235633Sdim  // Both types need to be function types.
2556235633Sdim  if (!FromFunction || !ToFunction) {
2557235633Sdim    PDiag << ft_default;
2558235633Sdim    return;
2559235633Sdim  }
2560235633Sdim
2561235633Sdim  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2562235633Sdim    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2563235633Sdim          << FromFunction->getNumArgs();
2564235633Sdim    return;
2565235633Sdim  }
2566235633Sdim
2567235633Sdim  // Handle different parameter types.
2568235633Sdim  unsigned ArgPos;
2569235633Sdim  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2570235633Sdim    PDiag << ft_parameter_mismatch << ArgPos + 1
2571235633Sdim          << ToFunction->getArgType(ArgPos)
2572235633Sdim          << FromFunction->getArgType(ArgPos);
2573235633Sdim    return;
2574235633Sdim  }
2575235633Sdim
2576235633Sdim  // Handle different return type.
2577235633Sdim  if (!Context.hasSameType(FromFunction->getResultType(),
2578235633Sdim                           ToFunction->getResultType())) {
2579235633Sdim    PDiag << ft_return_type << ToFunction->getResultType()
2580235633Sdim          << FromFunction->getResultType();
2581235633Sdim    return;
2582235633Sdim  }
2583235633Sdim
2584235633Sdim  unsigned FromQuals = FromFunction->getTypeQuals(),
2585235633Sdim           ToQuals = ToFunction->getTypeQuals();
2586235633Sdim  if (FromQuals != ToQuals) {
2587235633Sdim    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2588235633Sdim    return;
2589235633Sdim  }
2590235633Sdim
2591235633Sdim  // Unable to find a difference, so add no extra info.
2592235633Sdim  PDiag << ft_default;
2593235633Sdim}
2594235633Sdim
2595207619Srdivacky/// FunctionArgTypesAreEqual - This routine checks two function proto types
2596235633Sdim/// for equality of their argument types. Caller has already checked that
2597263509Sdim/// they have same number of arguments.  If the parameters are different,
2598263509Sdim/// ArgPos will have the parameter index of the first different parameter.
2599218893Sdimbool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2600235633Sdim                                    const FunctionProtoType *NewType,
2601235633Sdim                                    unsigned *ArgPos) {
2602207619Srdivacky  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2603207619Srdivacky       N = NewType->arg_type_begin(),
2604207619Srdivacky       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2605263509Sdim    if (!Context.hasSameType(O->getUnqualifiedType(),
2606263509Sdim                             N->getUnqualifiedType())) {
2607235633Sdim      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2608218893Sdim      return false;
2609207619Srdivacky    }
2610207619Srdivacky  }
2611207619Srdivacky  return true;
2612207619Srdivacky}
2613193326Sed
2614193326Sed/// CheckPointerConversion - Check the pointer conversion from the
2615193326Sed/// expression From to the type ToType. This routine checks for
2616198092Srdivacky/// ambiguous or inaccessible derived-to-base pointer
2617193326Sed/// conversions for which IsPointerConversion has already returned
2618193326Sed/// true. It returns true and produces a diagnostic if there was an
2619193326Sed/// error, or returns false otherwise.
2620198092Srdivackybool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2621212904Sdim                                  CastKind &Kind,
2622212904Sdim                                  CXXCastPath& BasePath,
2623199482Srdivacky                                  bool IgnoreBaseAccess) {
2624193326Sed  QualType FromType = From->getType();
2625218893Sdim  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2626193326Sed
2627218893Sdim  Kind = CK_BitCast;
2628218893Sdim
2629245431Sdim  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2630245431Sdim      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2631245431Sdim      Expr::NPCK_ZeroExpression) {
2632245431Sdim    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2633245431Sdim      DiagRuntimeBehavior(From->getExprLoc(), From,
2634245431Sdim                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2635245431Sdim                            << ToType << From->getSourceRange());
2636245431Sdim    else if (!isUnevaluatedContext())
2637245431Sdim      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2638245431Sdim        << ToType << From->getSourceRange();
2639245431Sdim  }
2640226890Sdim  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2641226890Sdim    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2642193326Sed      QualType FromPointeeType = FromPtrType->getPointeeType(),
2643193326Sed               ToPointeeType   = ToPtrType->getPointeeType();
2644193326Sed
2645204793Srdivacky      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2646204793Srdivacky          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2647193326Sed        // We must have a derived-to-base conversion. Check an
2648193326Sed        // ambiguous or inaccessible conversion.
2649198092Srdivacky        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2650198092Srdivacky                                         From->getExprLoc(),
2651207619Srdivacky                                         From->getSourceRange(), &BasePath,
2652199482Srdivacky                                         IgnoreBaseAccess))
2653198092Srdivacky          return true;
2654218893Sdim
2655198092Srdivacky        // The conversion was successful.
2656212904Sdim        Kind = CK_DerivedToBase;
2657193326Sed      }
2658193326Sed    }
2659226890Sdim  } else if (const ObjCObjectPointerType *ToPtrType =
2660226890Sdim               ToType->getAs<ObjCObjectPointerType>()) {
2661226890Sdim    if (const ObjCObjectPointerType *FromPtrType =
2662226890Sdim          FromType->getAs<ObjCObjectPointerType>()) {
2663198092Srdivacky      // Objective-C++ conversions are always okay.
2664198092Srdivacky      // FIXME: We should have a different class of conversions for the
2665198092Srdivacky      // Objective-C++ implicit conversions.
2666198092Srdivacky      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2667198092Srdivacky        return false;
2668226890Sdim    } else if (FromType->isBlockPointerType()) {
2669226890Sdim      Kind = CK_BlockPointerToObjCPointerCast;
2670226890Sdim    } else {
2671226890Sdim      Kind = CK_CPointerToObjCPointerCast;
2672218893Sdim    }
2673226890Sdim  } else if (ToType->isBlockPointerType()) {
2674226890Sdim    if (!FromType->isBlockPointerType())
2675226890Sdim      Kind = CK_AnyPointerToBlockPointerCast;
2676218893Sdim  }
2677193326Sed
2678218893Sdim  // We shouldn't fall into this case unless it's valid for other
2679218893Sdim  // reasons.
2680218893Sdim  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2681218893Sdim    Kind = CK_NullToPointer;
2682218893Sdim
2683193326Sed  return false;
2684193326Sed}
2685193326Sed
2686193326Sed/// IsMemberPointerConversion - Determines whether the conversion of the
2687193326Sed/// expression From, which has the (possibly adjusted) type FromType, can be
2688193326Sed/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2689193326Sed/// If so, returns true and places the converted type (that might differ from
2690193326Sed/// ToType in its cv-qualifiers at some level) into ConvertedType.
2691193326Sedbool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2692218893Sdim                                     QualType ToType,
2693198092Srdivacky                                     bool InOverloadResolution,
2694198092Srdivacky                                     QualType &ConvertedType) {
2695198092Srdivacky  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2696193326Sed  if (!ToTypePtr)
2697193326Sed    return false;
2698193326Sed
2699193326Sed  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2700198092Srdivacky  if (From->isNullPointerConstant(Context,
2701198092Srdivacky                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2702198092Srdivacky                                        : Expr::NPC_ValueDependentIsNull)) {
2703193326Sed    ConvertedType = ToType;
2704193326Sed    return true;
2705193326Sed  }
2706193326Sed
2707193326Sed  // Otherwise, both types have to be member pointers.
2708198092Srdivacky  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2709193326Sed  if (!FromTypePtr)
2710193326Sed    return false;
2711193326Sed
2712193326Sed  // A pointer to member of B can be converted to a pointer to member of D,
2713193326Sed  // where D is derived from B (C++ 4.11p2).
2714193326Sed  QualType FromClass(FromTypePtr->getClass(), 0);
2715193326Sed  QualType ToClass(ToTypePtr->getClass(), 0);
2716193326Sed
2717218893Sdim  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2718245431Sdim      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2719218893Sdim      IsDerivedFrom(ToClass, FromClass)) {
2720193326Sed    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2721193326Sed                                                 ToClass.getTypePtr());
2722193326Sed    return true;
2723193326Sed  }
2724193326Sed
2725193326Sed  return false;
2726193326Sed}
2727218893Sdim
2728193326Sed/// CheckMemberPointerConversion - Check the member pointer conversion from the
2729193326Sed/// expression From to the type ToType. This routine checks for ambiguous or
2730203955Srdivacky/// virtual or inaccessible base-to-derived member pointer conversions
2731193326Sed/// for which IsMemberPointerConversion has already returned true. It returns
2732193326Sed/// true and produces a diagnostic if there was an error, or returns false
2733193326Sed/// otherwise.
2734198092Srdivackybool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2735212904Sdim                                        CastKind &Kind,
2736212904Sdim                                        CXXCastPath &BasePath,
2737199482Srdivacky                                        bool IgnoreBaseAccess) {
2738193326Sed  QualType FromType = From->getType();
2739198092Srdivacky  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2740198092Srdivacky  if (!FromPtrType) {
2741198092Srdivacky    // This must be a null pointer to member pointer conversion
2742218893Sdim    assert(From->isNullPointerConstant(Context,
2743198092Srdivacky                                       Expr::NPC_ValueDependentIsNull) &&
2744198092Srdivacky           "Expr must be null pointer constant!");
2745212904Sdim    Kind = CK_NullToMemberPointer;
2746193326Sed    return false;
2747198092Srdivacky  }
2748193326Sed
2749198092Srdivacky  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2750193326Sed  assert(ToPtrType && "No member pointer cast has a target type "
2751193326Sed                      "that is not a member pointer.");
2752193326Sed
2753193326Sed  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2754193326Sed  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2755193326Sed
2756193326Sed  // FIXME: What about dependent types?
2757193326Sed  assert(FromClass->isRecordType() && "Pointer into non-class.");
2758193326Sed  assert(ToClass->isRecordType() && "Pointer into non-class.");
2759193326Sed
2760207619Srdivacky  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2761198092Srdivacky                     /*DetectVirtual=*/true);
2762193326Sed  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2763193326Sed  assert(DerivationOkay &&
2764193326Sed         "Should not have been called if derivation isn't OK.");
2765193326Sed  (void)DerivationOkay;
2766193326Sed
2767193326Sed  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2768193326Sed                                  getUnqualifiedType())) {
2769193326Sed    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2770193326Sed    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2771193326Sed      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2772193326Sed    return true;
2773193326Sed  }
2774193326Sed
2775193326Sed  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2776193326Sed    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2777193326Sed      << FromClass << ToClass << QualType(VBase, 0)
2778193326Sed      << From->getSourceRange();
2779193326Sed    return true;
2780193326Sed  }
2781193326Sed
2782203955Srdivacky  if (!IgnoreBaseAccess)
2783205219Srdivacky    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2784205219Srdivacky                         Paths.front(),
2785205219Srdivacky                         diag::err_downcast_from_inaccessible_base);
2786203955Srdivacky
2787198092Srdivacky  // Must be a base to derived member conversion.
2788207619Srdivacky  BuildBasePathArray(Paths, BasePath);
2789212904Sdim  Kind = CK_BaseToDerivedMemberPointer;
2790193326Sed  return false;
2791193326Sed}
2792193326Sed
2793263509Sdim/// Determine whether the lifetime conversion between the two given
2794263509Sdim/// qualifiers sets is nontrivial.
2795263509Sdimstatic bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2796263509Sdim                                               Qualifiers ToQuals) {
2797263509Sdim  // Converting anything to const __unsafe_unretained is trivial.
2798263509Sdim  if (ToQuals.hasConst() &&
2799263509Sdim      ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2800263509Sdim    return false;
2801263509Sdim
2802263509Sdim  return true;
2803263509Sdim}
2804263509Sdim
2805193326Sed/// IsQualificationConversion - Determines whether the conversion from
2806193326Sed/// an rvalue of type FromType to ToType is a qualification conversion
2807193326Sed/// (C++ 4.4).
2808224145Sdim///
2809224145Sdim/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2810224145Sdim/// when the qualification conversion involves a change in the Objective-C
2811224145Sdim/// object lifetime.
2812198092Srdivackybool
2813218893SdimSema::IsQualificationConversion(QualType FromType, QualType ToType,
2814224145Sdim                                bool CStyle, bool &ObjCLifetimeConversion) {
2815193326Sed  FromType = Context.getCanonicalType(FromType);
2816193326Sed  ToType = Context.getCanonicalType(ToType);
2817224145Sdim  ObjCLifetimeConversion = false;
2818224145Sdim
2819193326Sed  // If FromType and ToType are the same type, this is not a
2820193326Sed  // qualification conversion.
2821203955Srdivacky  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2822193326Sed    return false;
2823193326Sed
2824193326Sed  // (C++ 4.4p4):
2825193326Sed  //   A conversion can add cv-qualifiers at levels other than the first
2826193326Sed  //   in multi-level pointers, subject to the following rules: [...]
2827193326Sed  bool PreviousToQualsIncludeConst = true;
2828193326Sed  bool UnwrappedAnyPointer = false;
2829210299Sed  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2830193326Sed    // Within each iteration of the loop, we check the qualifiers to
2831193326Sed    // determine if this still looks like a qualification
2832193326Sed    // conversion. Then, if all is well, we unwrap one more level of
2833193326Sed    // pointers or pointers-to-members and do it all again
2834193326Sed    // until there are no more pointers or pointers-to-members left to
2835193326Sed    // unwrap.
2836193326Sed    UnwrappedAnyPointer = true;
2837193326Sed
2838221345Sdim    Qualifiers FromQuals = FromType.getQualifiers();
2839221345Sdim    Qualifiers ToQuals = ToType.getQualifiers();
2840221345Sdim
2841224145Sdim    // Objective-C ARC:
2842224145Sdim    //   Check Objective-C lifetime conversions.
2843224145Sdim    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2844224145Sdim        UnwrappedAnyPointer) {
2845224145Sdim      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2846263509Sdim        if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2847263509Sdim          ObjCLifetimeConversion = true;
2848224145Sdim        FromQuals.removeObjCLifetime();
2849224145Sdim        ToQuals.removeObjCLifetime();
2850224145Sdim      } else {
2851224145Sdim        // Qualification conversions cannot cast between different
2852224145Sdim        // Objective-C lifetime qualifiers.
2853224145Sdim        return false;
2854224145Sdim      }
2855224145Sdim    }
2856224145Sdim
2857223017Sdim    // Allow addition/removal of GC attributes but not changing GC attributes.
2858223017Sdim    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2859223017Sdim        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2860223017Sdim      FromQuals.removeObjCGCAttr();
2861223017Sdim      ToQuals.removeObjCGCAttr();
2862223017Sdim    }
2863223017Sdim
2864193326Sed    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2865193326Sed    //      2,j, and similarly for volatile.
2866221345Sdim    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2867193326Sed      return false;
2868198092Srdivacky
2869193326Sed    //   -- if the cv 1,j and cv 2,j are different, then const is in
2870193326Sed    //      every cv for 0 < k < j.
2871221345Sdim    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2872193326Sed        && !PreviousToQualsIncludeConst)
2873193326Sed      return false;
2874198092Srdivacky
2875193326Sed    // Keep track of whether all prior cv-qualifiers in the "to" type
2876193326Sed    // include const.
2877198092Srdivacky    PreviousToQualsIncludeConst
2878221345Sdim      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2879193326Sed  }
2880193326Sed
2881193326Sed  // We are left with FromType and ToType being the pointee types
2882193326Sed  // after unwrapping the original FromType and ToType the same number
2883193326Sed  // of types. If we unwrapped any pointers, and if FromType and
2884193326Sed  // ToType have the same unqualified type (since we checked
2885193326Sed  // qualifiers above), then this is a qualification conversion.
2886199482Srdivacky  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2887193326Sed}
2888193326Sed
2889235633Sdim/// \brief - Determine whether this is a conversion from a scalar type to an
2890235633Sdim/// atomic type.
2891235633Sdim///
2892235633Sdim/// If successful, updates \c SCS's second and third steps in the conversion
2893235633Sdim/// sequence to finish the conversion.
2894235633Sdimstatic bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2895235633Sdim                                bool InOverloadResolution,
2896235633Sdim                                StandardConversionSequence &SCS,
2897235633Sdim                                bool CStyle) {
2898235633Sdim  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2899235633Sdim  if (!ToAtomic)
2900235633Sdim    return false;
2901235633Sdim
2902235633Sdim  StandardConversionSequence InnerSCS;
2903235633Sdim  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2904235633Sdim                            InOverloadResolution, InnerSCS,
2905235633Sdim                            CStyle, /*AllowObjCWritebackConversion=*/false))
2906235633Sdim    return false;
2907235633Sdim
2908235633Sdim  SCS.Second = InnerSCS.Second;
2909235633Sdim  SCS.setToType(1, InnerSCS.getToType(1));
2910235633Sdim  SCS.Third = InnerSCS.Third;
2911235633Sdim  SCS.QualificationIncludesObjCLifetime
2912235633Sdim    = InnerSCS.QualificationIncludesObjCLifetime;
2913235633Sdim  SCS.setToType(2, InnerSCS.getToType(2));
2914235633Sdim  return true;
2915235633Sdim}
2916235633Sdim
2917235633Sdimstatic bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2918235633Sdim                                              CXXConstructorDecl *Constructor,
2919235633Sdim                                              QualType Type) {
2920235633Sdim  const FunctionProtoType *CtorType =
2921235633Sdim      Constructor->getType()->getAs<FunctionProtoType>();
2922235633Sdim  if (CtorType->getNumArgs() > 0) {
2923235633Sdim    QualType FirstArg = CtorType->getArgType(0);
2924235633Sdim    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2925235633Sdim      return true;
2926235633Sdim  }
2927235633Sdim  return false;
2928235633Sdim}
2929235633Sdim
2930235633Sdimstatic OverloadingResult
2931235633SdimIsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2932235633Sdim                                       CXXRecordDecl *To,
2933235633Sdim                                       UserDefinedConversionSequence &User,
2934235633Sdim                                       OverloadCandidateSet &CandidateSet,
2935235633Sdim                                       bool AllowExplicit) {
2936252723Sdim  DeclContext::lookup_result R = S.LookupConstructors(To);
2937252723Sdim  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2938235633Sdim       Con != ConEnd; ++Con) {
2939235633Sdim    NamedDecl *D = *Con;
2940235633Sdim    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2941235633Sdim
2942235633Sdim    // Find the constructor (which may be a template).
2943235633Sdim    CXXConstructorDecl *Constructor = 0;
2944235633Sdim    FunctionTemplateDecl *ConstructorTmpl
2945235633Sdim      = dyn_cast<FunctionTemplateDecl>(D);
2946235633Sdim    if (ConstructorTmpl)
2947235633Sdim      Constructor
2948235633Sdim        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2949235633Sdim    else
2950235633Sdim      Constructor = cast<CXXConstructorDecl>(D);
2951235633Sdim
2952235633Sdim    bool Usable = !Constructor->isInvalidDecl() &&
2953235633Sdim                  S.isInitListConstructor(Constructor) &&
2954235633Sdim                  (AllowExplicit || !Constructor->isExplicit());
2955235633Sdim    if (Usable) {
2956235633Sdim      // If the first argument is (a reference to) the target type,
2957235633Sdim      // suppress conversions.
2958235633Sdim      bool SuppressUserConversions =
2959235633Sdim          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2960235633Sdim      if (ConstructorTmpl)
2961235633Sdim        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2962235633Sdim                                       /*ExplicitArgs*/ 0,
2963235633Sdim                                       From, CandidateSet,
2964235633Sdim                                       SuppressUserConversions);
2965235633Sdim      else
2966235633Sdim        S.AddOverloadCandidate(Constructor, FoundDecl,
2967235633Sdim                               From, CandidateSet,
2968235633Sdim                               SuppressUserConversions);
2969235633Sdim    }
2970235633Sdim  }
2971235633Sdim
2972235633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2973235633Sdim
2974235633Sdim  OverloadCandidateSet::iterator Best;
2975235633Sdim  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2976235633Sdim  case OR_Success: {
2977235633Sdim    // Record the standard conversion we used and the conversion function.
2978235633Sdim    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2979235633Sdim    QualType ThisType = Constructor->getThisType(S.Context);
2980235633Sdim    // Initializer lists don't have conversions as such.
2981235633Sdim    User.Before.setAsIdentityConversion();
2982235633Sdim    User.HadMultipleCandidates = HadMultipleCandidates;
2983235633Sdim    User.ConversionFunction = Constructor;
2984235633Sdim    User.FoundConversionFunction = Best->FoundDecl;
2985235633Sdim    User.After.setAsIdentityConversion();
2986235633Sdim    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2987235633Sdim    User.After.setAllToTypes(ToType);
2988235633Sdim    return OR_Success;
2989235633Sdim  }
2990235633Sdim
2991235633Sdim  case OR_No_Viable_Function:
2992235633Sdim    return OR_No_Viable_Function;
2993235633Sdim  case OR_Deleted:
2994235633Sdim    return OR_Deleted;
2995235633Sdim  case OR_Ambiguous:
2996235633Sdim    return OR_Ambiguous;
2997235633Sdim  }
2998235633Sdim
2999235633Sdim  llvm_unreachable("Invalid OverloadResult!");
3000235633Sdim}
3001235633Sdim
3002193326Sed/// Determines whether there is a user-defined conversion sequence
3003193326Sed/// (C++ [over.ics.user]) that converts expression From to the type
3004193326Sed/// ToType. If such a conversion exists, User will contain the
3005193326Sed/// user-defined conversion sequence that performs such a conversion
3006193326Sed/// and this routine will return true. Otherwise, this routine returns
3007193326Sed/// false and User is unspecified.
3008193326Sed///
3009193326Sed/// \param AllowExplicit  true if the conversion should consider C++0x
3010193326Sed/// "explicit" conversion functions as well as non-explicit conversion
3011193326Sed/// functions (C++0x [class.conv.fct]p2).
3012263509Sdim///
3013263509Sdim/// \param AllowObjCConversionOnExplicit true if the conversion should
3014263509Sdim/// allow an extra Objective-C pointer conversion on uses of explicit
3015263509Sdim/// constructors. Requires \c AllowExplicit to also be set.
3016212904Sdimstatic OverloadingResult
3017212904SdimIsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3018235633Sdim                        UserDefinedConversionSequence &User,
3019235633Sdim                        OverloadCandidateSet &CandidateSet,
3020263509Sdim                        bool AllowExplicit,
3021263509Sdim                        bool AllowObjCConversionOnExplicit) {
3022263509Sdim  assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3023263509Sdim
3024207619Srdivacky  // Whether we will only visit constructors.
3025207619Srdivacky  bool ConstructorsOnly = false;
3026207619Srdivacky
3027207619Srdivacky  // If the type we are conversion to is a class type, enumerate its
3028207619Srdivacky  // constructors.
3029198092Srdivacky  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3030207619Srdivacky    // C++ [over.match.ctor]p1:
3031207619Srdivacky    //   When objects of class type are direct-initialized (8.5), or
3032207619Srdivacky    //   copy-initialized from an expression of the same or a
3033207619Srdivacky    //   derived class type (8.5), overload resolution selects the
3034207619Srdivacky    //   constructor. [...] For copy-initialization, the candidate
3035207619Srdivacky    //   functions are all the converting constructors (12.3.1) of
3036207619Srdivacky    //   that class. The argument list is the expression-list within
3037207619Srdivacky    //   the parentheses of the initializer.
3038212904Sdim    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3039207619Srdivacky        (From->getType()->getAs<RecordType>() &&
3040212904Sdim         S.IsDerivedFrom(From->getType(), ToType)))
3041207619Srdivacky      ConstructorsOnly = true;
3042207619Srdivacky
3043252723Sdim    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3044221345Sdim    // RequireCompleteType may have returned true due to some invalid decl
3045221345Sdim    // during template instantiation, but ToType may be complete enough now
3046221345Sdim    // to try to recover.
3047221345Sdim    if (ToType->isIncompleteType()) {
3048198954Srdivacky      // We're not going to find any constructors.
3049198954Srdivacky    } else if (CXXRecordDecl *ToRecordDecl
3050198954Srdivacky                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3051235633Sdim
3052235633Sdim      Expr **Args = &From;
3053235633Sdim      unsigned NumArgs = 1;
3054235633Sdim      bool ListInitializing = false;
3055235633Sdim      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3056263509Sdim        // But first, see if there is an init-list-constructor that will work.
3057235633Sdim        OverloadingResult Result = IsInitializerListConstructorConversion(
3058235633Sdim            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3059235633Sdim        if (Result != OR_No_Viable_Function)
3060235633Sdim          return Result;
3061235633Sdim        // Never mind.
3062235633Sdim        CandidateSet.clear();
3063235633Sdim
3064235633Sdim        // If we're list-initializing, we pass the individual elements as
3065235633Sdim        // arguments, not the entire list.
3066235633Sdim        Args = InitList->getInits();
3067235633Sdim        NumArgs = InitList->getNumInits();
3068235633Sdim        ListInitializing = true;
3069235633Sdim      }
3070235633Sdim
3071252723Sdim      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3072252723Sdim      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3073193326Sed           Con != ConEnd; ++Con) {
3074205408Srdivacky        NamedDecl *D = *Con;
3075205408Srdivacky        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3076205408Srdivacky
3077198092Srdivacky        // Find the constructor (which may be a template).
3078198092Srdivacky        CXXConstructorDecl *Constructor = 0;
3079198092Srdivacky        FunctionTemplateDecl *ConstructorTmpl
3080205408Srdivacky          = dyn_cast<FunctionTemplateDecl>(D);
3081198092Srdivacky        if (ConstructorTmpl)
3082198092Srdivacky          Constructor
3083198092Srdivacky            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3084198092Srdivacky        else
3085205408Srdivacky          Constructor = cast<CXXConstructorDecl>(D);
3086218893Sdim
3087235633Sdim        bool Usable = !Constructor->isInvalidDecl();
3088235633Sdim        if (ListInitializing)
3089235633Sdim          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3090235633Sdim        else
3091235633Sdim          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3092235633Sdim        if (Usable) {
3093235633Sdim          bool SuppressUserConversions = !ConstructorsOnly;
3094235633Sdim          if (SuppressUserConversions && ListInitializing) {
3095235633Sdim            SuppressUserConversions = false;
3096235633Sdim            if (NumArgs == 1) {
3097235633Sdim              // If the first argument is (a reference to) the target type,
3098235633Sdim              // suppress conversions.
3099235633Sdim              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3100235633Sdim                                                S.Context, Constructor, ToType);
3101235633Sdim            }
3102235633Sdim          }
3103198092Srdivacky          if (ConstructorTmpl)
3104212904Sdim            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3105212904Sdim                                           /*ExplicitArgs*/ 0,
3106235633Sdim                                           llvm::makeArrayRef(Args, NumArgs),
3107235633Sdim                                           CandidateSet, SuppressUserConversions);
3108198092Srdivacky          else
3109198092Srdivacky            // Allow one user-defined conversion when user specifies a
3110198092Srdivacky            // From->ToType conversion via an static cast (c-style, etc).
3111212904Sdim            S.AddOverloadCandidate(Constructor, FoundDecl,
3112235633Sdim                                   llvm::makeArrayRef(Args, NumArgs),
3113235633Sdim                                   CandidateSet, SuppressUserConversions);
3114198092Srdivacky        }
3115193326Sed      }
3116193326Sed    }
3117193326Sed  }
3118193326Sed
3119207619Srdivacky  // Enumerate conversion functions, if we're allowed to.
3120235633Sdim  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3121245431Sdim  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3122198092Srdivacky    // No conversion functions from incomplete types.
3123198092Srdivacky  } else if (const RecordType *FromRecordType
3124207619Srdivacky                                   = From->getType()->getAs<RecordType>()) {
3125198092Srdivacky    if (CXXRecordDecl *FromRecordDecl
3126198092Srdivacky         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3127193326Sed      // Add all of the conversion functions as candidates.
3128252723Sdim      std::pair<CXXRecordDecl::conversion_iterator,
3129252723Sdim                CXXRecordDecl::conversion_iterator>
3130252723Sdim        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3131252723Sdim      for (CXXRecordDecl::conversion_iterator
3132252723Sdim             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3133205408Srdivacky        DeclAccessPair FoundDecl = I.getPair();
3134205408Srdivacky        NamedDecl *D = FoundDecl.getDecl();
3135200583Srdivacky        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3136200583Srdivacky        if (isa<UsingShadowDecl>(D))
3137200583Srdivacky          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3138200583Srdivacky
3139198092Srdivacky        CXXConversionDecl *Conv;
3140198092Srdivacky        FunctionTemplateDecl *ConvTemplate;
3141206084Srdivacky        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3142206084Srdivacky          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3143198092Srdivacky        else
3144206084Srdivacky          Conv = cast<CXXConversionDecl>(D);
3145198092Srdivacky
3146198092Srdivacky        if (AllowExplicit || !Conv->isExplicit()) {
3147198092Srdivacky          if (ConvTemplate)
3148212904Sdim            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3149212904Sdim                                             ActingContext, From, ToType,
3150263509Sdim                                             CandidateSet,
3151263509Sdim                                             AllowObjCConversionOnExplicit);
3152198092Srdivacky          else
3153212904Sdim            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3154263509Sdim                                     From, ToType, CandidateSet,
3155263509Sdim                                     AllowObjCConversionOnExplicit);
3156198092Srdivacky        }
3157193326Sed      }
3158193326Sed    }
3159193326Sed  }
3160193326Sed
3161226890Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3162226890Sdim
3163193326Sed  OverloadCandidateSet::iterator Best;
3164218893Sdim  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3165212904Sdim  case OR_Success:
3166212904Sdim    // Record the standard conversion we used and the conversion function.
3167212904Sdim    if (CXXConstructorDecl *Constructor
3168212904Sdim          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3169212904Sdim      // C++ [over.ics.user]p1:
3170212904Sdim      //   If the user-defined conversion is specified by a
3171212904Sdim      //   constructor (12.3.1), the initial standard conversion
3172212904Sdim      //   sequence converts the source type to the type required by
3173212904Sdim      //   the argument of the constructor.
3174212904Sdim      //
3175212904Sdim      QualType ThisType = Constructor->getThisType(S.Context);
3176235633Sdim      if (isa<InitListExpr>(From)) {
3177235633Sdim        // Initializer lists don't have conversions as such.
3178235633Sdim        User.Before.setAsIdentityConversion();
3179235633Sdim      } else {
3180235633Sdim        if (Best->Conversions[0].isEllipsis())
3181235633Sdim          User.EllipsisConversion = true;
3182235633Sdim        else {
3183235633Sdim          User.Before = Best->Conversions[0].Standard;
3184235633Sdim          User.EllipsisConversion = false;
3185235633Sdim        }
3186193326Sed      }
3187226890Sdim      User.HadMultipleCandidates = HadMultipleCandidates;
3188212904Sdim      User.ConversionFunction = Constructor;
3189226890Sdim      User.FoundConversionFunction = Best->FoundDecl;
3190212904Sdim      User.After.setAsIdentityConversion();
3191212904Sdim      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3192212904Sdim      User.After.setAllToTypes(ToType);
3193212904Sdim      return OR_Success;
3194235633Sdim    }
3195235633Sdim    if (CXXConversionDecl *Conversion
3196212904Sdim                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3197212904Sdim      // C++ [over.ics.user]p1:
3198212904Sdim      //
3199212904Sdim      //   [...] If the user-defined conversion is specified by a
3200212904Sdim      //   conversion function (12.3.2), the initial standard
3201212904Sdim      //   conversion sequence converts the source type to the
3202212904Sdim      //   implicit object parameter of the conversion function.
3203212904Sdim      User.Before = Best->Conversions[0].Standard;
3204226890Sdim      User.HadMultipleCandidates = HadMultipleCandidates;
3205212904Sdim      User.ConversionFunction = Conversion;
3206226890Sdim      User.FoundConversionFunction = Best->FoundDecl;
3207212904Sdim      User.EllipsisConversion = false;
3208198092Srdivacky
3209212904Sdim      // C++ [over.ics.user]p2:
3210212904Sdim      //   The second standard conversion sequence converts the
3211212904Sdim      //   result of the user-defined conversion to the target type
3212212904Sdim      //   for the sequence. Since an implicit conversion sequence
3213212904Sdim      //   is an initialization, the special rules for
3214212904Sdim      //   initialization by user-defined conversion apply when
3215212904Sdim      //   selecting the best user-defined conversion for a
3216212904Sdim      //   user-defined conversion sequence (see 13.3.3 and
3217212904Sdim      //   13.3.3.1).
3218212904Sdim      User.After = Best->FinalConversion;
3219212904Sdim      return OR_Success;
3220193326Sed    }
3221235633Sdim    llvm_unreachable("Not a constructor or conversion function?");
3222193326Sed
3223212904Sdim  case OR_No_Viable_Function:
3224212904Sdim    return OR_No_Viable_Function;
3225212904Sdim  case OR_Deleted:
3226212904Sdim    // No conversion here! We're done.
3227212904Sdim    return OR_Deleted;
3228218893Sdim
3229212904Sdim  case OR_Ambiguous:
3230212904Sdim    return OR_Ambiguous;
3231212904Sdim  }
3232212904Sdim
3233235633Sdim  llvm_unreachable("Invalid OverloadResult!");
3234193326Sed}
3235218893Sdim
3236198092Srdivackybool
3237199512SrdivackySema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3238198092Srdivacky  ImplicitConversionSequence ICS;
3239203955Srdivacky  OverloadCandidateSet CandidateSet(From->getExprLoc());
3240218893Sdim  OverloadingResult OvResult =
3241212904Sdim    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3242263509Sdim                            CandidateSet, false, false);
3243199512Srdivacky  if (OvResult == OR_Ambiguous)
3244235633Sdim    Diag(From->getLocStart(),
3245199512Srdivacky         diag::err_typecheck_ambiguous_condition)
3246199512Srdivacky          << From->getType() << ToType << From->getSourceRange();
3247263509Sdim  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3248263509Sdim    if (!RequireCompleteType(From->getLocStart(), ToType,
3249263509Sdim                          diag::err_typecheck_nonviable_condition_incomplete,
3250263509Sdim                             From->getType(), From->getSourceRange()))
3251263509Sdim      Diag(From->getLocStart(),
3252263509Sdim           diag::err_typecheck_nonviable_condition)
3253263509Sdim           << From->getType() << From->getSourceRange() << ToType;
3254263509Sdim  }
3255199512Srdivacky  else
3256198092Srdivacky    return false;
3257235633Sdim  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3258218893Sdim  return true;
3259198092Srdivacky}
3260193326Sed
3261235633Sdim/// \brief Compare the user-defined conversion functions or constructors
3262235633Sdim/// of two user-defined conversion sequences to determine whether any ordering
3263235633Sdim/// is possible.
3264235633Sdimstatic ImplicitConversionSequence::CompareKind
3265235633SdimcompareConversionFunctions(Sema &S,
3266235633Sdim                           FunctionDecl *Function1,
3267235633Sdim                           FunctionDecl *Function2) {
3268252723Sdim  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3269235633Sdim    return ImplicitConversionSequence::Indistinguishable;
3270235633Sdim
3271235633Sdim  // Objective-C++:
3272235633Sdim  //   If both conversion functions are implicitly-declared conversions from
3273235633Sdim  //   a lambda closure type to a function pointer and a block pointer,
3274235633Sdim  //   respectively, always prefer the conversion to a function pointer,
3275235633Sdim  //   because the function pointer is more lightweight and is more likely
3276235633Sdim  //   to keep code working.
3277235633Sdim  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3278235633Sdim  if (!Conv1)
3279235633Sdim    return ImplicitConversionSequence::Indistinguishable;
3280235633Sdim
3281235633Sdim  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3282235633Sdim  if (!Conv2)
3283235633Sdim    return ImplicitConversionSequence::Indistinguishable;
3284235633Sdim
3285235633Sdim  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3286235633Sdim    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3287235633Sdim    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3288235633Sdim    if (Block1 != Block2)
3289235633Sdim      return Block1? ImplicitConversionSequence::Worse
3290235633Sdim                   : ImplicitConversionSequence::Better;
3291235633Sdim  }
3292235633Sdim
3293235633Sdim  return ImplicitConversionSequence::Indistinguishable;
3294235633Sdim}
3295235633Sdim
3296193326Sed/// CompareImplicitConversionSequences - Compare two implicit
3297193326Sed/// conversion sequences to determine whether one is better than the
3298193326Sed/// other or if they are indistinguishable (C++ 13.3.3.2).
3299212904Sdimstatic ImplicitConversionSequence::CompareKind
3300212904SdimCompareImplicitConversionSequences(Sema &S,
3301212904Sdim                                   const ImplicitConversionSequence& ICS1,
3302212904Sdim                                   const ImplicitConversionSequence& ICS2)
3303193326Sed{
3304193326Sed  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3305193326Sed  // conversion sequences (as defined in 13.3.3.1)
3306193326Sed  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3307193326Sed  //      conversion sequence than a user-defined conversion sequence or
3308193326Sed  //      an ellipsis conversion sequence, and
3309193326Sed  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3310193326Sed  //      conversion sequence than an ellipsis conversion sequence
3311193326Sed  //      (13.3.3.1.3).
3312198092Srdivacky  //
3313202379Srdivacky  // C++0x [over.best.ics]p10:
3314202379Srdivacky  //   For the purpose of ranking implicit conversion sequences as
3315202379Srdivacky  //   described in 13.3.3.2, the ambiguous conversion sequence is
3316202379Srdivacky  //   treated as a user-defined sequence that is indistinguishable
3317202379Srdivacky  //   from any other user-defined conversion sequence.
3318207619Srdivacky  if (ICS1.getKindRank() < ICS2.getKindRank())
3319207619Srdivacky    return ImplicitConversionSequence::Better;
3320235633Sdim  if (ICS2.getKindRank() < ICS1.getKindRank())
3321207619Srdivacky    return ImplicitConversionSequence::Worse;
3322193326Sed
3323207619Srdivacky  // The following checks require both conversion sequences to be of
3324207619Srdivacky  // the same kind.
3325207619Srdivacky  if (ICS1.getKind() != ICS2.getKind())
3326202379Srdivacky    return ImplicitConversionSequence::Indistinguishable;
3327202379Srdivacky
3328235633Sdim  ImplicitConversionSequence::CompareKind Result =
3329235633Sdim      ImplicitConversionSequence::Indistinguishable;
3330235633Sdim
3331193326Sed  // Two implicit conversion sequences of the same form are
3332193326Sed  // indistinguishable conversion sequences unless one of the
3333193326Sed  // following rules apply: (C++ 13.3.3.2p3):
3334202379Srdivacky  if (ICS1.isStandard())
3335235633Sdim    Result = CompareStandardConversionSequences(S,
3336235633Sdim                                                ICS1.Standard, ICS2.Standard);
3337202379Srdivacky  else if (ICS1.isUserDefined()) {
3338193326Sed    // User-defined conversion sequence U1 is a better conversion
3339193326Sed    // sequence than another user-defined conversion sequence U2 if
3340193326Sed    // they contain the same user-defined conversion function or
3341193326Sed    // constructor and if the second standard conversion sequence of
3342193326Sed    // U1 is better than the second standard conversion sequence of
3343193326Sed    // U2 (C++ 13.3.3.2p3).
3344198092Srdivacky    if (ICS1.UserDefined.ConversionFunction ==
3345193326Sed          ICS2.UserDefined.ConversionFunction)
3346235633Sdim      Result = CompareStandardConversionSequences(S,
3347235633Sdim                                                  ICS1.UserDefined.After,
3348235633Sdim                                                  ICS2.UserDefined.After);
3349235633Sdim    else
3350235633Sdim      Result = compareConversionFunctions(S,
3351235633Sdim                                          ICS1.UserDefined.ConversionFunction,
3352235633Sdim                                          ICS2.UserDefined.ConversionFunction);
3353193326Sed  }
3354193326Sed
3355235633Sdim  // List-initialization sequence L1 is a better conversion sequence than
3356235633Sdim  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3357235633Sdim  // for some X and L2 does not.
3358235633Sdim  if (Result == ImplicitConversionSequence::Indistinguishable &&
3359263509Sdim      !ICS1.isBad()) {
3360235633Sdim    if (ICS1.isStdInitializerListElement() &&
3361235633Sdim        !ICS2.isStdInitializerListElement())
3362235633Sdim      return ImplicitConversionSequence::Better;
3363235633Sdim    if (!ICS1.isStdInitializerListElement() &&
3364235633Sdim        ICS2.isStdInitializerListElement())
3365235633Sdim      return ImplicitConversionSequence::Worse;
3366235633Sdim  }
3367235633Sdim
3368235633Sdim  return Result;
3369193326Sed}
3370193326Sed
3371210299Sedstatic bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3372210299Sed  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3373210299Sed    Qualifiers Quals;
3374210299Sed    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3375218893Sdim    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3376210299Sed  }
3377218893Sdim
3378210299Sed  return Context.hasSameUnqualifiedType(T1, T2);
3379210299Sed}
3380218893Sdim
3381203955Srdivacky// Per 13.3.3.2p3, compare the given standard conversion sequences to
3382203955Srdivacky// determine if one is a proper subset of the other.
3383203955Srdivackystatic ImplicitConversionSequence::CompareKind
3384203955SrdivackycompareStandardConversionSubsets(ASTContext &Context,
3385203955Srdivacky                                 const StandardConversionSequence& SCS1,
3386203955Srdivacky                                 const StandardConversionSequence& SCS2) {
3387203955Srdivacky  ImplicitConversionSequence::CompareKind Result
3388203955Srdivacky    = ImplicitConversionSequence::Indistinguishable;
3389203955Srdivacky
3390218893Sdim  // the identity conversion sequence is considered to be a subsequence of
3391208600Srdivacky  // any non-identity conversion sequence
3392223017Sdim  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3393223017Sdim    return ImplicitConversionSequence::Better;
3394223017Sdim  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3395223017Sdim    return ImplicitConversionSequence::Worse;
3396218893Sdim
3397203955Srdivacky  if (SCS1.Second != SCS2.Second) {
3398203955Srdivacky    if (SCS1.Second == ICK_Identity)
3399203955Srdivacky      Result = ImplicitConversionSequence::Better;
3400203955Srdivacky    else if (SCS2.Second == ICK_Identity)
3401203955Srdivacky      Result = ImplicitConversionSequence::Worse;
3402203955Srdivacky    else
3403203955Srdivacky      return ImplicitConversionSequence::Indistinguishable;
3404210299Sed  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3405203955Srdivacky    return ImplicitConversionSequence::Indistinguishable;
3406203955Srdivacky
3407203955Srdivacky  if (SCS1.Third == SCS2.Third) {
3408203955Srdivacky    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3409203955Srdivacky                             : ImplicitConversionSequence::Indistinguishable;
3410203955Srdivacky  }
3411203955Srdivacky
3412203955Srdivacky  if (SCS1.Third == ICK_Identity)
3413203955Srdivacky    return Result == ImplicitConversionSequence::Worse
3414203955Srdivacky             ? ImplicitConversionSequence::Indistinguishable
3415203955Srdivacky             : ImplicitConversionSequence::Better;
3416203955Srdivacky
3417203955Srdivacky  if (SCS2.Third == ICK_Identity)
3418203955Srdivacky    return Result == ImplicitConversionSequence::Better
3419203955Srdivacky             ? ImplicitConversionSequence::Indistinguishable
3420203955Srdivacky             : ImplicitConversionSequence::Worse;
3421218893Sdim
3422203955Srdivacky  return ImplicitConversionSequence::Indistinguishable;
3423203955Srdivacky}
3424203955Srdivacky
3425218893Sdim/// \brief Determine whether one of the given reference bindings is better
3426218893Sdim/// than the other based on what kind of bindings they are.
3427218893Sdimstatic bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3428218893Sdim                                       const StandardConversionSequence &SCS2) {
3429218893Sdim  // C++0x [over.ics.rank]p3b4:
3430218893Sdim  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3431218893Sdim  //      implicit object parameter of a non-static member function declared
3432218893Sdim  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3433218893Sdim  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3434218893Sdim  //      lvalue reference to a function lvalue and S2 binds an rvalue
3435218893Sdim  //      reference*.
3436218893Sdim  //
3437218893Sdim  // FIXME: Rvalue references. We're going rogue with the above edits,
3438218893Sdim  // because the semantics in the current C++0x working paper (N3225 at the
3439218893Sdim  // time of this writing) break the standard definition of std::forward
3440218893Sdim  // and std::reference_wrapper when dealing with references to functions.
3441218893Sdim  // Proposed wording changes submitted to CWG for consideration.
3442218893Sdim  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3443218893Sdim      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3444218893Sdim    return false;
3445218893Sdim
3446218893Sdim  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3447218893Sdim          SCS2.IsLvalueReference) ||
3448218893Sdim         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3449218893Sdim          !SCS2.IsLvalueReference);
3450218893Sdim}
3451218893Sdim
3452193326Sed/// CompareStandardConversionSequences - Compare two standard
3453193326Sed/// conversion sequences to determine whether one is better than the
3454193326Sed/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3455212904Sdimstatic ImplicitConversionSequence::CompareKind
3456212904SdimCompareStandardConversionSequences(Sema &S,
3457212904Sdim                                   const StandardConversionSequence& SCS1,
3458212904Sdim                                   const StandardConversionSequence& SCS2)
3459193326Sed{
3460193326Sed  // Standard conversion sequence S1 is a better conversion sequence
3461193326Sed  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3462193326Sed
3463193326Sed  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3464193326Sed  //     sequences in the canonical form defined by 13.3.3.1.1,
3465193326Sed  //     excluding any Lvalue Transformation; the identity conversion
3466193326Sed  //     sequence is considered to be a subsequence of any
3467193326Sed  //     non-identity conversion sequence) or, if not that,
3468203955Srdivacky  if (ImplicitConversionSequence::CompareKind CK
3469212904Sdim        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3470203955Srdivacky    return CK;
3471193326Sed
3472193326Sed  //  -- the rank of S1 is better than the rank of S2 (by the rules
3473193326Sed  //     defined below), or, if not that,
3474193326Sed  ImplicitConversionRank Rank1 = SCS1.getRank();
3475193326Sed  ImplicitConversionRank Rank2 = SCS2.getRank();
3476193326Sed  if (Rank1 < Rank2)
3477193326Sed    return ImplicitConversionSequence::Better;
3478193326Sed  else if (Rank2 < Rank1)
3479193326Sed    return ImplicitConversionSequence::Worse;
3480193326Sed
3481193326Sed  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3482193326Sed  // are indistinguishable unless one of the following rules
3483193326Sed  // applies:
3484198092Srdivacky
3485193326Sed  //   A conversion that is not a conversion of a pointer, or
3486193326Sed  //   pointer to member, to bool is better than another conversion
3487193326Sed  //   that is such a conversion.
3488193326Sed  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3489193326Sed    return SCS2.isPointerConversionToBool()
3490193326Sed             ? ImplicitConversionSequence::Better
3491193326Sed             : ImplicitConversionSequence::Worse;
3492193326Sed
3493193326Sed  // C++ [over.ics.rank]p4b2:
3494193326Sed  //
3495193326Sed  //   If class B is derived directly or indirectly from class A,
3496193326Sed  //   conversion of B* to A* is better than conversion of B* to
3497193326Sed  //   void*, and conversion of A* to void* is better than conversion
3498193326Sed  //   of B* to void*.
3499198092Srdivacky  bool SCS1ConvertsToVoid
3500212904Sdim    = SCS1.isPointerConversionToVoidPointer(S.Context);
3501198092Srdivacky  bool SCS2ConvertsToVoid
3502212904Sdim    = SCS2.isPointerConversionToVoidPointer(S.Context);
3503193326Sed  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3504193326Sed    // Exactly one of the conversion sequences is a conversion to
3505193326Sed    // a void pointer; it's the worse conversion.
3506193326Sed    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3507193326Sed                              : ImplicitConversionSequence::Worse;
3508193326Sed  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3509193326Sed    // Neither conversion sequence converts to a void pointer; compare
3510193326Sed    // their derived-to-base conversions.
3511193326Sed    if (ImplicitConversionSequence::CompareKind DerivedCK
3512212904Sdim          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3513193326Sed      return DerivedCK;
3514221345Sdim  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3515221345Sdim             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3516193326Sed    // Both conversion sequences are conversions to void
3517193326Sed    // pointers. Compare the source types to determine if there's an
3518193326Sed    // inheritance relationship in their sources.
3519202379Srdivacky    QualType FromType1 = SCS1.getFromType();
3520202379Srdivacky    QualType FromType2 = SCS2.getFromType();
3521193326Sed
3522193326Sed    // Adjust the types we're converting from via the array-to-pointer
3523193326Sed    // conversion, if we need to.
3524193326Sed    if (SCS1.First == ICK_Array_To_Pointer)
3525212904Sdim      FromType1 = S.Context.getArrayDecayedType(FromType1);
3526193326Sed    if (SCS2.First == ICK_Array_To_Pointer)
3527212904Sdim      FromType2 = S.Context.getArrayDecayedType(FromType2);
3528193326Sed
3529221345Sdim    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3530221345Sdim    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3531193326Sed
3532212904Sdim    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3533193326Sed      return ImplicitConversionSequence::Better;
3534212904Sdim    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3535193326Sed      return ImplicitConversionSequence::Worse;
3536193326Sed
3537193326Sed    // Objective-C++: If one interface is more specific than the
3538193326Sed    // other, it is the better one.
3539221345Sdim    const ObjCObjectPointerType* FromObjCPtr1
3540221345Sdim      = FromType1->getAs<ObjCObjectPointerType>();
3541221345Sdim    const ObjCObjectPointerType* FromObjCPtr2
3542221345Sdim      = FromType2->getAs<ObjCObjectPointerType>();
3543221345Sdim    if (FromObjCPtr1 && FromObjCPtr2) {
3544221345Sdim      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3545221345Sdim                                                          FromObjCPtr2);
3546221345Sdim      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3547221345Sdim                                                           FromObjCPtr1);
3548221345Sdim      if (AssignLeft != AssignRight) {
3549221345Sdim        return AssignLeft? ImplicitConversionSequence::Better
3550221345Sdim                         : ImplicitConversionSequence::Worse;
3551221345Sdim      }
3552193326Sed    }
3553193326Sed  }
3554193326Sed
3555193326Sed  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3556193326Sed  // bullet 3).
3557198092Srdivacky  if (ImplicitConversionSequence::CompareKind QualCK
3558212904Sdim        = CompareQualificationConversions(S, SCS1, SCS2))
3559193326Sed    return QualCK;
3560193326Sed
3561193326Sed  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3562218893Sdim    // Check for a better reference binding based on the kind of bindings.
3563218893Sdim    if (isBetterReferenceBindingKind(SCS1, SCS2))
3564218893Sdim      return ImplicitConversionSequence::Better;
3565218893Sdim    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3566218893Sdim      return ImplicitConversionSequence::Worse;
3567193326Sed
3568193326Sed    // C++ [over.ics.rank]p3b4:
3569193326Sed    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3570193326Sed    //      which the references refer are the same type except for
3571193326Sed    //      top-level cv-qualifiers, and the type to which the reference
3572193326Sed    //      initialized by S2 refers is more cv-qualified than the type
3573193326Sed    //      to which the reference initialized by S1 refers.
3574203955Srdivacky    QualType T1 = SCS1.getToType(2);
3575203955Srdivacky    QualType T2 = SCS2.getToType(2);
3576212904Sdim    T1 = S.Context.getCanonicalType(T1);
3577212904Sdim    T2 = S.Context.getCanonicalType(T2);
3578201361Srdivacky    Qualifiers T1Quals, T2Quals;
3579212904Sdim    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3580212904Sdim    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3581201361Srdivacky    if (UnqualT1 == UnqualT2) {
3582224145Sdim      // Objective-C++ ARC: If the references refer to objects with different
3583224145Sdim      // lifetimes, prefer bindings that don't change lifetime.
3584224145Sdim      if (SCS1.ObjCLifetimeConversionBinding !=
3585224145Sdim                                          SCS2.ObjCLifetimeConversionBinding) {
3586224145Sdim        return SCS1.ObjCLifetimeConversionBinding
3587224145Sdim                                           ? ImplicitConversionSequence::Worse
3588224145Sdim                                           : ImplicitConversionSequence::Better;
3589224145Sdim      }
3590224145Sdim
3591218893Sdim      // If the type is an array type, promote the element qualifiers to the
3592218893Sdim      // type for comparison.
3593201361Srdivacky      if (isa<ArrayType>(T1) && T1Quals)
3594212904Sdim        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3595201361Srdivacky      if (isa<ArrayType>(T2) && T2Quals)
3596212904Sdim        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3597193326Sed      if (T2.isMoreQualifiedThan(T1))
3598193326Sed        return ImplicitConversionSequence::Better;
3599193326Sed      else if (T1.isMoreQualifiedThan(T2))
3600224145Sdim        return ImplicitConversionSequence::Worse;
3601193326Sed    }
3602193326Sed  }
3603193326Sed
3604226890Sdim  // In Microsoft mode, prefer an integral conversion to a
3605226890Sdim  // floating-to-integral conversion if the integral conversion
3606226890Sdim  // is between types of the same size.
3607226890Sdim  // For example:
3608226890Sdim  // void f(float);
3609226890Sdim  // void f(int);
3610226890Sdim  // int main {
3611226890Sdim  //    long a;
3612226890Sdim  //    f(a);
3613226890Sdim  // }
3614226890Sdim  // Here, MSVC will call f(int) instead of generating a compile error
3615226890Sdim  // as clang will do in standard mode.
3616235633Sdim  if (S.getLangOpts().MicrosoftMode &&
3617226890Sdim      SCS1.Second == ICK_Integral_Conversion &&
3618226890Sdim      SCS2.Second == ICK_Floating_Integral &&
3619226890Sdim      S.Context.getTypeSize(SCS1.getFromType()) ==
3620226890Sdim      S.Context.getTypeSize(SCS1.getToType(2)))
3621226890Sdim    return ImplicitConversionSequence::Better;
3622226890Sdim
3623193326Sed  return ImplicitConversionSequence::Indistinguishable;
3624193326Sed}
3625193326Sed
3626193326Sed/// CompareQualificationConversions - Compares two standard conversion
3627193326Sed/// sequences to determine whether they can be ranked based on their
3628198092Srdivacky/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3629198092SrdivackyImplicitConversionSequence::CompareKind
3630212904SdimCompareQualificationConversions(Sema &S,
3631212904Sdim                                const StandardConversionSequence& SCS1,
3632212904Sdim                                const StandardConversionSequence& SCS2) {
3633193326Sed  // C++ 13.3.3.2p3:
3634193326Sed  //  -- S1 and S2 differ only in their qualification conversion and
3635193326Sed  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3636193326Sed  //     cv-qualification signature of type T1 is a proper subset of
3637193326Sed  //     the cv-qualification signature of type T2, and S1 is not the
3638193326Sed  //     deprecated string literal array-to-pointer conversion (4.2).
3639193326Sed  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3640193326Sed      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3641193326Sed    return ImplicitConversionSequence::Indistinguishable;
3642193326Sed
3643193326Sed  // FIXME: the example in the standard doesn't use a qualification
3644193326Sed  // conversion (!)
3645203955Srdivacky  QualType T1 = SCS1.getToType(2);
3646203955Srdivacky  QualType T2 = SCS2.getToType(2);
3647212904Sdim  T1 = S.Context.getCanonicalType(T1);
3648212904Sdim  T2 = S.Context.getCanonicalType(T2);
3649201361Srdivacky  Qualifiers T1Quals, T2Quals;
3650212904Sdim  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3651212904Sdim  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3652193326Sed
3653193326Sed  // If the types are the same, we won't learn anything by unwrapped
3654193326Sed  // them.
3655201361Srdivacky  if (UnqualT1 == UnqualT2)
3656193326Sed    return ImplicitConversionSequence::Indistinguishable;
3657193326Sed
3658201361Srdivacky  // If the type is an array type, promote the element qualifiers to the type
3659201361Srdivacky  // for comparison.
3660201361Srdivacky  if (isa<ArrayType>(T1) && T1Quals)
3661212904Sdim    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3662201361Srdivacky  if (isa<ArrayType>(T2) && T2Quals)
3663212904Sdim    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3664201361Srdivacky
3665198092Srdivacky  ImplicitConversionSequence::CompareKind Result
3666193326Sed    = ImplicitConversionSequence::Indistinguishable;
3667224145Sdim
3668224145Sdim  // Objective-C++ ARC:
3669224145Sdim  //   Prefer qualification conversions not involving a change in lifetime
3670224145Sdim  //   to qualification conversions that do not change lifetime.
3671224145Sdim  if (SCS1.QualificationIncludesObjCLifetime !=
3672224145Sdim                                      SCS2.QualificationIncludesObjCLifetime) {
3673224145Sdim    Result = SCS1.QualificationIncludesObjCLifetime
3674224145Sdim               ? ImplicitConversionSequence::Worse
3675224145Sdim               : ImplicitConversionSequence::Better;
3676224145Sdim  }
3677224145Sdim
3678212904Sdim  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3679193326Sed    // Within each iteration of the loop, we check the qualifiers to
3680193326Sed    // determine if this still looks like a qualification
3681193326Sed    // conversion. Then, if all is well, we unwrap one more level of
3682193326Sed    // pointers or pointers-to-members and do it all again
3683193326Sed    // until there are no more pointers or pointers-to-members left
3684193326Sed    // to unwrap. This essentially mimics what
3685193326Sed    // IsQualificationConversion does, but here we're checking for a
3686193326Sed    // strict subset of qualifiers.
3687193326Sed    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3688193326Sed      // The qualifiers are the same, so this doesn't tell us anything
3689193326Sed      // about how the sequences rank.
3690193326Sed      ;
3691193326Sed    else if (T2.isMoreQualifiedThan(T1)) {
3692193326Sed      // T1 has fewer qualifiers, so it could be the better sequence.
3693193326Sed      if (Result == ImplicitConversionSequence::Worse)
3694193326Sed        // Neither has qualifiers that are a subset of the other's
3695193326Sed        // qualifiers.
3696193326Sed        return ImplicitConversionSequence::Indistinguishable;
3697198092Srdivacky
3698193326Sed      Result = ImplicitConversionSequence::Better;
3699193326Sed    } else if (T1.isMoreQualifiedThan(T2)) {
3700193326Sed      // T2 has fewer qualifiers, so it could be the better sequence.
3701193326Sed      if (Result == ImplicitConversionSequence::Better)
3702193326Sed        // Neither has qualifiers that are a subset of the other's
3703193326Sed        // qualifiers.
3704193326Sed        return ImplicitConversionSequence::Indistinguishable;
3705198092Srdivacky
3706193326Sed      Result = ImplicitConversionSequence::Worse;
3707193326Sed    } else {
3708193326Sed      // Qualifiers are disjoint.
3709193326Sed      return ImplicitConversionSequence::Indistinguishable;
3710193326Sed    }
3711193326Sed
3712193326Sed    // If the types after this point are equivalent, we're done.
3713212904Sdim    if (S.Context.hasSameUnqualifiedType(T1, T2))
3714193326Sed      break;
3715193326Sed  }
3716193326Sed
3717193326Sed  // Check that the winning standard conversion sequence isn't using
3718193326Sed  // the deprecated string literal array to pointer conversion.
3719193326Sed  switch (Result) {
3720193326Sed  case ImplicitConversionSequence::Better:
3721204643Srdivacky    if (SCS1.DeprecatedStringLiteralToCharPtr)
3722193326Sed      Result = ImplicitConversionSequence::Indistinguishable;
3723193326Sed    break;
3724193326Sed
3725193326Sed  case ImplicitConversionSequence::Indistinguishable:
3726193326Sed    break;
3727193326Sed
3728193326Sed  case ImplicitConversionSequence::Worse:
3729204643Srdivacky    if (SCS2.DeprecatedStringLiteralToCharPtr)
3730193326Sed      Result = ImplicitConversionSequence::Indistinguishable;
3731193326Sed    break;
3732193326Sed  }
3733193326Sed
3734193326Sed  return Result;
3735193326Sed}
3736193326Sed
3737193326Sed/// CompareDerivedToBaseConversions - Compares two standard conversion
3738193326Sed/// sequences to determine whether they can be ranked based on their
3739193326Sed/// various kinds of derived-to-base conversions (C++
3740193326Sed/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3741193326Sed/// conversions between Objective-C interface types.
3742193326SedImplicitConversionSequence::CompareKind
3743212904SdimCompareDerivedToBaseConversions(Sema &S,
3744212904Sdim                                const StandardConversionSequence& SCS1,
3745212904Sdim                                const StandardConversionSequence& SCS2) {
3746202379Srdivacky  QualType FromType1 = SCS1.getFromType();
3747203955Srdivacky  QualType ToType1 = SCS1.getToType(1);
3748202379Srdivacky  QualType FromType2 = SCS2.getFromType();
3749203955Srdivacky  QualType ToType2 = SCS2.getToType(1);
3750193326Sed
3751193326Sed  // Adjust the types we're converting from via the array-to-pointer
3752193326Sed  // conversion, if we need to.
3753193326Sed  if (SCS1.First == ICK_Array_To_Pointer)
3754212904Sdim    FromType1 = S.Context.getArrayDecayedType(FromType1);
3755193326Sed  if (SCS2.First == ICK_Array_To_Pointer)
3756212904Sdim    FromType2 = S.Context.getArrayDecayedType(FromType2);
3757193326Sed
3758193326Sed  // Canonicalize all of the types.
3759212904Sdim  FromType1 = S.Context.getCanonicalType(FromType1);
3760212904Sdim  ToType1 = S.Context.getCanonicalType(ToType1);
3761212904Sdim  FromType2 = S.Context.getCanonicalType(FromType2);
3762212904Sdim  ToType2 = S.Context.getCanonicalType(ToType2);
3763193326Sed
3764193326Sed  // C++ [over.ics.rank]p4b3:
3765193326Sed  //
3766193326Sed  //   If class B is derived directly or indirectly from class A and
3767193326Sed  //   class C is derived directly or indirectly from B,
3768193326Sed  //
3769193326Sed  // Compare based on pointer conversions.
3770198092Srdivacky  if (SCS1.Second == ICK_Pointer_Conversion &&
3771193326Sed      SCS2.Second == ICK_Pointer_Conversion &&
3772193326Sed      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3773193326Sed      FromType1->isPointerType() && FromType2->isPointerType() &&
3774193326Sed      ToType1->isPointerType() && ToType2->isPointerType()) {
3775198092Srdivacky    QualType FromPointee1
3776198092Srdivacky      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3777198092Srdivacky    QualType ToPointee1
3778198092Srdivacky      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3779193326Sed    QualType FromPointee2
3780198092Srdivacky      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3781193326Sed    QualType ToPointee2
3782198092Srdivacky      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3783193326Sed
3784193326Sed    //   -- conversion of C* to B* is better than conversion of C* to A*,
3785193326Sed    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3786212904Sdim      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3787193326Sed        return ImplicitConversionSequence::Better;
3788212904Sdim      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3789193326Sed        return ImplicitConversionSequence::Worse;
3790193326Sed    }
3791193326Sed
3792193326Sed    //   -- conversion of B* to A* is better than conversion of C* to A*,
3793193326Sed    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3794212904Sdim      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3795193326Sed        return ImplicitConversionSequence::Better;
3796212904Sdim      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3797193326Sed        return ImplicitConversionSequence::Worse;
3798218893Sdim    }
3799218893Sdim  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3800218893Sdim             SCS2.Second == ICK_Pointer_Conversion) {
3801218893Sdim    const ObjCObjectPointerType *FromPtr1
3802218893Sdim      = FromType1->getAs<ObjCObjectPointerType>();
3803218893Sdim    const ObjCObjectPointerType *FromPtr2
3804218893Sdim      = FromType2->getAs<ObjCObjectPointerType>();
3805218893Sdim    const ObjCObjectPointerType *ToPtr1
3806218893Sdim      = ToType1->getAs<ObjCObjectPointerType>();
3807218893Sdim    const ObjCObjectPointerType *ToPtr2
3808218893Sdim      = ToType2->getAs<ObjCObjectPointerType>();
3809218893Sdim
3810218893Sdim    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3811218893Sdim      // Apply the same conversion ranking rules for Objective-C pointer types
3812218893Sdim      // that we do for C++ pointers to class types. However, we employ the
3813218893Sdim      // Objective-C pseudo-subtyping relationship used for assignment of
3814218893Sdim      // Objective-C pointer types.
3815218893Sdim      bool FromAssignLeft
3816218893Sdim        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3817218893Sdim      bool FromAssignRight
3818218893Sdim        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3819218893Sdim      bool ToAssignLeft
3820218893Sdim        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3821218893Sdim      bool ToAssignRight
3822218893Sdim        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3823218893Sdim
3824218893Sdim      // A conversion to an a non-id object pointer type or qualified 'id'
3825218893Sdim      // type is better than a conversion to 'id'.
3826218893Sdim      if (ToPtr1->isObjCIdType() &&
3827218893Sdim          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3828218893Sdim        return ImplicitConversionSequence::Worse;
3829218893Sdim      if (ToPtr2->isObjCIdType() &&
3830218893Sdim          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3831218893Sdim        return ImplicitConversionSequence::Better;
3832218893Sdim
3833218893Sdim      // A conversion to a non-id object pointer type is better than a
3834218893Sdim      // conversion to a qualified 'id' type
3835218893Sdim      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3836218893Sdim        return ImplicitConversionSequence::Worse;
3837218893Sdim      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3838218893Sdim        return ImplicitConversionSequence::Better;
3839218893Sdim
3840218893Sdim      // A conversion to an a non-Class object pointer type or qualified 'Class'
3841218893Sdim      // type is better than a conversion to 'Class'.
3842218893Sdim      if (ToPtr1->isObjCClassType() &&
3843218893Sdim          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3844218893Sdim        return ImplicitConversionSequence::Worse;
3845218893Sdim      if (ToPtr2->isObjCClassType() &&
3846218893Sdim          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3847218893Sdim        return ImplicitConversionSequence::Better;
3848218893Sdim
3849218893Sdim      // A conversion to a non-Class object pointer type is better than a
3850218893Sdim      // conversion to a qualified 'Class' type.
3851218893Sdim      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3852218893Sdim        return ImplicitConversionSequence::Worse;
3853218893Sdim      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3854218893Sdim        return ImplicitConversionSequence::Better;
3855198092Srdivacky
3856218893Sdim      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3857218893Sdim      if (S.Context.hasSameType(FromType1, FromType2) &&
3858218893Sdim          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3859218893Sdim          (ToAssignLeft != ToAssignRight))
3860218893Sdim        return ToAssignLeft? ImplicitConversionSequence::Worse
3861218893Sdim                           : ImplicitConversionSequence::Better;
3862218893Sdim
3863218893Sdim      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3864218893Sdim      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3865218893Sdim          (FromAssignLeft != FromAssignRight))
3866218893Sdim        return FromAssignLeft? ImplicitConversionSequence::Better
3867218893Sdim        : ImplicitConversionSequence::Worse;
3868193326Sed    }
3869193326Sed  }
3870218893Sdim
3871198398Srdivacky  // Ranking of member-pointer types.
3872198398Srdivacky  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3873198398Srdivacky      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3874198398Srdivacky      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3875218893Sdim    const MemberPointerType * FromMemPointer1 =
3876198398Srdivacky                                        FromType1->getAs<MemberPointerType>();
3877218893Sdim    const MemberPointerType * ToMemPointer1 =
3878198398Srdivacky                                          ToType1->getAs<MemberPointerType>();
3879218893Sdim    const MemberPointerType * FromMemPointer2 =
3880198398Srdivacky                                          FromType2->getAs<MemberPointerType>();
3881218893Sdim    const MemberPointerType * ToMemPointer2 =
3882198398Srdivacky                                          ToType2->getAs<MemberPointerType>();
3883198398Srdivacky    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3884198398Srdivacky    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3885198398Srdivacky    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3886198398Srdivacky    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3887198398Srdivacky    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3888198398Srdivacky    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3889198398Srdivacky    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3890198398Srdivacky    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3891198398Srdivacky    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3892198398Srdivacky    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3893212904Sdim      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3894198398Srdivacky        return ImplicitConversionSequence::Worse;
3895212904Sdim      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3896198398Srdivacky        return ImplicitConversionSequence::Better;
3897198398Srdivacky    }
3898198398Srdivacky    // conversion of B::* to C::* is better than conversion of A::* to C::*
3899198398Srdivacky    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3900212904Sdim      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3901198398Srdivacky        return ImplicitConversionSequence::Better;
3902212904Sdim      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3903198398Srdivacky        return ImplicitConversionSequence::Worse;
3904198398Srdivacky    }
3905198398Srdivacky  }
3906218893Sdim
3907207619Srdivacky  if (SCS1.Second == ICK_Derived_To_Base) {
3908193326Sed    //   -- conversion of C to B is better than conversion of C to A,
3909204643Srdivacky    //   -- binding of an expression of type C to a reference of type
3910204643Srdivacky    //      B& is better than binding an expression of type C to a
3911204643Srdivacky    //      reference of type A&,
3912212904Sdim    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3913212904Sdim        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3914212904Sdim      if (S.IsDerivedFrom(ToType1, ToType2))
3915193326Sed        return ImplicitConversionSequence::Better;
3916212904Sdim      else if (S.IsDerivedFrom(ToType2, ToType1))
3917193326Sed        return ImplicitConversionSequence::Worse;
3918193326Sed    }
3919193326Sed
3920193326Sed    //   -- conversion of B to A is better than conversion of C to A.
3921204643Srdivacky    //   -- binding of an expression of type B to a reference of type
3922204643Srdivacky    //      A& is better than binding an expression of type C to a
3923204643Srdivacky    //      reference of type A&,
3924212904Sdim    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3925212904Sdim        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3926212904Sdim      if (S.IsDerivedFrom(FromType2, FromType1))
3927193326Sed        return ImplicitConversionSequence::Better;
3928212904Sdim      else if (S.IsDerivedFrom(FromType1, FromType2))
3929193326Sed        return ImplicitConversionSequence::Worse;
3930193326Sed    }
3931193326Sed  }
3932193326Sed
3933193326Sed  return ImplicitConversionSequence::Indistinguishable;
3934193326Sed}
3935193326Sed
3936252723Sdim/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3937252723Sdim/// C++ class.
3938252723Sdimstatic bool isTypeValid(QualType T) {
3939252723Sdim  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3940252723Sdim    return !Record->isInvalidDecl();
3941252723Sdim
3942252723Sdim  return true;
3943252723Sdim}
3944252723Sdim
3945207619Srdivacky/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3946207619Srdivacky/// determine whether they are reference-related,
3947207619Srdivacky/// reference-compatible, reference-compatible with added
3948207619Srdivacky/// qualification, or incompatible, for use in C++ initialization by
3949207619Srdivacky/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3950207619Srdivacky/// type, and the first type (T1) is the pointee type of the reference
3951207619Srdivacky/// type being initialized.
3952207619SrdivackySema::ReferenceCompareResult
3953207619SrdivackySema::CompareReferenceRelationship(SourceLocation Loc,
3954207619Srdivacky                                   QualType OrigT1, QualType OrigT2,
3955212904Sdim                                   bool &DerivedToBase,
3956224145Sdim                                   bool &ObjCConversion,
3957224145Sdim                                   bool &ObjCLifetimeConversion) {
3958207619Srdivacky  assert(!OrigT1->isReferenceType() &&
3959207619Srdivacky    "T1 must be the pointee type of the reference type");
3960207619Srdivacky  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3961207619Srdivacky
3962207619Srdivacky  QualType T1 = Context.getCanonicalType(OrigT1);
3963207619Srdivacky  QualType T2 = Context.getCanonicalType(OrigT2);
3964207619Srdivacky  Qualifiers T1Quals, T2Quals;
3965207619Srdivacky  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3966207619Srdivacky  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3967207619Srdivacky
3968207619Srdivacky  // C++ [dcl.init.ref]p4:
3969207619Srdivacky  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3970207619Srdivacky  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3971207619Srdivacky  //   T1 is a base class of T2.
3972212904Sdim  DerivedToBase = false;
3973212904Sdim  ObjCConversion = false;
3974224145Sdim  ObjCLifetimeConversion = false;
3975212904Sdim  if (UnqualT1 == UnqualT2) {
3976212904Sdim    // Nothing to do.
3977245431Sdim  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3978252723Sdim             isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3979252723Sdim             IsDerivedFrom(UnqualT2, UnqualT1))
3980207619Srdivacky    DerivedToBase = true;
3981212904Sdim  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3982212904Sdim           UnqualT2->isObjCObjectOrInterfaceType() &&
3983212904Sdim           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3984212904Sdim    ObjCConversion = true;
3985207619Srdivacky  else
3986207619Srdivacky    return Ref_Incompatible;
3987207619Srdivacky
3988207619Srdivacky  // At this point, we know that T1 and T2 are reference-related (at
3989207619Srdivacky  // least).
3990207619Srdivacky
3991207619Srdivacky  // If the type is an array type, promote the element qualifiers to the type
3992207619Srdivacky  // for comparison.
3993207619Srdivacky  if (isa<ArrayType>(T1) && T1Quals)
3994207619Srdivacky    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3995207619Srdivacky  if (isa<ArrayType>(T2) && T2Quals)
3996207619Srdivacky    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3997207619Srdivacky
3998207619Srdivacky  // C++ [dcl.init.ref]p4:
3999207619Srdivacky  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4000207619Srdivacky  //   reference-related to T2 and cv1 is the same cv-qualification
4001207619Srdivacky  //   as, or greater cv-qualification than, cv2. For purposes of
4002207619Srdivacky  //   overload resolution, cases for which cv1 is greater
4003207619Srdivacky  //   cv-qualification than cv2 are identified as
4004207619Srdivacky  //   reference-compatible with added qualification (see 13.3.3.2).
4005221345Sdim  //
4006221345Sdim  // Note that we also require equivalence of Objective-C GC and address-space
4007221345Sdim  // qualifiers when performing these computations, so that e.g., an int in
4008221345Sdim  // address space 1 is not reference-compatible with an int in address
4009221345Sdim  // space 2.
4010224145Sdim  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4011224145Sdim      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4012263509Sdim    if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4013263509Sdim      ObjCLifetimeConversion = true;
4014263509Sdim
4015224145Sdim    T1Quals.removeObjCLifetime();
4016224145Sdim    T2Quals.removeObjCLifetime();
4017224145Sdim  }
4018224145Sdim
4019221345Sdim  if (T1Quals == T2Quals)
4020207619Srdivacky    return Ref_Compatible;
4021224145Sdim  else if (T1Quals.compatiblyIncludes(T2Quals))
4022207619Srdivacky    return Ref_Compatible_With_Added_Qualification;
4023207619Srdivacky  else
4024207619Srdivacky    return Ref_Related;
4025207619Srdivacky}
4026207619Srdivacky
4027212904Sdim/// \brief Look for a user-defined conversion to an value reference-compatible
4028210299Sed///        with DeclType. Return true if something definite is found.
4029210299Sedstatic bool
4030212904SdimFindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4031212904Sdim                         QualType DeclType, SourceLocation DeclLoc,
4032212904Sdim                         Expr *Init, QualType T2, bool AllowRvalues,
4033212904Sdim                         bool AllowExplicit) {
4034210299Sed  assert(T2->isRecordType() && "Can only find conversions of record types.");
4035210299Sed  CXXRecordDecl *T2RecordDecl
4036210299Sed    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4037210299Sed
4038210299Sed  OverloadCandidateSet CandidateSet(DeclLoc);
4039252723Sdim  std::pair<CXXRecordDecl::conversion_iterator,
4040252723Sdim            CXXRecordDecl::conversion_iterator>
4041252723Sdim    Conversions = T2RecordDecl->getVisibleConversionFunctions();
4042252723Sdim  for (CXXRecordDecl::conversion_iterator
4043252723Sdim         I = Conversions.first, E = Conversions.second; I != E; ++I) {
4044210299Sed    NamedDecl *D = *I;
4045210299Sed    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4046210299Sed    if (isa<UsingShadowDecl>(D))
4047210299Sed      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4048210299Sed
4049210299Sed    FunctionTemplateDecl *ConvTemplate
4050210299Sed      = dyn_cast<FunctionTemplateDecl>(D);
4051210299Sed    CXXConversionDecl *Conv;
4052210299Sed    if (ConvTemplate)
4053210299Sed      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4054210299Sed    else
4055210299Sed      Conv = cast<CXXConversionDecl>(D);
4056210299Sed
4057218893Sdim    // If this is an explicit conversion, and we're not allowed to consider
4058212904Sdim    // explicit conversions, skip it.
4059212904Sdim    if (!AllowExplicit && Conv->isExplicit())
4060212904Sdim      continue;
4061218893Sdim
4062212904Sdim    if (AllowRvalues) {
4063212904Sdim      bool DerivedToBase = false;
4064212904Sdim      bool ObjCConversion = false;
4065224145Sdim      bool ObjCLifetimeConversion = false;
4066226890Sdim
4067226890Sdim      // If we are initializing an rvalue reference, don't permit conversion
4068226890Sdim      // functions that return lvalues.
4069226890Sdim      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4070226890Sdim        const ReferenceType *RefType
4071226890Sdim          = Conv->getConversionType()->getAs<LValueReferenceType>();
4072226890Sdim        if (RefType && !RefType->getPointeeType()->isFunctionType())
4073226890Sdim          continue;
4074226890Sdim      }
4075226890Sdim
4076212904Sdim      if (!ConvTemplate &&
4077218893Sdim          S.CompareReferenceRelationship(
4078218893Sdim            DeclLoc,
4079218893Sdim            Conv->getConversionType().getNonReferenceType()
4080218893Sdim              .getUnqualifiedType(),
4081218893Sdim            DeclType.getNonReferenceType().getUnqualifiedType(),
4082224145Sdim            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4083218893Sdim          Sema::Ref_Incompatible)
4084212904Sdim        continue;
4085212904Sdim    } else {
4086212904Sdim      // If the conversion function doesn't return a reference type,
4087212904Sdim      // it can't be considered for this conversion. An rvalue reference
4088212904Sdim      // is only acceptable if its referencee is a function type.
4089212904Sdim
4090212904Sdim      const ReferenceType *RefType =
4091212904Sdim        Conv->getConversionType()->getAs<ReferenceType>();
4092212904Sdim      if (!RefType ||
4093212904Sdim          (!RefType->isLValueReferenceType() &&
4094212904Sdim           !RefType->getPointeeType()->isFunctionType()))
4095212904Sdim        continue;
4096210299Sed    }
4097218893Sdim
4098212904Sdim    if (ConvTemplate)
4099212904Sdim      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4100263509Sdim                                       Init, DeclType, CandidateSet,
4101263509Sdim                                       /*AllowObjCConversionOnExplicit=*/false);
4102212904Sdim    else
4103212904Sdim      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4104263509Sdim                               DeclType, CandidateSet,
4105263509Sdim                               /*AllowObjCConversionOnExplicit=*/false);
4106210299Sed  }
4107210299Sed
4108226890Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4109226890Sdim
4110210299Sed  OverloadCandidateSet::iterator Best;
4111218893Sdim  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4112210299Sed  case OR_Success:
4113210299Sed    // C++ [over.ics.ref]p1:
4114210299Sed    //
4115210299Sed    //   [...] If the parameter binds directly to the result of
4116210299Sed    //   applying a conversion function to the argument
4117210299Sed    //   expression, the implicit conversion sequence is a
4118210299Sed    //   user-defined conversion sequence (13.3.3.1.2), with the
4119210299Sed    //   second standard conversion sequence either an identity
4120210299Sed    //   conversion or, if the conversion function returns an
4121210299Sed    //   entity of a type that is a derived class of the parameter
4122210299Sed    //   type, a derived-to-base Conversion.
4123210299Sed    if (!Best->FinalConversion.DirectBinding)
4124210299Sed      return false;
4125210299Sed
4126210299Sed    ICS.setUserDefined();
4127210299Sed    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4128210299Sed    ICS.UserDefined.After = Best->FinalConversion;
4129226890Sdim    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4130210299Sed    ICS.UserDefined.ConversionFunction = Best->Function;
4131226890Sdim    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4132210299Sed    ICS.UserDefined.EllipsisConversion = false;
4133210299Sed    assert(ICS.UserDefined.After.ReferenceBinding &&
4134210299Sed           ICS.UserDefined.After.DirectBinding &&
4135210299Sed           "Expected a direct reference binding!");
4136210299Sed    return true;
4137210299Sed
4138210299Sed  case OR_Ambiguous:
4139210299Sed    ICS.setAmbiguous();
4140210299Sed    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4141210299Sed         Cand != CandidateSet.end(); ++Cand)
4142210299Sed      if (Cand->Viable)
4143210299Sed        ICS.Ambiguous.addConversion(Cand->Function);
4144210299Sed    return true;
4145210299Sed
4146210299Sed  case OR_No_Viable_Function:
4147210299Sed  case OR_Deleted:
4148210299Sed    // There was no suitable conversion, or we found a deleted
4149210299Sed    // conversion; continue with other checks.
4150210299Sed    return false;
4151210299Sed  }
4152218893Sdim
4153235633Sdim  llvm_unreachable("Invalid OverloadResult!");
4154210299Sed}
4155210299Sed
4156207619Srdivacky/// \brief Compute an implicit conversion sequence for reference
4157207619Srdivacky/// initialization.
4158207619Srdivackystatic ImplicitConversionSequence
4159235633SdimTryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4160207619Srdivacky                 SourceLocation DeclLoc,
4161207619Srdivacky                 bool SuppressUserConversions,
4162207619Srdivacky                 bool AllowExplicit) {
4163207619Srdivacky  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4164207619Srdivacky
4165207619Srdivacky  // Most paths end in a failed conversion.
4166207619Srdivacky  ImplicitConversionSequence ICS;
4167207619Srdivacky  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4168207619Srdivacky
4169207619Srdivacky  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4170207619Srdivacky  QualType T2 = Init->getType();
4171207619Srdivacky
4172207619Srdivacky  // If the initializer is the address of an overloaded function, try
4173207619Srdivacky  // to resolve the overloaded function. If all goes well, T2 is the
4174207619Srdivacky  // type of the resulting function.
4175207619Srdivacky  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4176207619Srdivacky    DeclAccessPair Found;
4177207619Srdivacky    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4178207619Srdivacky                                                                false, Found))
4179207619Srdivacky      T2 = Fn->getType();
4180207619Srdivacky  }
4181207619Srdivacky
4182207619Srdivacky  // Compute some basic properties of the types and the initializer.
4183207619Srdivacky  bool isRValRef = DeclType->isRValueReferenceType();
4184207619Srdivacky  bool DerivedToBase = false;
4185212904Sdim  bool ObjCConversion = false;
4186224145Sdim  bool ObjCLifetimeConversion = false;
4187210299Sed  Expr::Classification InitCategory = Init->Classify(S.Context);
4188207619Srdivacky  Sema::ReferenceCompareResult RefRelationship
4189212904Sdim    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4190224145Sdim                                     ObjCConversion, ObjCLifetimeConversion);
4191207619Srdivacky
4192207619Srdivacky
4193210299Sed  // C++0x [dcl.init.ref]p5:
4194207619Srdivacky  //   A reference to type "cv1 T1" is initialized by an expression
4195207619Srdivacky  //   of type "cv2 T2" as follows:
4196207619Srdivacky
4197210299Sed  //     -- If reference is an lvalue reference and the initializer expression
4198218893Sdim  if (!isRValRef) {
4199210299Sed    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4200210299Sed    //        reference-compatible with "cv2 T2," or
4201210299Sed    //
4202210299Sed    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4203210299Sed    if (InitCategory.isLValue() &&
4204210299Sed        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4205207619Srdivacky      // C++ [over.ics.ref]p1:
4206210299Sed      //   When a parameter of reference type binds directly (8.5.3)
4207210299Sed      //   to an argument expression, the implicit conversion sequence
4208210299Sed      //   is the identity conversion, unless the argument expression
4209210299Sed      //   has a type that is a derived class of the parameter type,
4210210299Sed      //   in which case the implicit conversion sequence is a
4211210299Sed      //   derived-to-base Conversion (13.3.3.1).
4212210299Sed      ICS.setStandard();
4213210299Sed      ICS.Standard.First = ICK_Identity;
4214212904Sdim      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4215212904Sdim                         : ObjCConversion? ICK_Compatible_Conversion
4216212904Sdim                         : ICK_Identity;
4217210299Sed      ICS.Standard.Third = ICK_Identity;
4218210299Sed      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4219210299Sed      ICS.Standard.setToType(0, T2);
4220210299Sed      ICS.Standard.setToType(1, T1);
4221210299Sed      ICS.Standard.setToType(2, T1);
4222210299Sed      ICS.Standard.ReferenceBinding = true;
4223210299Sed      ICS.Standard.DirectBinding = true;
4224218893Sdim      ICS.Standard.IsLvalueReference = !isRValRef;
4225218893Sdim      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4226218893Sdim      ICS.Standard.BindsToRvalue = false;
4227218893Sdim      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4228224145Sdim      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4229210299Sed      ICS.Standard.CopyConstructor = 0;
4230207619Srdivacky
4231210299Sed      // Nothing more to do: the inaccessibility/ambiguity check for
4232210299Sed      // derived-to-base conversions is suppressed when we're
4233210299Sed      // computing the implicit conversion sequence (C++
4234210299Sed      // [over.best.ics]p2).
4235207619Srdivacky      return ICS;
4236210299Sed    }
4237207619Srdivacky
4238210299Sed    //       -- has a class type (i.e., T2 is a class type), where T1 is
4239210299Sed    //          not reference-related to T2, and can be implicitly
4240210299Sed    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4241210299Sed    //          is reference-compatible with "cv3 T3" 92) (this
4242210299Sed    //          conversion is selected by enumerating the applicable
4243210299Sed    //          conversion functions (13.3.1.6) and choosing the best
4244210299Sed    //          one through overload resolution (13.3)),
4245210299Sed    if (!SuppressUserConversions && T2->isRecordType() &&
4246218893Sdim        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4247210299Sed        RefRelationship == Sema::Ref_Incompatible) {
4248212904Sdim      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4249212904Sdim                                   Init, T2, /*AllowRvalues=*/false,
4250212904Sdim                                   AllowExplicit))
4251210299Sed        return ICS;
4252207619Srdivacky    }
4253207619Srdivacky  }
4254207619Srdivacky
4255210299Sed  //     -- Otherwise, the reference shall be an lvalue reference to a
4256210299Sed  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4257218893Sdim  //        shall be an rvalue reference.
4258218893Sdim  //
4259207619Srdivacky  // We actually handle one oddity of C++ [over.ics.ref] at this
4260207619Srdivacky  // point, which is that, due to p2 (which short-circuits reference
4261207619Srdivacky  // binding by only attempting a simple conversion for non-direct
4262207619Srdivacky  // bindings) and p3's strange wording, we allow a const volatile
4263207619Srdivacky  // reference to bind to an rvalue. Hence the check for the presence
4264207619Srdivacky  // of "const" rather than checking for "const" being the only
4265207619Srdivacky  // qualifier.
4266210299Sed  // This is also the point where rvalue references and lvalue inits no longer
4267210299Sed  // go together.
4268245431Sdim  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4269207619Srdivacky    return ICS;
4270207619Srdivacky
4271218893Sdim  //       -- If the initializer expression
4272218893Sdim  //
4273218893Sdim  //            -- is an xvalue, class prvalue, array prvalue or function
4274224145Sdim  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4275218893Sdim  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4276218893Sdim      (InitCategory.isXValue() ||
4277218893Sdim      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4278218893Sdim      (InitCategory.isLValue() && T2->isFunctionType()))) {
4279218893Sdim    ICS.setStandard();
4280218893Sdim    ICS.Standard.First = ICK_Identity;
4281218893Sdim    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4282218893Sdim                      : ObjCConversion? ICK_Compatible_Conversion
4283218893Sdim                      : ICK_Identity;
4284218893Sdim    ICS.Standard.Third = ICK_Identity;
4285218893Sdim    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4286218893Sdim    ICS.Standard.setToType(0, T2);
4287218893Sdim    ICS.Standard.setToType(1, T1);
4288218893Sdim    ICS.Standard.setToType(2, T1);
4289218893Sdim    ICS.Standard.ReferenceBinding = true;
4290218893Sdim    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4291218893Sdim    // binding unless we're binding to a class prvalue.
4292218893Sdim    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4293218893Sdim    // allow the use of rvalue references in C++98/03 for the benefit of
4294218893Sdim    // standard library implementors; therefore, we need the xvalue check here.
4295218893Sdim    ICS.Standard.DirectBinding =
4296252723Sdim      S.getLangOpts().CPlusPlus11 ||
4297218893Sdim      (InitCategory.isPRValue() && !T2->isRecordType());
4298218893Sdim    ICS.Standard.IsLvalueReference = !isRValRef;
4299218893Sdim    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4300218893Sdim    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4301218893Sdim    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4302224145Sdim    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4303218893Sdim    ICS.Standard.CopyConstructor = 0;
4304210299Sed    return ICS;
4305218893Sdim  }
4306210299Sed
4307218893Sdim  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4308218893Sdim  //               reference-related to T2, and can be implicitly converted to
4309218893Sdim  //               an xvalue, class prvalue, or function lvalue of type
4310218893Sdim  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4311218893Sdim  //               "cv3 T3",
4312207619Srdivacky  //
4313218893Sdim  //          then the reference is bound to the value of the initializer
4314218893Sdim  //          expression in the first case and to the result of the conversion
4315218893Sdim  //          in the second case (or, in either case, to an appropriate base
4316218893Sdim  //          class subobject).
4317218893Sdim  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4318218893Sdim      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4319218893Sdim      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320218893Sdim                               Init, T2, /*AllowRvalues=*/true,
4321218893Sdim                               AllowExplicit)) {
4322218893Sdim    // In the second case, if the reference is an rvalue reference
4323218893Sdim    // and the second standard conversion sequence of the
4324218893Sdim    // user-defined conversion sequence includes an lvalue-to-rvalue
4325218893Sdim    // conversion, the program is ill-formed.
4326218893Sdim    if (ICS.isUserDefined() && isRValRef &&
4327218893Sdim        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4328218893Sdim      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4329218893Sdim
4330218893Sdim    return ICS;
4331207619Srdivacky  }
4332218893Sdim
4333207619Srdivacky  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4334207619Srdivacky  //          initialized from the initializer expression using the
4335207619Srdivacky  //          rules for a non-reference copy initialization (8.5). The
4336207619Srdivacky  //          reference is then bound to the temporary. If T1 is
4337207619Srdivacky  //          reference-related to T2, cv1 must be the same
4338207619Srdivacky  //          cv-qualification as, or greater cv-qualification than,
4339207619Srdivacky  //          cv2; otherwise, the program is ill-formed.
4340207619Srdivacky  if (RefRelationship == Sema::Ref_Related) {
4341207619Srdivacky    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4342207619Srdivacky    // we would be reference-compatible or reference-compatible with
4343207619Srdivacky    // added qualification. But that wasn't the case, so the reference
4344207619Srdivacky    // initialization fails.
4345224145Sdim    //
4346224145Sdim    // Note that we only want to check address spaces and cvr-qualifiers here.
4347224145Sdim    // ObjC GC and lifetime qualifiers aren't important.
4348224145Sdim    Qualifiers T1Quals = T1.getQualifiers();
4349224145Sdim    Qualifiers T2Quals = T2.getQualifiers();
4350224145Sdim    T1Quals.removeObjCGCAttr();
4351224145Sdim    T1Quals.removeObjCLifetime();
4352224145Sdim    T2Quals.removeObjCGCAttr();
4353224145Sdim    T2Quals.removeObjCLifetime();
4354224145Sdim    if (!T1Quals.compatiblyIncludes(T2Quals))
4355224145Sdim      return ICS;
4356207619Srdivacky  }
4357207619Srdivacky
4358207619Srdivacky  // If at least one of the types is a class type, the types are not
4359207619Srdivacky  // related, and we aren't allowed any user conversions, the
4360207619Srdivacky  // reference binding fails. This case is important for breaking
4361207619Srdivacky  // recursion, since TryImplicitConversion below will attempt to
4362207619Srdivacky  // create a temporary through the use of a copy constructor.
4363207619Srdivacky  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4364207619Srdivacky      (T1->isRecordType() || T2->isRecordType()))
4365207619Srdivacky    return ICS;
4366207619Srdivacky
4367218893Sdim  // If T1 is reference-related to T2 and the reference is an rvalue
4368218893Sdim  // reference, the initializer expression shall not be an lvalue.
4369218893Sdim  if (RefRelationship >= Sema::Ref_Related &&
4370218893Sdim      isRValRef && Init->Classify(S.Context).isLValue())
4371218893Sdim    return ICS;
4372218893Sdim
4373207619Srdivacky  // C++ [over.ics.ref]p2:
4374207619Srdivacky  //   When a parameter of reference type is not bound directly to
4375207619Srdivacky  //   an argument expression, the conversion sequence is the one
4376207619Srdivacky  //   required to convert the argument expression to the
4377207619Srdivacky  //   underlying type of the reference according to
4378207619Srdivacky  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4379207619Srdivacky  //   to copy-initializing a temporary of the underlying type with
4380207619Srdivacky  //   the argument expression. Any difference in top-level
4381207619Srdivacky  //   cv-qualification is subsumed by the initialization itself
4382207619Srdivacky  //   and does not constitute a conversion.
4383212904Sdim  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4384212904Sdim                              /*AllowExplicit=*/false,
4385218893Sdim                              /*InOverloadResolution=*/false,
4386224145Sdim                              /*CStyle=*/false,
4387263509Sdim                              /*AllowObjCWritebackConversion=*/false,
4388263509Sdim                              /*AllowObjCConversionOnExplicit=*/false);
4389207619Srdivacky
4390207619Srdivacky  // Of course, that's still a reference binding.
4391207619Srdivacky  if (ICS.isStandard()) {
4392207619Srdivacky    ICS.Standard.ReferenceBinding = true;
4393218893Sdim    ICS.Standard.IsLvalueReference = !isRValRef;
4394218893Sdim    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4395218893Sdim    ICS.Standard.BindsToRvalue = true;
4396218893Sdim    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4397224145Sdim    ICS.Standard.ObjCLifetimeConversionBinding = false;
4398207619Srdivacky  } else if (ICS.isUserDefined()) {
4399226890Sdim    // Don't allow rvalue references to bind to lvalues.
4400226890Sdim    if (DeclType->isRValueReferenceType()) {
4401226890Sdim      if (const ReferenceType *RefType
4402226890Sdim            = ICS.UserDefined.ConversionFunction->getResultType()
4403226890Sdim                ->getAs<LValueReferenceType>()) {
4404226890Sdim        if (!RefType->getPointeeType()->isFunctionType()) {
4405226890Sdim          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4406226890Sdim                     DeclType);
4407226890Sdim          return ICS;
4408226890Sdim        }
4409226890Sdim      }
4410226890Sdim    }
4411226890Sdim
4412207619Srdivacky    ICS.UserDefined.After.ReferenceBinding = true;
4413226890Sdim    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4414226890Sdim    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4415226890Sdim    ICS.UserDefined.After.BindsToRvalue = true;
4416226890Sdim    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4417226890Sdim    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4418207619Srdivacky  }
4419218893Sdim
4420207619Srdivacky  return ICS;
4421207619Srdivacky}
4422207619Srdivacky
4423235633Sdimstatic ImplicitConversionSequence
4424235633SdimTryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4425235633Sdim                      bool SuppressUserConversions,
4426235633Sdim                      bool InOverloadResolution,
4427235633Sdim                      bool AllowObjCWritebackConversion,
4428235633Sdim                      bool AllowExplicit = false);
4429235633Sdim
4430235633Sdim/// TryListConversion - Try to copy-initialize a value of type ToType from the
4431235633Sdim/// initializer list From.
4432235633Sdimstatic ImplicitConversionSequence
4433235633SdimTryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4434235633Sdim                  bool SuppressUserConversions,
4435235633Sdim                  bool InOverloadResolution,
4436235633Sdim                  bool AllowObjCWritebackConversion) {
4437235633Sdim  // C++11 [over.ics.list]p1:
4438235633Sdim  //   When an argument is an initializer list, it is not an expression and
4439235633Sdim  //   special rules apply for converting it to a parameter type.
4440235633Sdim
4441235633Sdim  ImplicitConversionSequence Result;
4442235633Sdim  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4443235633Sdim
4444235633Sdim  // We need a complete type for what follows. Incomplete types can never be
4445235633Sdim  // initialized from init lists.
4446245431Sdim  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4447235633Sdim    return Result;
4448235633Sdim
4449235633Sdim  // C++11 [over.ics.list]p2:
4450235633Sdim  //   If the parameter type is std::initializer_list<X> or "array of X" and
4451235633Sdim  //   all the elements can be implicitly converted to X, the implicit
4452235633Sdim  //   conversion sequence is the worst conversion necessary to convert an
4453235633Sdim  //   element of the list to X.
4454235633Sdim  bool toStdInitializerList = false;
4455235633Sdim  QualType X;
4456235633Sdim  if (ToType->isArrayType())
4457252723Sdim    X = S.Context.getAsArrayType(ToType)->getElementType();
4458235633Sdim  else
4459235633Sdim    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4460235633Sdim  if (!X.isNull()) {
4461235633Sdim    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4462235633Sdim      Expr *Init = From->getInit(i);
4463235633Sdim      ImplicitConversionSequence ICS =
4464235633Sdim          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4465235633Sdim                                InOverloadResolution,
4466235633Sdim                                AllowObjCWritebackConversion);
4467235633Sdim      // If a single element isn't convertible, fail.
4468235633Sdim      if (ICS.isBad()) {
4469235633Sdim        Result = ICS;
4470235633Sdim        break;
4471235633Sdim      }
4472235633Sdim      // Otherwise, look for the worst conversion.
4473235633Sdim      if (Result.isBad() ||
4474235633Sdim          CompareImplicitConversionSequences(S, ICS, Result) ==
4475235633Sdim              ImplicitConversionSequence::Worse)
4476235633Sdim        Result = ICS;
4477235633Sdim    }
4478235633Sdim
4479235633Sdim    // For an empty list, we won't have computed any conversion sequence.
4480235633Sdim    // Introduce the identity conversion sequence.
4481235633Sdim    if (From->getNumInits() == 0) {
4482235633Sdim      Result.setStandard();
4483235633Sdim      Result.Standard.setAsIdentityConversion();
4484235633Sdim      Result.Standard.setFromType(ToType);
4485235633Sdim      Result.Standard.setAllToTypes(ToType);
4486235633Sdim    }
4487235633Sdim
4488235633Sdim    Result.setStdInitializerListElement(toStdInitializerList);
4489235633Sdim    return Result;
4490235633Sdim  }
4491235633Sdim
4492235633Sdim  // C++11 [over.ics.list]p3:
4493235633Sdim  //   Otherwise, if the parameter is a non-aggregate class X and overload
4494235633Sdim  //   resolution chooses a single best constructor [...] the implicit
4495235633Sdim  //   conversion sequence is a user-defined conversion sequence. If multiple
4496235633Sdim  //   constructors are viable but none is better than the others, the
4497235633Sdim  //   implicit conversion sequence is a user-defined conversion sequence.
4498235633Sdim  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4499235633Sdim    // This function can deal with initializer lists.
4500263509Sdim    return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4501263509Sdim                                    /*AllowExplicit=*/false,
4502263509Sdim                                    InOverloadResolution, /*CStyle=*/false,
4503263509Sdim                                    AllowObjCWritebackConversion,
4504263509Sdim                                    /*AllowObjCConversionOnExplicit=*/false);
4505235633Sdim  }
4506235633Sdim
4507235633Sdim  // C++11 [over.ics.list]p4:
4508235633Sdim  //   Otherwise, if the parameter has an aggregate type which can be
4509235633Sdim  //   initialized from the initializer list [...] the implicit conversion
4510235633Sdim  //   sequence is a user-defined conversion sequence.
4511235633Sdim  if (ToType->isAggregateType()) {
4512235633Sdim    // Type is an aggregate, argument is an init list. At this point it comes
4513235633Sdim    // down to checking whether the initialization works.
4514235633Sdim    // FIXME: Find out whether this parameter is consumed or not.
4515235633Sdim    InitializedEntity Entity =
4516235633Sdim        InitializedEntity::InitializeParameter(S.Context, ToType,
4517235633Sdim                                               /*Consumed=*/false);
4518235633Sdim    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4519235633Sdim      Result.setUserDefined();
4520235633Sdim      Result.UserDefined.Before.setAsIdentityConversion();
4521235633Sdim      // Initializer lists don't have a type.
4522235633Sdim      Result.UserDefined.Before.setFromType(QualType());
4523235633Sdim      Result.UserDefined.Before.setAllToTypes(QualType());
4524235633Sdim
4525235633Sdim      Result.UserDefined.After.setAsIdentityConversion();
4526235633Sdim      Result.UserDefined.After.setFromType(ToType);
4527235633Sdim      Result.UserDefined.After.setAllToTypes(ToType);
4528235633Sdim      Result.UserDefined.ConversionFunction = 0;
4529235633Sdim    }
4530235633Sdim    return Result;
4531235633Sdim  }
4532235633Sdim
4533235633Sdim  // C++11 [over.ics.list]p5:
4534235633Sdim  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4535235633Sdim  if (ToType->isReferenceType()) {
4536235633Sdim    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4537235633Sdim    // mention initializer lists in any way. So we go by what list-
4538235633Sdim    // initialization would do and try to extrapolate from that.
4539235633Sdim
4540235633Sdim    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4541235633Sdim
4542235633Sdim    // If the initializer list has a single element that is reference-related
4543235633Sdim    // to the parameter type, we initialize the reference from that.
4544235633Sdim    if (From->getNumInits() == 1) {
4545235633Sdim      Expr *Init = From->getInit(0);
4546235633Sdim
4547235633Sdim      QualType T2 = Init->getType();
4548235633Sdim
4549235633Sdim      // If the initializer is the address of an overloaded function, try
4550235633Sdim      // to resolve the overloaded function. If all goes well, T2 is the
4551235633Sdim      // type of the resulting function.
4552235633Sdim      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4553235633Sdim        DeclAccessPair Found;
4554235633Sdim        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4555235633Sdim                                   Init, ToType, false, Found))
4556235633Sdim          T2 = Fn->getType();
4557235633Sdim      }
4558235633Sdim
4559235633Sdim      // Compute some basic properties of the types and the initializer.
4560235633Sdim      bool dummy1 = false;
4561235633Sdim      bool dummy2 = false;
4562235633Sdim      bool dummy3 = false;
4563235633Sdim      Sema::ReferenceCompareResult RefRelationship
4564235633Sdim        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4565235633Sdim                                         dummy2, dummy3);
4566235633Sdim
4567263509Sdim      if (RefRelationship >= Sema::Ref_Related) {
4568263509Sdim        return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4569235633Sdim                                SuppressUserConversions,
4570235633Sdim                                /*AllowExplicit=*/false);
4571263509Sdim      }
4572235633Sdim    }
4573235633Sdim
4574235633Sdim    // Otherwise, we bind the reference to a temporary created from the
4575235633Sdim    // initializer list.
4576235633Sdim    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4577235633Sdim                               InOverloadResolution,
4578235633Sdim                               AllowObjCWritebackConversion);
4579235633Sdim    if (Result.isFailure())
4580235633Sdim      return Result;
4581235633Sdim    assert(!Result.isEllipsis() &&
4582235633Sdim           "Sub-initialization cannot result in ellipsis conversion.");
4583235633Sdim
4584235633Sdim    // Can we even bind to a temporary?
4585235633Sdim    if (ToType->isRValueReferenceType() ||
4586235633Sdim        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4587235633Sdim      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4588235633Sdim                                            Result.UserDefined.After;
4589235633Sdim      SCS.ReferenceBinding = true;
4590235633Sdim      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4591235633Sdim      SCS.BindsToRvalue = true;
4592235633Sdim      SCS.BindsToFunctionLvalue = false;
4593235633Sdim      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4594235633Sdim      SCS.ObjCLifetimeConversionBinding = false;
4595235633Sdim    } else
4596235633Sdim      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4597235633Sdim                    From, ToType);
4598235633Sdim    return Result;
4599235633Sdim  }
4600235633Sdim
4601235633Sdim  // C++11 [over.ics.list]p6:
4602235633Sdim  //   Otherwise, if the parameter type is not a class:
4603235633Sdim  if (!ToType->isRecordType()) {
4604235633Sdim    //    - if the initializer list has one element, the implicit conversion
4605235633Sdim    //      sequence is the one required to convert the element to the
4606235633Sdim    //      parameter type.
4607235633Sdim    unsigned NumInits = From->getNumInits();
4608235633Sdim    if (NumInits == 1)
4609235633Sdim      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4610235633Sdim                                     SuppressUserConversions,
4611235633Sdim                                     InOverloadResolution,
4612235633Sdim                                     AllowObjCWritebackConversion);
4613235633Sdim    //    - if the initializer list has no elements, the implicit conversion
4614235633Sdim    //      sequence is the identity conversion.
4615235633Sdim    else if (NumInits == 0) {
4616235633Sdim      Result.setStandard();
4617235633Sdim      Result.Standard.setAsIdentityConversion();
4618235633Sdim      Result.Standard.setFromType(ToType);
4619235633Sdim      Result.Standard.setAllToTypes(ToType);
4620235633Sdim    }
4621235633Sdim    return Result;
4622235633Sdim  }
4623235633Sdim
4624235633Sdim  // C++11 [over.ics.list]p7:
4625235633Sdim  //   In all cases other than those enumerated above, no conversion is possible
4626235633Sdim  return Result;
4627235633Sdim}
4628235633Sdim
4629193326Sed/// TryCopyInitialization - Try to copy-initialize a value of type
4630193326Sed/// ToType from the expression From. Return the implicit conversion
4631193326Sed/// sequence required to pass this argument, which may be a bad
4632193326Sed/// conversion sequence (meaning that the argument cannot be passed to
4633193326Sed/// a parameter of this type). If @p SuppressUserConversions, then we
4634207619Srdivacky/// do not permit any user-defined conversion sequences.
4635207619Srdivackystatic ImplicitConversionSequence
4636207619SrdivackyTryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4637218893Sdim                      bool SuppressUserConversions,
4638224145Sdim                      bool InOverloadResolution,
4639235633Sdim                      bool AllowObjCWritebackConversion,
4640235633Sdim                      bool AllowExplicit) {
4641235633Sdim  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4642235633Sdim    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4643235633Sdim                             InOverloadResolution,AllowObjCWritebackConversion);
4644235633Sdim
4645207619Srdivacky  if (ToType->isReferenceType())
4646207619Srdivacky    return TryReferenceInit(S, From, ToType,
4647207619Srdivacky                            /*FIXME:*/From->getLocStart(),
4648207619Srdivacky                            SuppressUserConversions,
4649235633Sdim                            AllowExplicit);
4650207619Srdivacky
4651212904Sdim  return TryImplicitConversion(S, From, ToType,
4652212904Sdim                               SuppressUserConversions,
4653212904Sdim                               /*AllowExplicit=*/false,
4654218893Sdim                               InOverloadResolution,
4655224145Sdim                               /*CStyle=*/false,
4656263509Sdim                               AllowObjCWritebackConversion,
4657263509Sdim                               /*AllowObjCConversionOnExplicit=*/false);
4658193326Sed}
4659193326Sed
4660226890Sdimstatic bool TryCopyInitialization(const CanQualType FromQTy,
4661226890Sdim                                  const CanQualType ToQTy,
4662226890Sdim                                  Sema &S,
4663226890Sdim                                  SourceLocation Loc,
4664226890Sdim                                  ExprValueKind FromVK) {
4665226890Sdim  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4666226890Sdim  ImplicitConversionSequence ICS =
4667226890Sdim    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4668226890Sdim
4669226890Sdim  return !ICS.isBad();
4670226890Sdim}
4671226890Sdim
4672193326Sed/// TryObjectArgumentInitialization - Try to initialize the object
4673193326Sed/// parameter of the given member function (@c Method) from the
4674193326Sed/// expression @p From.
4675212904Sdimstatic ImplicitConversionSequence
4676252723SdimTryObjectArgumentInitialization(Sema &S, QualType FromType,
4677218893Sdim                                Expr::Classification FromClassification,
4678212904Sdim                                CXXMethodDecl *Method,
4679212904Sdim                                CXXRecordDecl *ActingContext) {
4680212904Sdim  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4681199512Srdivacky  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4682199512Srdivacky  //                 const volatile object.
4683199512Srdivacky  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4684199512Srdivacky    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4685212904Sdim  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4686193326Sed
4687193326Sed  // Set up the conversion sequence as a "bad" conversion, to allow us
4688193326Sed  // to exit early.
4689193326Sed  ImplicitConversionSequence ICS;
4690193326Sed
4691193326Sed  // We need to have an object of class type.
4692218893Sdim  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4693193326Sed    FromType = PT->getPointeeType();
4694193326Sed
4695218893Sdim    // When we had a pointer, it's implicitly dereferenced, so we
4696218893Sdim    // better have an lvalue.
4697218893Sdim    assert(FromClassification.isLValue());
4698218893Sdim  }
4699218893Sdim
4700193326Sed  assert(FromType->isRecordType());
4701193326Sed
4702218893Sdim  // C++0x [over.match.funcs]p4:
4703218893Sdim  //   For non-static member functions, the type of the implicit object
4704218893Sdim  //   parameter is
4705218893Sdim  //
4706218893Sdim  //     - "lvalue reference to cv X" for functions declared without a
4707218893Sdim  //        ref-qualifier or with the & ref-qualifier
4708218893Sdim  //     - "rvalue reference to cv X" for functions declared with the &&
4709218893Sdim  //        ref-qualifier
4710218893Sdim  //
4711218893Sdim  // where X is the class of which the function is a member and cv is the
4712218893Sdim  // cv-qualification on the member function declaration.
4713218893Sdim  //
4714218893Sdim  // However, when finding an implicit conversion sequence for the argument, we
4715218893Sdim  // are not allowed to create temporaries or perform user-defined conversions
4716193326Sed  // (C++ [over.match.funcs]p5). We perform a simplified version of
4717193326Sed  // reference binding here, that allows class rvalues to bind to
4718193326Sed  // non-constant references.
4719193326Sed
4720218893Sdim  // First check the qualifiers.
4721212904Sdim  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4722218893Sdim  if (ImplicitParamType.getCVRQualifiers()
4723199482Srdivacky                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4724202379Srdivacky      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4725204643Srdivacky    ICS.setBad(BadConversionSequence::bad_qualifiers,
4726252723Sdim               FromType, ImplicitParamType);
4727193326Sed    return ICS;
4728202379Srdivacky  }
4729193326Sed
4730193326Sed  // Check that we have either the same type or a derived type. It
4731193326Sed  // affects the conversion rank.
4732212904Sdim  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4733204643Srdivacky  ImplicitConversionKind SecondKind;
4734204643Srdivacky  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4735204643Srdivacky    SecondKind = ICK_Identity;
4736212904Sdim  } else if (S.IsDerivedFrom(FromType, ClassType))
4737204643Srdivacky    SecondKind = ICK_Derived_To_Base;
4738202379Srdivacky  else {
4739204643Srdivacky    ICS.setBad(BadConversionSequence::unrelated_class,
4740204643Srdivacky               FromType, ImplicitParamType);
4741193326Sed    return ICS;
4742202379Srdivacky  }
4743193326Sed
4744218893Sdim  // Check the ref-qualifier.
4745218893Sdim  switch (Method->getRefQualifier()) {
4746218893Sdim  case RQ_None:
4747218893Sdim    // Do nothing; we don't care about lvalueness or rvalueness.
4748218893Sdim    break;
4749218893Sdim
4750218893Sdim  case RQ_LValue:
4751218893Sdim    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4752218893Sdim      // non-const lvalue reference cannot bind to an rvalue
4753218893Sdim      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4754218893Sdim                 ImplicitParamType);
4755218893Sdim      return ICS;
4756218893Sdim    }
4757218893Sdim    break;
4758218893Sdim
4759218893Sdim  case RQ_RValue:
4760218893Sdim    if (!FromClassification.isRValue()) {
4761218893Sdim      // rvalue reference cannot bind to an lvalue
4762218893Sdim      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4763218893Sdim                 ImplicitParamType);
4764218893Sdim      return ICS;
4765218893Sdim    }
4766218893Sdim    break;
4767218893Sdim  }
4768218893Sdim
4769193326Sed  // Success. Mark this as a reference binding.
4770202379Srdivacky  ICS.setStandard();
4771204643Srdivacky  ICS.Standard.setAsIdentityConversion();
4772204643Srdivacky  ICS.Standard.Second = SecondKind;
4773202379Srdivacky  ICS.Standard.setFromType(FromType);
4774203955Srdivacky  ICS.Standard.setAllToTypes(ImplicitParamType);
4775193326Sed  ICS.Standard.ReferenceBinding = true;
4776193326Sed  ICS.Standard.DirectBinding = true;
4777218893Sdim  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4778218893Sdim  ICS.Standard.BindsToFunctionLvalue = false;
4779218893Sdim  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4780218893Sdim  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4781218893Sdim    = (Method->getRefQualifier() == RQ_None);
4782193326Sed  return ICS;
4783193326Sed}
4784193326Sed
4785193326Sed/// PerformObjectArgumentInitialization - Perform initialization of
4786193326Sed/// the implicit object parameter for the given Method with the given
4787193326Sed/// expression.
4788221345SdimExprResult
4789221345SdimSema::PerformObjectArgumentInitialization(Expr *From,
4790218893Sdim                                          NestedNameSpecifier *Qualifier,
4791206084Srdivacky                                          NamedDecl *FoundDecl,
4792204793Srdivacky                                          CXXMethodDecl *Method) {
4793193326Sed  QualType FromRecordType, DestType;
4794198092Srdivacky  QualType ImplicitParamRecordType  =
4795198092Srdivacky    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4796198092Srdivacky
4797218893Sdim  Expr::Classification FromClassification;
4798198092Srdivacky  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4799193326Sed    FromRecordType = PT->getPointeeType();
4800193326Sed    DestType = Method->getThisType(Context);
4801218893Sdim    FromClassification = Expr::Classification::makeSimpleLValue();
4802193326Sed  } else {
4803193326Sed    FromRecordType = From->getType();
4804193326Sed    DestType = ImplicitParamRecordType;
4805218893Sdim    FromClassification = From->Classify(Context);
4806193326Sed  }
4807193326Sed
4808200583Srdivacky  // Note that we always use the true parent context when performing
4809200583Srdivacky  // the actual argument initialization.
4810198092Srdivacky  ImplicitConversionSequence ICS
4811218893Sdim    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4812218893Sdim                                      Method, Method->getParent());
4813218893Sdim  if (ICS.isBad()) {
4814218893Sdim    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4815218893Sdim      Qualifiers FromQs = FromRecordType.getQualifiers();
4816218893Sdim      Qualifiers ToQs = DestType.getQualifiers();
4817218893Sdim      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4818218893Sdim      if (CVR) {
4819235633Sdim        Diag(From->getLocStart(),
4820218893Sdim             diag::err_member_function_call_bad_cvr)
4821218893Sdim          << Method->getDeclName() << FromRecordType << (CVR - 1)
4822218893Sdim          << From->getSourceRange();
4823218893Sdim        Diag(Method->getLocation(), diag::note_previous_decl)
4824218893Sdim          << Method->getDeclName();
4825221345Sdim        return ExprError();
4826218893Sdim      }
4827218893Sdim    }
4828218893Sdim
4829235633Sdim    return Diag(From->getLocStart(),
4830193326Sed                diag::err_implicit_object_parameter_init)
4831193326Sed       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4832218893Sdim  }
4833198092Srdivacky
4834221345Sdim  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4835221345Sdim    ExprResult FromRes =
4836221345Sdim      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4837221345Sdim    if (FromRes.isInvalid())
4838221345Sdim      return ExprError();
4839221345Sdim    From = FromRes.take();
4840221345Sdim  }
4841193326Sed
4842204793Srdivacky  if (!Context.hasSameType(From->getType(), DestType))
4843221345Sdim    From = ImpCastExprToType(From, DestType, CK_NoOp,
4844235633Sdim                             From->getValueKind()).take();
4845221345Sdim  return Owned(From);
4846193326Sed}
4847193326Sed
4848193326Sed/// TryContextuallyConvertToBool - Attempt to contextually convert the
4849193326Sed/// expression From to bool (C++0x [conv]p3).
4850212904Sdimstatic ImplicitConversionSequence
4851212904SdimTryContextuallyConvertToBool(Sema &S, Expr *From) {
4852212904Sdim  return TryImplicitConversion(S, From, S.Context.BoolTy,
4853198092Srdivacky                               /*SuppressUserConversions=*/false,
4854198092Srdivacky                               /*AllowExplicit=*/true,
4855218893Sdim                               /*InOverloadResolution=*/false,
4856224145Sdim                               /*CStyle=*/false,
4857263509Sdim                               /*AllowObjCWritebackConversion=*/false,
4858263509Sdim                               /*AllowObjCConversionOnExplicit=*/false);
4859193326Sed}
4860193326Sed
4861193326Sed/// PerformContextuallyConvertToBool - Perform a contextual conversion
4862193326Sed/// of the expression From to bool (C++0x [conv]p3).
4863221345SdimExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4864235633Sdim  if (checkPlaceholderForOverload(*this, From))
4865235633Sdim    return ExprError();
4866235633Sdim
4867212904Sdim  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4868202379Srdivacky  if (!ICS.isBad())
4869202379Srdivacky    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4870218893Sdim
4871199512Srdivacky  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4872235633Sdim    return Diag(From->getLocStart(),
4873221345Sdim                diag::err_typecheck_bool_condition)
4874198092Srdivacky                  << From->getType() << From->getSourceRange();
4875221345Sdim  return ExprError();
4876193326Sed}
4877218893Sdim
4878235633Sdim/// Check that the specified conversion is permitted in a converted constant
4879235633Sdim/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4880235633Sdim/// is acceptable.
4881235633Sdimstatic bool CheckConvertedConstantConversions(Sema &S,
4882235633Sdim                                              StandardConversionSequence &SCS) {
4883235633Sdim  // Since we know that the target type is an integral or unscoped enumeration
4884235633Sdim  // type, most conversion kinds are impossible. All possible First and Third
4885235633Sdim  // conversions are fine.
4886235633Sdim  switch (SCS.Second) {
4887235633Sdim  case ICK_Identity:
4888235633Sdim  case ICK_Integral_Promotion:
4889235633Sdim  case ICK_Integral_Conversion:
4890252723Sdim  case ICK_Zero_Event_Conversion:
4891235633Sdim    return true;
4892235633Sdim
4893235633Sdim  case ICK_Boolean_Conversion:
4894235633Sdim    // Conversion from an integral or unscoped enumeration type to bool is
4895235633Sdim    // classified as ICK_Boolean_Conversion, but it's also an integral
4896235633Sdim    // conversion, so it's permitted in a converted constant expression.
4897235633Sdim    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4898235633Sdim           SCS.getToType(2)->isBooleanType();
4899235633Sdim
4900235633Sdim  case ICK_Floating_Integral:
4901235633Sdim  case ICK_Complex_Real:
4902235633Sdim    return false;
4903235633Sdim
4904235633Sdim  case ICK_Lvalue_To_Rvalue:
4905235633Sdim  case ICK_Array_To_Pointer:
4906235633Sdim  case ICK_Function_To_Pointer:
4907235633Sdim  case ICK_NoReturn_Adjustment:
4908235633Sdim  case ICK_Qualification:
4909235633Sdim  case ICK_Compatible_Conversion:
4910235633Sdim  case ICK_Vector_Conversion:
4911235633Sdim  case ICK_Vector_Splat:
4912235633Sdim  case ICK_Derived_To_Base:
4913235633Sdim  case ICK_Pointer_Conversion:
4914235633Sdim  case ICK_Pointer_Member:
4915235633Sdim  case ICK_Block_Pointer_Conversion:
4916235633Sdim  case ICK_Writeback_Conversion:
4917235633Sdim  case ICK_Floating_Promotion:
4918235633Sdim  case ICK_Complex_Promotion:
4919235633Sdim  case ICK_Complex_Conversion:
4920235633Sdim  case ICK_Floating_Conversion:
4921235633Sdim  case ICK_TransparentUnionConversion:
4922235633Sdim    llvm_unreachable("unexpected second conversion kind");
4923235633Sdim
4924235633Sdim  case ICK_Num_Conversion_Kinds:
4925235633Sdim    break;
4926235633Sdim  }
4927235633Sdim
4928235633Sdim  llvm_unreachable("unknown conversion kind");
4929235633Sdim}
4930235633Sdim
4931235633Sdim/// CheckConvertedConstantExpression - Check that the expression From is a
4932235633Sdim/// converted constant expression of type T, perform the conversion and produce
4933235633Sdim/// the converted expression, per C++11 [expr.const]p3.
4934235633SdimExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4935235633Sdim                                                  llvm::APSInt &Value,
4936235633Sdim                                                  CCEKind CCE) {
4937252723Sdim  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4938235633Sdim  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4939235633Sdim
4940235633Sdim  if (checkPlaceholderForOverload(*this, From))
4941235633Sdim    return ExprError();
4942235633Sdim
4943235633Sdim  // C++11 [expr.const]p3 with proposed wording fixes:
4944235633Sdim  //  A converted constant expression of type T is a core constant expression,
4945235633Sdim  //  implicitly converted to a prvalue of type T, where the converted
4946235633Sdim  //  expression is a literal constant expression and the implicit conversion
4947235633Sdim  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4948235633Sdim  //  conversions, integral promotions, and integral conversions other than
4949235633Sdim  //  narrowing conversions.
4950235633Sdim  ImplicitConversionSequence ICS =
4951235633Sdim    TryImplicitConversion(From, T,
4952235633Sdim                          /*SuppressUserConversions=*/false,
4953235633Sdim                          /*AllowExplicit=*/false,
4954235633Sdim                          /*InOverloadResolution=*/false,
4955235633Sdim                          /*CStyle=*/false,
4956235633Sdim                          /*AllowObjcWritebackConversion=*/false);
4957235633Sdim  StandardConversionSequence *SCS = 0;
4958235633Sdim  switch (ICS.getKind()) {
4959235633Sdim  case ImplicitConversionSequence::StandardConversion:
4960235633Sdim    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4961235633Sdim      return Diag(From->getLocStart(),
4962235633Sdim                  diag::err_typecheck_converted_constant_expression_disallowed)
4963235633Sdim               << From->getType() << From->getSourceRange() << T;
4964235633Sdim    SCS = &ICS.Standard;
4965235633Sdim    break;
4966235633Sdim  case ImplicitConversionSequence::UserDefinedConversion:
4967235633Sdim    // We are converting from class type to an integral or enumeration type, so
4968235633Sdim    // the Before sequence must be trivial.
4969235633Sdim    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4970235633Sdim      return Diag(From->getLocStart(),
4971235633Sdim                  diag::err_typecheck_converted_constant_expression_disallowed)
4972235633Sdim               << From->getType() << From->getSourceRange() << T;
4973235633Sdim    SCS = &ICS.UserDefined.After;
4974235633Sdim    break;
4975235633Sdim  case ImplicitConversionSequence::AmbiguousConversion:
4976235633Sdim  case ImplicitConversionSequence::BadConversion:
4977235633Sdim    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4978235633Sdim      return Diag(From->getLocStart(),
4979235633Sdim                  diag::err_typecheck_converted_constant_expression)
4980235633Sdim                    << From->getType() << From->getSourceRange() << T;
4981235633Sdim    return ExprError();
4982235633Sdim
4983235633Sdim  case ImplicitConversionSequence::EllipsisConversion:
4984235633Sdim    llvm_unreachable("ellipsis conversion in converted constant expression");
4985235633Sdim  }
4986235633Sdim
4987235633Sdim  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4988235633Sdim  if (Result.isInvalid())
4989235633Sdim    return Result;
4990235633Sdim
4991235633Sdim  // Check for a narrowing implicit conversion.
4992235633Sdim  APValue PreNarrowingValue;
4993235633Sdim  QualType PreNarrowingType;
4994235633Sdim  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4995235633Sdim                                PreNarrowingType)) {
4996235633Sdim  case NK_Variable_Narrowing:
4997235633Sdim    // Implicit conversion to a narrower type, and the value is not a constant
4998235633Sdim    // expression. We'll diagnose this in a moment.
4999235633Sdim  case NK_Not_Narrowing:
5000235633Sdim    break;
5001235633Sdim
5002235633Sdim  case NK_Constant_Narrowing:
5003263509Sdim    Diag(From->getLocStart(), diag::ext_cce_narrowing)
5004235633Sdim      << CCE << /*Constant*/1
5005235633Sdim      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5006235633Sdim    break;
5007235633Sdim
5008235633Sdim  case NK_Type_Narrowing:
5009263509Sdim    Diag(From->getLocStart(), diag::ext_cce_narrowing)
5010235633Sdim      << CCE << /*Constant*/0 << From->getType() << T;
5011235633Sdim    break;
5012235633Sdim  }
5013235633Sdim
5014235633Sdim  // Check the expression is a constant expression.
5015252723Sdim  SmallVector<PartialDiagnosticAt, 8> Notes;
5016235633Sdim  Expr::EvalResult Eval;
5017235633Sdim  Eval.Diag = &Notes;
5018235633Sdim
5019252723Sdim  if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5020235633Sdim    // The expression can't be folded, so we can't keep it at this position in
5021235633Sdim    // the AST.
5022235633Sdim    Result = ExprError();
5023235633Sdim  } else {
5024235633Sdim    Value = Eval.Val.getInt();
5025235633Sdim
5026235633Sdim    if (Notes.empty()) {
5027235633Sdim      // It's a constant expression.
5028235633Sdim      return Result;
5029235633Sdim    }
5030235633Sdim  }
5031235633Sdim
5032235633Sdim  // It's not a constant expression. Produce an appropriate diagnostic.
5033235633Sdim  if (Notes.size() == 1 &&
5034235633Sdim      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5035235633Sdim    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5036235633Sdim  else {
5037235633Sdim    Diag(From->getLocStart(), diag::err_expr_not_cce)
5038235633Sdim      << CCE << From->getSourceRange();
5039235633Sdim    for (unsigned I = 0; I < Notes.size(); ++I)
5040235633Sdim      Diag(Notes[I].first, Notes[I].second);
5041235633Sdim  }
5042235633Sdim  return Result;
5043235633Sdim}
5044235633Sdim
5045226890Sdim/// dropPointerConversions - If the given standard conversion sequence
5046226890Sdim/// involves any pointer conversions, remove them.  This may change
5047226890Sdim/// the result type of the conversion sequence.
5048226890Sdimstatic void dropPointerConversion(StandardConversionSequence &SCS) {
5049226890Sdim  if (SCS.Second == ICK_Pointer_Conversion) {
5050226890Sdim    SCS.Second = ICK_Identity;
5051226890Sdim    SCS.Third = ICK_Identity;
5052226890Sdim    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5053226890Sdim  }
5054226890Sdim}
5055226890Sdim
5056226890Sdim/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5057226890Sdim/// convert the expression From to an Objective-C pointer type.
5058212904Sdimstatic ImplicitConversionSequence
5059226890SdimTryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5060226890Sdim  // Do an implicit conversion to 'id'.
5061212904Sdim  QualType Ty = S.Context.getObjCIdType();
5062226890Sdim  ImplicitConversionSequence ICS
5063226890Sdim    = TryImplicitConversion(S, From, Ty,
5064226890Sdim                            // FIXME: Are these flags correct?
5065226890Sdim                            /*SuppressUserConversions=*/false,
5066226890Sdim                            /*AllowExplicit=*/true,
5067226890Sdim                            /*InOverloadResolution=*/false,
5068226890Sdim                            /*CStyle=*/false,
5069263509Sdim                            /*AllowObjCWritebackConversion=*/false,
5070263509Sdim                            /*AllowObjCConversionOnExplicit=*/true);
5071226890Sdim
5072226890Sdim  // Strip off any final conversions to 'id'.
5073226890Sdim  switch (ICS.getKind()) {
5074226890Sdim  case ImplicitConversionSequence::BadConversion:
5075226890Sdim  case ImplicitConversionSequence::AmbiguousConversion:
5076226890Sdim  case ImplicitConversionSequence::EllipsisConversion:
5077226890Sdim    break;
5078226890Sdim
5079226890Sdim  case ImplicitConversionSequence::UserDefinedConversion:
5080226890Sdim    dropPointerConversion(ICS.UserDefined.After);
5081226890Sdim    break;
5082226890Sdim
5083226890Sdim  case ImplicitConversionSequence::StandardConversion:
5084226890Sdim    dropPointerConversion(ICS.Standard);
5085226890Sdim    break;
5086226890Sdim  }
5087226890Sdim
5088226890Sdim  return ICS;
5089208600Srdivacky}
5090212904Sdim
5091226890Sdim/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5092226890Sdim/// conversion of the expression From to an Objective-C pointer type.
5093226890SdimExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5094235633Sdim  if (checkPlaceholderForOverload(*this, From))
5095235633Sdim    return ExprError();
5096235633Sdim
5097208600Srdivacky  QualType Ty = Context.getObjCIdType();
5098226890Sdim  ImplicitConversionSequence ICS =
5099226890Sdim    TryContextuallyConvertToObjCPointer(*this, From);
5100208600Srdivacky  if (!ICS.isBad())
5101208600Srdivacky    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5102221345Sdim  return ExprError();
5103208600Srdivacky}
5104193326Sed
5105235633Sdim/// Determine whether the provided type is an integral type, or an enumeration
5106235633Sdim/// type of a permitted flavor.
5107263509Sdimbool Sema::ICEConvertDiagnoser::match(QualType T) {
5108263509Sdim  return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5109263509Sdim                                 : T->isIntegralOrUnscopedEnumerationType();
5110235633Sdim}
5111235633Sdim
5112263509Sdimstatic ExprResult
5113263509SdimdiagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5114263509Sdim                            Sema::ContextualImplicitConverter &Converter,
5115263509Sdim                            QualType T, UnresolvedSetImpl &ViableConversions) {
5116263509Sdim
5117263509Sdim  if (Converter.Suppress)
5118263509Sdim    return ExprError();
5119263509Sdim
5120263509Sdim  Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5121263509Sdim  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5122263509Sdim    CXXConversionDecl *Conv =
5123263509Sdim        cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5124263509Sdim    QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5125263509Sdim    Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5126263509Sdim  }
5127263509Sdim  return SemaRef.Owned(From);
5128263509Sdim}
5129263509Sdim
5130263509Sdimstatic bool
5131263509SdimdiagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5132263509Sdim                           Sema::ContextualImplicitConverter &Converter,
5133263509Sdim                           QualType T, bool HadMultipleCandidates,
5134263509Sdim                           UnresolvedSetImpl &ExplicitConversions) {
5135263509Sdim  if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5136263509Sdim    DeclAccessPair Found = ExplicitConversions[0];
5137263509Sdim    CXXConversionDecl *Conversion =
5138263509Sdim        cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5139263509Sdim
5140263509Sdim    // The user probably meant to invoke the given explicit
5141263509Sdim    // conversion; use it.
5142263509Sdim    QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5143263509Sdim    std::string TypeStr;
5144263509Sdim    ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5145263509Sdim
5146263509Sdim    Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5147263509Sdim        << FixItHint::CreateInsertion(From->getLocStart(),
5148263509Sdim                                      "static_cast<" + TypeStr + ">(")
5149263509Sdim        << FixItHint::CreateInsertion(
5150263509Sdim               SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5151263509Sdim    Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5152263509Sdim
5153263509Sdim    // If we aren't in a SFINAE context, build a call to the
5154263509Sdim    // explicit conversion function.
5155263509Sdim    if (SemaRef.isSFINAEContext())
5156263509Sdim      return true;
5157263509Sdim
5158263509Sdim    SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5159263509Sdim    ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5160263509Sdim                                                       HadMultipleCandidates);
5161263509Sdim    if (Result.isInvalid())
5162263509Sdim      return true;
5163263509Sdim    // Record usage of conversion in an implicit cast.
5164263509Sdim    From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5165263509Sdim                                    CK_UserDefinedConversion, Result.get(), 0,
5166263509Sdim                                    Result.get()->getValueKind());
5167263509Sdim  }
5168263509Sdim  return false;
5169263509Sdim}
5170263509Sdim
5171263509Sdimstatic bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5172263509Sdim                             Sema::ContextualImplicitConverter &Converter,
5173263509Sdim                             QualType T, bool HadMultipleCandidates,
5174263509Sdim                             DeclAccessPair &Found) {
5175263509Sdim  CXXConversionDecl *Conversion =
5176263509Sdim      cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5177263509Sdim  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5178263509Sdim
5179263509Sdim  QualType ToType = Conversion->getConversionType().getNonReferenceType();
5180263509Sdim  if (!Converter.SuppressConversion) {
5181263509Sdim    if (SemaRef.isSFINAEContext())
5182263509Sdim      return true;
5183263509Sdim
5184263509Sdim    Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5185263509Sdim        << From->getSourceRange();
5186263509Sdim  }
5187263509Sdim
5188263509Sdim  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5189263509Sdim                                                     HadMultipleCandidates);
5190263509Sdim  if (Result.isInvalid())
5191263509Sdim    return true;
5192263509Sdim  // Record usage of conversion in an implicit cast.
5193263509Sdim  From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5194263509Sdim                                  CK_UserDefinedConversion, Result.get(), 0,
5195263509Sdim                                  Result.get()->getValueKind());
5196263509Sdim  return false;
5197263509Sdim}
5198263509Sdim
5199263509Sdimstatic ExprResult finishContextualImplicitConversion(
5200263509Sdim    Sema &SemaRef, SourceLocation Loc, Expr *From,
5201263509Sdim    Sema::ContextualImplicitConverter &Converter) {
5202263509Sdim  if (!Converter.match(From->getType()) && !Converter.Suppress)
5203263509Sdim    Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5204263509Sdim        << From->getSourceRange();
5205263509Sdim
5206263509Sdim  return SemaRef.DefaultLvalueConversion(From);
5207263509Sdim}
5208263509Sdim
5209263509Sdimstatic void
5210263509SdimcollectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5211263509Sdim                                  UnresolvedSetImpl &ViableConversions,
5212263509Sdim                                  OverloadCandidateSet &CandidateSet) {
5213263509Sdim  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5214263509Sdim    DeclAccessPair FoundDecl = ViableConversions[I];
5215263509Sdim    NamedDecl *D = FoundDecl.getDecl();
5216263509Sdim    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5217263509Sdim    if (isa<UsingShadowDecl>(D))
5218263509Sdim      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5219263509Sdim
5220263509Sdim    CXXConversionDecl *Conv;
5221263509Sdim    FunctionTemplateDecl *ConvTemplate;
5222263509Sdim    if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5223263509Sdim      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5224263509Sdim    else
5225263509Sdim      Conv = cast<CXXConversionDecl>(D);
5226263509Sdim
5227263509Sdim    if (ConvTemplate)
5228263509Sdim      SemaRef.AddTemplateConversionCandidate(
5229263509Sdim        ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5230263509Sdim        /*AllowObjCConversionOnExplicit=*/false);
5231263509Sdim    else
5232263509Sdim      SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5233263509Sdim                                     ToType, CandidateSet,
5234263509Sdim                                     /*AllowObjCConversionOnExplicit=*/false);
5235263509Sdim  }
5236263509Sdim}
5237263509Sdim
5238263509Sdim/// \brief Attempt to convert the given expression to a type which is accepted
5239263509Sdim/// by the given converter.
5240210299Sed///
5241263509Sdim/// This routine will attempt to convert an expression of class type to a
5242263509Sdim/// type accepted by the specified converter. In C++11 and before, the class
5243263509Sdim/// must have a single non-explicit conversion function converting to a matching
5244263509Sdim/// type. In C++1y, there can be multiple such conversion functions, but only
5245263509Sdim/// one target type.
5246210299Sed///
5247210299Sed/// \param Loc The source location of the construct that requires the
5248210299Sed/// conversion.
5249210299Sed///
5250245431Sdim/// \param From The expression we're converting from.
5251210299Sed///
5252263509Sdim/// \param Converter Used to control and diagnose the conversion process.
5253210299Sed///
5254210299Sed/// \returns The expression, converted to an integral or enumeration type if
5255210299Sed/// successful.
5256263509SdimExprResult Sema::PerformContextualImplicitConversion(
5257263509Sdim    SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5258210299Sed  // We can't perform any more checking for type-dependent expressions.
5259210299Sed  if (From->isTypeDependent())
5260212904Sdim    return Owned(From);
5261218893Sdim
5262235633Sdim  // Process placeholders immediately.
5263235633Sdim  if (From->hasPlaceholderType()) {
5264235633Sdim    ExprResult result = CheckPlaceholderExpr(From);
5265263509Sdim    if (result.isInvalid())
5266263509Sdim      return result;
5267235633Sdim    From = result.take();
5268235633Sdim  }
5269235633Sdim
5270263509Sdim  // If the expression already has a matching type, we're golden.
5271210299Sed  QualType T = From->getType();
5272263509Sdim  if (Converter.match(T))
5273235633Sdim    return DefaultLvalueConversion(From);
5274210299Sed
5275210299Sed  // FIXME: Check for missing '()' if T is a function type?
5276210299Sed
5277263509Sdim  // We can only perform contextual implicit conversions on objects of class
5278263509Sdim  // type.
5279210299Sed  const RecordType *RecordTy = T->getAs<RecordType>();
5280235633Sdim  if (!RecordTy || !getLangOpts().CPlusPlus) {
5281263509Sdim    if (!Converter.Suppress)
5282263509Sdim      Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5283212904Sdim    return Owned(From);
5284210299Sed  }
5285218893Sdim
5286210299Sed  // We must have a complete class type.
5287245431Sdim  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5288263509Sdim    ContextualImplicitConverter &Converter;
5289245431Sdim    Expr *From;
5290263509Sdim
5291263509Sdim    TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5292263509Sdim        : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5293263509Sdim
5294245431Sdim    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5295263509Sdim      Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5296245431Sdim    }
5297263509Sdim  } IncompleteDiagnoser(Converter, From);
5298245431Sdim
5299245431Sdim  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5300212904Sdim    return Owned(From);
5301218893Sdim
5302210299Sed  // Look for a conversion to an integral or enumeration type.
5303263509Sdim  UnresolvedSet<4>
5304263509Sdim      ViableConversions; // These are *potentially* viable in C++1y.
5305210299Sed  UnresolvedSet<4> ExplicitConversions;
5306252723Sdim  std::pair<CXXRecordDecl::conversion_iterator,
5307263509Sdim            CXXRecordDecl::conversion_iterator> Conversions =
5308263509Sdim      cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5309218893Sdim
5310263509Sdim  bool HadMultipleCandidates =
5311263509Sdim      (std::distance(Conversions.first, Conversions.second) > 1);
5312226890Sdim
5313263509Sdim  // To check that there is only one target type, in C++1y:
5314263509Sdim  QualType ToType;
5315263509Sdim  bool HasUniqueTargetType = true;
5316263509Sdim
5317263509Sdim  // Collect explicit or viable (potentially in C++1y) conversions.
5318263509Sdim  for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5319263509Sdim                                          E = Conversions.second;
5320263509Sdim       I != E; ++I) {
5321263509Sdim    NamedDecl *D = (*I)->getUnderlyingDecl();
5322263509Sdim    CXXConversionDecl *Conversion;
5323263509Sdim    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5324263509Sdim    if (ConvTemplate) {
5325263509Sdim      if (getLangOpts().CPlusPlus1y)
5326263509Sdim        Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5327263509Sdim      else
5328263509Sdim        continue; // C++11 does not consider conversion operator templates(?).
5329263509Sdim    } else
5330263509Sdim      Conversion = cast<CXXConversionDecl>(D);
5331263509Sdim
5332263509Sdim    assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5333263509Sdim           "Conversion operator templates are considered potentially "
5334263509Sdim           "viable in C++1y");
5335263509Sdim
5336263509Sdim    QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5337263509Sdim    if (Converter.match(CurToType) || ConvTemplate) {
5338263509Sdim
5339263509Sdim      if (Conversion->isExplicit()) {
5340263509Sdim        // FIXME: For C++1y, do we need this restriction?
5341263509Sdim        // cf. diagnoseNoViableConversion()
5342263509Sdim        if (!ConvTemplate)
5343210299Sed          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5344263509Sdim      } else {
5345263509Sdim        if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5346263509Sdim          if (ToType.isNull())
5347263509Sdim            ToType = CurToType.getUnqualifiedType();
5348263509Sdim          else if (HasUniqueTargetType &&
5349263509Sdim                   (CurToType.getUnqualifiedType() != ToType))
5350263509Sdim            HasUniqueTargetType = false;
5351263509Sdim        }
5352263509Sdim        ViableConversions.addDecl(I.getDecl(), I.getAccess());
5353210299Sed      }
5354235633Sdim    }
5355210299Sed  }
5356218893Sdim
5357263509Sdim  if (getLangOpts().CPlusPlus1y) {
5358263509Sdim    // C++1y [conv]p6:
5359263509Sdim    // ... An expression e of class type E appearing in such a context
5360263509Sdim    // is said to be contextually implicitly converted to a specified
5361263509Sdim    // type T and is well-formed if and only if e can be implicitly
5362263509Sdim    // converted to a type T that is determined as follows: E is searched
5363263509Sdim    // for conversion functions whose return type is cv T or reference to
5364263509Sdim    // cv T such that T is allowed by the context. There shall be
5365263509Sdim    // exactly one such T.
5366218893Sdim
5367263509Sdim    // If no unique T is found:
5368263509Sdim    if (ToType.isNull()) {
5369263509Sdim      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5370263509Sdim                                     HadMultipleCandidates,
5371263509Sdim                                     ExplicitConversions))
5372210299Sed        return ExprError();
5373263509Sdim      return finishContextualImplicitConversion(*this, Loc, From, Converter);
5374210299Sed    }
5375218893Sdim
5376263509Sdim    // If more than one unique Ts are found:
5377263509Sdim    if (!HasUniqueTargetType)
5378263509Sdim      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5379263509Sdim                                         ViableConversions);
5380218893Sdim
5381263509Sdim    // If one unique T is found:
5382263509Sdim    // First, build a candidate set from the previously recorded
5383263509Sdim    // potentially viable conversions.
5384263509Sdim    OverloadCandidateSet CandidateSet(Loc);
5385263509Sdim    collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5386263509Sdim                                      CandidateSet);
5387218893Sdim
5388263509Sdim    // Then, perform overload resolution over the candidate set.
5389263509Sdim    OverloadCandidateSet::iterator Best;
5390263509Sdim    switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5391263509Sdim    case OR_Success: {
5392263509Sdim      // Apply this conversion.
5393263509Sdim      DeclAccessPair Found =
5394263509Sdim          DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5395263509Sdim      if (recordConversion(*this, Loc, From, Converter, T,
5396263509Sdim                           HadMultipleCandidates, Found))
5397210299Sed        return ExprError();
5398263509Sdim      break;
5399210299Sed    }
5400263509Sdim    case OR_Ambiguous:
5401263509Sdim      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5402263509Sdim                                         ViableConversions);
5403263509Sdim    case OR_No_Viable_Function:
5404263509Sdim      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5405263509Sdim                                     HadMultipleCandidates,
5406263509Sdim                                     ExplicitConversions))
5407263509Sdim        return ExprError();
5408263509Sdim    // fall through 'OR_Deleted' case.
5409263509Sdim    case OR_Deleted:
5410263509Sdim      // We'll complain below about a non-integral condition type.
5411263509Sdim      break;
5412263509Sdim    }
5413263509Sdim  } else {
5414263509Sdim    switch (ViableConversions.size()) {
5415263509Sdim    case 0: {
5416263509Sdim      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5417263509Sdim                                     HadMultipleCandidates,
5418263509Sdim                                     ExplicitConversions))
5419263509Sdim        return ExprError();
5420218893Sdim
5421263509Sdim      // We'll complain below about a non-integral condition type.
5422263509Sdim      break;
5423210299Sed    }
5424263509Sdim    case 1: {
5425263509Sdim      // Apply this conversion.
5426263509Sdim      DeclAccessPair Found = ViableConversions[0];
5427263509Sdim      if (recordConversion(*this, Loc, From, Converter, T,
5428263509Sdim                           HadMultipleCandidates, Found))
5429263509Sdim        return ExprError();
5430263509Sdim      break;
5431263509Sdim    }
5432263509Sdim    default:
5433263509Sdim      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5434263509Sdim                                         ViableConversions);
5435263509Sdim    }
5436210299Sed  }
5437218893Sdim
5438263509Sdim  return finishContextualImplicitConversion(*this, Loc, From, Converter);
5439210299Sed}
5440210299Sed
5441193326Sed/// AddOverloadCandidate - Adds the given function to the set of
5442193326Sed/// candidate functions, using the given function call arguments.  If
5443193326Sed/// @p SuppressUserConversions, then don't allow user-defined
5444193326Sed/// conversions via constructors or conversion operators.
5445198092Srdivacky///
5446245431Sdim/// \param PartialOverloading true if we are performing "partial" overloading
5447198092Srdivacky/// based on an incomplete set of function arguments. This feature is used by
5448198092Srdivacky/// code completion.
5449198092Srdivackyvoid
5450198092SrdivackySema::AddOverloadCandidate(FunctionDecl *Function,
5451205408Srdivacky                           DeclAccessPair FoundDecl,
5452252723Sdim                           ArrayRef<Expr *> Args,
5453193326Sed                           OverloadCandidateSet& CandidateSet,
5454193326Sed                           bool SuppressUserConversions,
5455235633Sdim                           bool PartialOverloading,
5456235633Sdim                           bool AllowExplicit) {
5457198092Srdivacky  const FunctionProtoType* Proto
5458198092Srdivacky    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5459193326Sed  assert(Proto && "Functions without a prototype cannot be overloaded");
5460198092Srdivacky  assert(!Function->getDescribedFunctionTemplate() &&
5461195099Sed         "Use AddTemplateOverloadCandidate for function templates");
5462198092Srdivacky
5463193326Sed  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5464193326Sed    if (!isa<CXXConstructorDecl>(Method)) {
5465193326Sed      // If we get here, it's because we're calling a member function
5466193326Sed      // that is named without a member access expression (e.g.,
5467193326Sed      // "this->f") that was either written explicitly or created
5468193326Sed      // implicitly. This can happen with a qualified call to a member
5469200583Srdivacky      // function, e.g., X::f(). We use an empty type for the implied
5470200583Srdivacky      // object argument (C++ [over.call.func]p3), and the acting context
5471200583Srdivacky      // is irrelevant.
5472205408Srdivacky      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5473218893Sdim                         QualType(), Expr::Classification::makeSimpleLValue(),
5474235633Sdim                         Args, CandidateSet, SuppressUserConversions);
5475193326Sed      return;
5476193326Sed    }
5477193326Sed    // We treat a constructor like a non-member function, since its object
5478193326Sed    // argument doesn't participate in overload resolution.
5479193326Sed  }
5480193326Sed
5481198092Srdivacky  if (!CandidateSet.isNewCandidate(Function))
5482198092Srdivacky    return;
5483199482Srdivacky
5484263509Sdim  // C++11 [class.copy]p11: [DR1402]
5485263509Sdim  //   A defaulted move constructor that is defined as deleted is ignored by
5486263509Sdim  //   overload resolution.
5487263509Sdim  CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5488263509Sdim  if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5489263509Sdim      Constructor->isMoveConstructor())
5490263509Sdim    return;
5491263509Sdim
5492199990Srdivacky  // Overload resolution is always an unevaluated context.
5493212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5494199990Srdivacky
5495263509Sdim  if (Constructor) {
5496199482Srdivacky    // C++ [class.copy]p3:
5497199482Srdivacky    //   A member function template is never instantiated to perform the copy
5498199482Srdivacky    //   of a class object to an object of its class type.
5499199482Srdivacky    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5500235633Sdim    if (Args.size() == 1 &&
5501218893Sdim        Constructor->isSpecializationCopyingObject() &&
5502204643Srdivacky        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5503204643Srdivacky         IsDerivedFrom(Args[0]->getType(), ClassType)))
5504199482Srdivacky      return;
5505199482Srdivacky  }
5506218893Sdim
5507193326Sed  // Add this candidate
5508235633Sdim  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5509205408Srdivacky  Candidate.FoundDecl = FoundDecl;
5510193326Sed  Candidate.Function = Function;
5511193326Sed  Candidate.Viable = true;
5512193326Sed  Candidate.IsSurrogate = false;
5513193326Sed  Candidate.IgnoreObjectArgument = false;
5514235633Sdim  Candidate.ExplicitCallArguments = Args.size();
5515193326Sed
5516193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
5517193326Sed
5518193326Sed  // (C++ 13.3.2p2): A candidate function having fewer than m
5519193326Sed  // parameters is viable only if it has an ellipsis in its parameter
5520193326Sed  // list (8.3.5).
5521235633Sdim  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5522198092Srdivacky      !Proto->isVariadic()) {
5523193326Sed    Candidate.Viable = false;
5524202379Srdivacky    Candidate.FailureKind = ovl_fail_too_many_arguments;
5525193326Sed    return;
5526193326Sed  }
5527193326Sed
5528193326Sed  // (C++ 13.3.2p2): A candidate function having more than m parameters
5529193326Sed  // is viable only if the (m+1)st parameter has a default argument
5530193326Sed  // (8.3.6). For the purposes of overload resolution, the
5531193326Sed  // parameter list is truncated on the right, so that there are
5532193326Sed  // exactly m parameters.
5533193326Sed  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5534235633Sdim  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5535193326Sed    // Not enough arguments.
5536193326Sed    Candidate.Viable = false;
5537202379Srdivacky    Candidate.FailureKind = ovl_fail_too_few_arguments;
5538193326Sed    return;
5539193326Sed  }
5540193326Sed
5541226890Sdim  // (CUDA B.1): Check for invalid calls between targets.
5542235633Sdim  if (getLangOpts().CUDA)
5543226890Sdim    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5544226890Sdim      if (CheckCUDATarget(Caller, Function)) {
5545226890Sdim        Candidate.Viable = false;
5546226890Sdim        Candidate.FailureKind = ovl_fail_bad_target;
5547226890Sdim        return;
5548226890Sdim      }
5549226890Sdim
5550193326Sed  // Determine the implicit conversion sequences for each of the
5551193326Sed  // arguments.
5552235633Sdim  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5553193326Sed    if (ArgIdx < NumArgsInProto) {
5554193326Sed      // (C++ 13.3.2p3): for F to be a viable function, there shall
5555193326Sed      // exist for each argument an implicit conversion sequence
5556193326Sed      // (13.3.3.1) that converts that argument to the corresponding
5557193326Sed      // parameter of F.
5558193326Sed      QualType ParamType = Proto->getArgType(ArgIdx);
5559198092Srdivacky      Candidate.Conversions[ArgIdx]
5560207619Srdivacky        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5561218893Sdim                                SuppressUserConversions,
5562224145Sdim                                /*InOverloadResolution=*/true,
5563224145Sdim                                /*AllowObjCWritebackConversion=*/
5564235633Sdim                                  getLangOpts().ObjCAutoRefCount,
5565235633Sdim                                AllowExplicit);
5566202379Srdivacky      if (Candidate.Conversions[ArgIdx].isBad()) {
5567202379Srdivacky        Candidate.Viable = false;
5568202379Srdivacky        Candidate.FailureKind = ovl_fail_bad_conversion;
5569202379Srdivacky        break;
5570193326Sed      }
5571193326Sed    } else {
5572193326Sed      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5573193326Sed      // argument for which there is no corresponding parameter is
5574193326Sed      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5575202379Srdivacky      Candidate.Conversions[ArgIdx].setEllipsis();
5576193326Sed    }
5577193326Sed  }
5578193326Sed}
5579193326Sed
5580193326Sed/// \brief Add all of the function declarations in the given function set to
5581263509Sdim/// the overload candidate set.
5582203955Srdivackyvoid Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5583252723Sdim                                 ArrayRef<Expr *> Args,
5584193326Sed                                 OverloadCandidateSet& CandidateSet,
5585235633Sdim                                 bool SuppressUserConversions,
5586235633Sdim                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5587203955Srdivacky  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5588205408Srdivacky    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5589205408Srdivacky    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5590198092Srdivacky      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5591205408Srdivacky        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5592200583Srdivacky                           cast<CXXMethodDecl>(FD)->getParent(),
5593218893Sdim                           Args[0]->getType(), Args[0]->Classify(Context),
5594235633Sdim                           Args.slice(1), CandidateSet,
5595235633Sdim                           SuppressUserConversions);
5596198092Srdivacky      else
5597235633Sdim        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5598198092Srdivacky                             SuppressUserConversions);
5599198092Srdivacky    } else {
5600205408Srdivacky      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5601198092Srdivacky      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5602198092Srdivacky          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5603205408Srdivacky        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5604200583Srdivacky                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5605235633Sdim                                   ExplicitTemplateArgs,
5606218893Sdim                                   Args[0]->getType(),
5607235633Sdim                                   Args[0]->Classify(Context), Args.slice(1),
5608235633Sdim                                   CandidateSet, SuppressUserConversions);
5609198092Srdivacky      else
5610205408Srdivacky        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5611235633Sdim                                     ExplicitTemplateArgs, Args,
5612235633Sdim                                     CandidateSet, SuppressUserConversions);
5613198092Srdivacky    }
5614195341Sed  }
5615193326Sed}
5616193326Sed
5617199482Srdivacky/// AddMethodCandidate - Adds a named decl (which is some kind of
5618199482Srdivacky/// method) as a method candidate to the given overload set.
5619205408Srdivackyvoid Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5620200583Srdivacky                              QualType ObjectType,
5621218893Sdim                              Expr::Classification ObjectClassification,
5622252723Sdim                              ArrayRef<Expr *> Args,
5623199482Srdivacky                              OverloadCandidateSet& CandidateSet,
5624207619Srdivacky                              bool SuppressUserConversions) {
5625205408Srdivacky  NamedDecl *Decl = FoundDecl.getDecl();
5626200583Srdivacky  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5627199482Srdivacky
5628199482Srdivacky  if (isa<UsingShadowDecl>(Decl))
5629199482Srdivacky    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5630218893Sdim
5631199482Srdivacky  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5632199482Srdivacky    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5633199482Srdivacky           "Expected a member function template");
5634205408Srdivacky    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5635205408Srdivacky                               /*ExplicitArgs*/ 0,
5636235633Sdim                               ObjectType, ObjectClassification,
5637252723Sdim                               Args, CandidateSet,
5638207619Srdivacky                               SuppressUserConversions);
5639199482Srdivacky  } else {
5640205408Srdivacky    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5641235633Sdim                       ObjectType, ObjectClassification,
5642252723Sdim                       Args,
5643207619Srdivacky                       CandidateSet, SuppressUserConversions);
5644199482Srdivacky  }
5645199482Srdivacky}
5646199482Srdivacky
5647193326Sed/// AddMethodCandidate - Adds the given C++ member function to the set
5648193326Sed/// of candidate functions, using the given function call arguments
5649193326Sed/// and the object argument (@c Object). For example, in a call
5650193326Sed/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5651193326Sed/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5652193326Sed/// allow user-defined conversions via constructors or conversion
5653207619Srdivacky/// operators.
5654198092Srdivackyvoid
5655205408SrdivackySema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5656203955Srdivacky                         CXXRecordDecl *ActingContext, QualType ObjectType,
5657218893Sdim                         Expr::Classification ObjectClassification,
5658252723Sdim                         ArrayRef<Expr *> Args,
5659193326Sed                         OverloadCandidateSet& CandidateSet,
5660207619Srdivacky                         bool SuppressUserConversions) {
5661198092Srdivacky  const FunctionProtoType* Proto
5662198092Srdivacky    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5663193326Sed  assert(Proto && "Methods without a prototype cannot be overloaded");
5664193326Sed  assert(!isa<CXXConstructorDecl>(Method) &&
5665193326Sed         "Use AddOverloadCandidate for constructors");
5666193326Sed
5667198092Srdivacky  if (!CandidateSet.isNewCandidate(Method))
5668198092Srdivacky    return;
5669198092Srdivacky
5670263509Sdim  // C++11 [class.copy]p23: [DR1402]
5671263509Sdim  //   A defaulted move assignment operator that is defined as deleted is
5672263509Sdim  //   ignored by overload resolution.
5673263509Sdim  if (Method->isDefaulted() && Method->isDeleted() &&
5674263509Sdim      Method->isMoveAssignmentOperator())
5675263509Sdim    return;
5676263509Sdim
5677199990Srdivacky  // Overload resolution is always an unevaluated context.
5678212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5679199990Srdivacky
5680193326Sed  // Add this candidate
5681235633Sdim  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5682205408Srdivacky  Candidate.FoundDecl = FoundDecl;
5683193326Sed  Candidate.Function = Method;
5684193326Sed  Candidate.IsSurrogate = false;
5685193326Sed  Candidate.IgnoreObjectArgument = false;
5686235633Sdim  Candidate.ExplicitCallArguments = Args.size();
5687193326Sed
5688193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
5689193326Sed
5690193326Sed  // (C++ 13.3.2p2): A candidate function having fewer than m
5691193326Sed  // parameters is viable only if it has an ellipsis in its parameter
5692193326Sed  // list (8.3.5).
5693235633Sdim  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5694193326Sed    Candidate.Viable = false;
5695202379Srdivacky    Candidate.FailureKind = ovl_fail_too_many_arguments;
5696193326Sed    return;
5697193326Sed  }
5698193326Sed
5699193326Sed  // (C++ 13.3.2p2): A candidate function having more than m parameters
5700193326Sed  // is viable only if the (m+1)st parameter has a default argument
5701193326Sed  // (8.3.6). For the purposes of overload resolution, the
5702193326Sed  // parameter list is truncated on the right, so that there are
5703193326Sed  // exactly m parameters.
5704193326Sed  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5705235633Sdim  if (Args.size() < MinRequiredArgs) {
5706193326Sed    // Not enough arguments.
5707193326Sed    Candidate.Viable = false;
5708202379Srdivacky    Candidate.FailureKind = ovl_fail_too_few_arguments;
5709193326Sed    return;
5710193326Sed  }
5711193326Sed
5712193326Sed  Candidate.Viable = true;
5713193326Sed
5714200583Srdivacky  if (Method->isStatic() || ObjectType.isNull())
5715193326Sed    // The implicit object argument is ignored.
5716193326Sed    Candidate.IgnoreObjectArgument = true;
5717193326Sed  else {
5718193326Sed    // Determine the implicit conversion sequence for the object
5719193326Sed    // parameter.
5720200583Srdivacky    Candidate.Conversions[0]
5721218893Sdim      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5722218893Sdim                                        Method, ActingContext);
5723202379Srdivacky    if (Candidate.Conversions[0].isBad()) {
5724193326Sed      Candidate.Viable = false;
5725202379Srdivacky      Candidate.FailureKind = ovl_fail_bad_conversion;
5726193326Sed      return;
5727193326Sed    }
5728193326Sed  }
5729193326Sed
5730193326Sed  // Determine the implicit conversion sequences for each of the
5731193326Sed  // arguments.
5732235633Sdim  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5733193326Sed    if (ArgIdx < NumArgsInProto) {
5734193326Sed      // (C++ 13.3.2p3): for F to be a viable function, there shall
5735193326Sed      // exist for each argument an implicit conversion sequence
5736193326Sed      // (13.3.3.1) that converts that argument to the corresponding
5737193326Sed      // parameter of F.
5738193326Sed      QualType ParamType = Proto->getArgType(ArgIdx);
5739198092Srdivacky      Candidate.Conversions[ArgIdx + 1]
5740207619Srdivacky        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5741218893Sdim                                SuppressUserConversions,
5742224145Sdim                                /*InOverloadResolution=*/true,
5743224145Sdim                                /*AllowObjCWritebackConversion=*/
5744235633Sdim                                  getLangOpts().ObjCAutoRefCount);
5745202379Srdivacky      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5746193326Sed        Candidate.Viable = false;
5747202379Srdivacky        Candidate.FailureKind = ovl_fail_bad_conversion;
5748193326Sed        break;
5749193326Sed      }
5750193326Sed    } else {
5751193326Sed      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5752193326Sed      // argument for which there is no corresponding parameter is
5753193326Sed      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5754202379Srdivacky      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5755193326Sed    }
5756193326Sed  }
5757193326Sed}
5758218893Sdim
5759198092Srdivacky/// \brief Add a C++ member function template as a candidate to the candidate
5760198092Srdivacky/// set, using template argument deduction to produce an appropriate member
5761198092Srdivacky/// function template specialization.
5762198092Srdivackyvoid
5763198092SrdivackySema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5764205408Srdivacky                                 DeclAccessPair FoundDecl,
5765200583Srdivacky                                 CXXRecordDecl *ActingContext,
5766221345Sdim                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5767200583Srdivacky                                 QualType ObjectType,
5768218893Sdim                                 Expr::Classification ObjectClassification,
5769252723Sdim                                 ArrayRef<Expr *> Args,
5770198092Srdivacky                                 OverloadCandidateSet& CandidateSet,
5771207619Srdivacky                                 bool SuppressUserConversions) {
5772198092Srdivacky  if (!CandidateSet.isNewCandidate(MethodTmpl))
5773198092Srdivacky    return;
5774198092Srdivacky
5775198092Srdivacky  // C++ [over.match.funcs]p7:
5776198092Srdivacky  //   In each case where a candidate is a function template, candidate
5777198092Srdivacky  //   function template specializations are generated using template argument
5778198092Srdivacky  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5779198092Srdivacky  //   candidate functions in the usual way.113) A given name can refer to one
5780198092Srdivacky  //   or more function templates and also to a set of overloaded non-template
5781198092Srdivacky  //   functions. In such a case, the candidate functions generated from each
5782198092Srdivacky  //   function template are combined with the set of non-template candidate
5783198092Srdivacky  //   functions.
5784245431Sdim  TemplateDeductionInfo Info(CandidateSet.getLocation());
5785198092Srdivacky  FunctionDecl *Specialization = 0;
5786198092Srdivacky  if (TemplateDeductionResult Result
5787235633Sdim      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5788235633Sdim                                Specialization, Info)) {
5789235633Sdim    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5790208600Srdivacky    Candidate.FoundDecl = FoundDecl;
5791208600Srdivacky    Candidate.Function = MethodTmpl->getTemplatedDecl();
5792208600Srdivacky    Candidate.Viable = false;
5793208600Srdivacky    Candidate.FailureKind = ovl_fail_bad_deduction;
5794208600Srdivacky    Candidate.IsSurrogate = false;
5795208600Srdivacky    Candidate.IgnoreObjectArgument = false;
5796235633Sdim    Candidate.ExplicitCallArguments = Args.size();
5797218893Sdim    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5798208600Srdivacky                                                          Info);
5799208600Srdivacky    return;
5800208600Srdivacky  }
5801198092Srdivacky
5802198092Srdivacky  // Add the function template specialization produced by template argument
5803198092Srdivacky  // deduction as a candidate.
5804198092Srdivacky  assert(Specialization && "Missing member function template specialization?");
5805198092Srdivacky  assert(isa<CXXMethodDecl>(Specialization) &&
5806198092Srdivacky         "Specialization is not a member function?");
5807205408Srdivacky  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5808235633Sdim                     ActingContext, ObjectType, ObjectClassification, Args,
5809235633Sdim                     CandidateSet, SuppressUserConversions);
5810198092Srdivacky}
5811198092Srdivacky
5812198092Srdivacky/// \brief Add a C++ function template specialization as a candidate
5813198092Srdivacky/// in the candidate set, using template argument deduction to produce
5814198092Srdivacky/// an appropriate function template specialization.
5815198092Srdivackyvoid
5816195099SedSema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5817205408Srdivacky                                   DeclAccessPair FoundDecl,
5818221345Sdim                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5819252723Sdim                                   ArrayRef<Expr *> Args,
5820195099Sed                                   OverloadCandidateSet& CandidateSet,
5821207619Srdivacky                                   bool SuppressUserConversions) {
5822198092Srdivacky  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5823198092Srdivacky    return;
5824198092Srdivacky
5825195099Sed  // C++ [over.match.funcs]p7:
5826198092Srdivacky  //   In each case where a candidate is a function template, candidate
5827195099Sed  //   function template specializations are generated using template argument
5828198092Srdivacky  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5829195099Sed  //   candidate functions in the usual way.113) A given name can refer to one
5830195099Sed  //   or more function templates and also to a set of overloaded non-template
5831195099Sed  //   functions. In such a case, the candidate functions generated from each
5832195099Sed  //   function template are combined with the set of non-template candidate
5833195099Sed  //   functions.
5834245431Sdim  TemplateDeductionInfo Info(CandidateSet.getLocation());
5835195099Sed  FunctionDecl *Specialization = 0;
5836195099Sed  if (TemplateDeductionResult Result
5837235633Sdim        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5838235633Sdim                                  Specialization, Info)) {
5839235633Sdim    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5840205408Srdivacky    Candidate.FoundDecl = FoundDecl;
5841201361Srdivacky    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5842201361Srdivacky    Candidate.Viable = false;
5843202379Srdivacky    Candidate.FailureKind = ovl_fail_bad_deduction;
5844201361Srdivacky    Candidate.IsSurrogate = false;
5845201361Srdivacky    Candidate.IgnoreObjectArgument = false;
5846235633Sdim    Candidate.ExplicitCallArguments = Args.size();
5847218893Sdim    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5848208600Srdivacky                                                          Info);
5849195099Sed    return;
5850195099Sed  }
5851198092Srdivacky
5852195099Sed  // Add the function template specialization produced by template argument
5853195099Sed  // deduction as a candidate.
5854195099Sed  assert(Specialization && "Missing function template specialization?");
5855235633Sdim  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5856207619Srdivacky                       SuppressUserConversions);
5857195099Sed}
5858198092Srdivacky
5859263509Sdim/// Determine whether this is an allowable conversion from the result
5860263509Sdim/// of an explicit conversion operator to the expected type, per C++
5861263509Sdim/// [over.match.conv]p1 and [over.match.ref]p1.
5862263509Sdim///
5863263509Sdim/// \param ConvType The return type of the conversion function.
5864263509Sdim///
5865263509Sdim/// \param ToType The type we are converting to.
5866263509Sdim///
5867263509Sdim/// \param AllowObjCPointerConversion Allow a conversion from one
5868263509Sdim/// Objective-C pointer to another.
5869263509Sdim///
5870263509Sdim/// \returns true if the conversion is allowable, false otherwise.
5871263509Sdimstatic bool isAllowableExplicitConversion(Sema &S,
5872263509Sdim                                          QualType ConvType, QualType ToType,
5873263509Sdim                                          bool AllowObjCPointerConversion) {
5874263509Sdim  QualType ToNonRefType = ToType.getNonReferenceType();
5875263509Sdim
5876263509Sdim  // Easy case: the types are the same.
5877263509Sdim  if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
5878263509Sdim    return true;
5879263509Sdim
5880263509Sdim  // Allow qualification conversions.
5881263509Sdim  bool ObjCLifetimeConversion;
5882263509Sdim  if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
5883263509Sdim                                  ObjCLifetimeConversion))
5884263509Sdim    return true;
5885263509Sdim
5886263509Sdim  // If we're not allowed to consider Objective-C pointer conversions,
5887263509Sdim  // we're done.
5888263509Sdim  if (!AllowObjCPointerConversion)
5889263509Sdim    return false;
5890263509Sdim
5891263509Sdim  // Is this an Objective-C pointer conversion?
5892263509Sdim  bool IncompatibleObjC = false;
5893263509Sdim  QualType ConvertedType;
5894263509Sdim  return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
5895263509Sdim                                   IncompatibleObjC);
5896263509Sdim}
5897263509Sdim
5898193326Sed/// AddConversionCandidate - Add a C++ conversion function as a
5899198092Srdivacky/// candidate in the candidate set (C++ [over.match.conv],
5900193326Sed/// C++ [over.match.copy]). From is the expression we're converting from,
5901198092Srdivacky/// and ToType is the type that we're eventually trying to convert to
5902193326Sed/// (which may or may not be the same type as the type that the
5903193326Sed/// conversion function produces).
5904193326Sedvoid
5905193326SedSema::AddConversionCandidate(CXXConversionDecl *Conversion,
5906205408Srdivacky                             DeclAccessPair FoundDecl,
5907200583Srdivacky                             CXXRecordDecl *ActingContext,
5908193326Sed                             Expr *From, QualType ToType,
5909263509Sdim                             OverloadCandidateSet& CandidateSet,
5910263509Sdim                             bool AllowObjCConversionOnExplicit) {
5911198092Srdivacky  assert(!Conversion->getDescribedFunctionTemplate() &&
5912198092Srdivacky         "Conversion function templates use AddTemplateConversionCandidate");
5913207619Srdivacky  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5914198092Srdivacky  if (!CandidateSet.isNewCandidate(Conversion))
5915198092Srdivacky    return;
5916198092Srdivacky
5917252723Sdim  // If the conversion function has an undeduced return type, trigger its
5918252723Sdim  // deduction now.
5919252723Sdim  if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5920252723Sdim    if (DeduceReturnType(Conversion, From->getExprLoc()))
5921252723Sdim      return;
5922252723Sdim    ConvType = Conversion->getConversionType().getNonReferenceType();
5923252723Sdim  }
5924252723Sdim
5925263509Sdim  // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
5926263509Sdim  // operator is only a candidate if its return type is the target type or
5927263509Sdim  // can be converted to the target type with a qualification conversion.
5928263509Sdim  if (Conversion->isExplicit() &&
5929263509Sdim      !isAllowableExplicitConversion(*this, ConvType, ToType,
5930263509Sdim                                     AllowObjCConversionOnExplicit))
5931263509Sdim    return;
5932263509Sdim
5933199990Srdivacky  // Overload resolution is always an unevaluated context.
5934212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5935199990Srdivacky
5936193326Sed  // Add this candidate
5937235633Sdim  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5938205408Srdivacky  Candidate.FoundDecl = FoundDecl;
5939193326Sed  Candidate.Function = Conversion;
5940193326Sed  Candidate.IsSurrogate = false;
5941193326Sed  Candidate.IgnoreObjectArgument = false;
5942193326Sed  Candidate.FinalConversion.setAsIdentityConversion();
5943207619Srdivacky  Candidate.FinalConversion.setFromType(ConvType);
5944203955Srdivacky  Candidate.FinalConversion.setAllToTypes(ToType);
5945212904Sdim  Candidate.Viable = true;
5946218893Sdim  Candidate.ExplicitCallArguments = 1;
5947193326Sed
5948212904Sdim  // C++ [over.match.funcs]p4:
5949218893Sdim  //   For conversion functions, the function is considered to be a member of
5950218893Sdim  //   the class of the implicit implied object argument for the purpose of
5951212904Sdim  //   defining the type of the implicit object parameter.
5952212904Sdim  //
5953193326Sed  // Determine the implicit conversion sequence for the implicit
5954193326Sed  // object parameter.
5955212904Sdim  QualType ImplicitParamType = From->getType();
5956212904Sdim  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5957212904Sdim    ImplicitParamType = FromPtrType->getPointeeType();
5958212904Sdim  CXXRecordDecl *ConversionContext
5959212904Sdim    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5960218893Sdim
5961200583Srdivacky  Candidate.Conversions[0]
5962218893Sdim    = TryObjectArgumentInitialization(*this, From->getType(),
5963218893Sdim                                      From->Classify(Context),
5964218893Sdim                                      Conversion, ConversionContext);
5965218893Sdim
5966202379Srdivacky  if (Candidate.Conversions[0].isBad()) {
5967193326Sed    Candidate.Viable = false;
5968202379Srdivacky    Candidate.FailureKind = ovl_fail_bad_conversion;
5969193326Sed    return;
5970193326Sed  }
5971212904Sdim
5972218893Sdim  // We won't go through a user-define type conversion function to convert a
5973198398Srdivacky  // derived to base as such conversions are given Conversion Rank. They only
5974198398Srdivacky  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5975198398Srdivacky  QualType FromCanon
5976198398Srdivacky    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5977198398Srdivacky  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5978198398Srdivacky  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5979198398Srdivacky    Candidate.Viable = false;
5980202879Srdivacky    Candidate.FailureKind = ovl_fail_trivial_conversion;
5981198398Srdivacky    return;
5982198398Srdivacky  }
5983218893Sdim
5984193326Sed  // To determine what the conversion from the result of calling the
5985193326Sed  // conversion function to the type we're eventually trying to
5986193326Sed  // convert to (ToType), we need to synthesize a call to the
5987193326Sed  // conversion function and attempt copy initialization from it. This
5988193326Sed  // makes sure that we get the right semantics with respect to
5989193326Sed  // lvalues/rvalues and the type. Fortunately, we can allocate this
5990193326Sed  // call on the stack and we don't need its arguments to be
5991193326Sed  // well-formed.
5992235633Sdim  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5993218893Sdim                            VK_LValue, From->getLocStart());
5994212904Sdim  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5995212904Sdim                                Context.getPointerType(Conversion->getType()),
5996212904Sdim                                CK_FunctionToPointerDecay,
5997212904Sdim                                &ConversionRef, VK_RValue);
5998198092Srdivacky
5999224145Sdim  QualType ConversionType = Conversion->getConversionType();
6000224145Sdim  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6001218893Sdim    Candidate.Viable = false;
6002218893Sdim    Candidate.FailureKind = ovl_fail_bad_final_conversion;
6003218893Sdim    return;
6004218893Sdim  }
6005218893Sdim
6006224145Sdim  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6007218893Sdim
6008198092Srdivacky  // Note that it is safe to allocate CallExpr on the stack here because
6009193326Sed  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6010193326Sed  // allocator).
6011224145Sdim  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6012252723Sdim  CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6013199482Srdivacky                From->getLocStart());
6014198092Srdivacky  ImplicitConversionSequence ICS =
6015207619Srdivacky    TryCopyInitialization(*this, &Call, ToType,
6016198092Srdivacky                          /*SuppressUserConversions=*/true,
6017224145Sdim                          /*InOverloadResolution=*/false,
6018224145Sdim                          /*AllowObjCWritebackConversion=*/false);
6019198092Srdivacky
6020202379Srdivacky  switch (ICS.getKind()) {
6021193326Sed  case ImplicitConversionSequence::StandardConversion:
6022193326Sed    Candidate.FinalConversion = ICS.Standard;
6023218893Sdim
6024207619Srdivacky    // C++ [over.ics.user]p3:
6025207619Srdivacky    //   If the user-defined conversion is specified by a specialization of a
6026218893Sdim    //   conversion function template, the second standard conversion sequence
6027207619Srdivacky    //   shall have exact match rank.
6028207619Srdivacky    if (Conversion->getPrimaryTemplate() &&
6029207619Srdivacky        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6030207619Srdivacky      Candidate.Viable = false;
6031207619Srdivacky      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6032207619Srdivacky    }
6033218893Sdim
6034218893Sdim    // C++0x [dcl.init.ref]p5:
6035218893Sdim    //    In the second case, if the reference is an rvalue reference and
6036218893Sdim    //    the second standard conversion sequence of the user-defined
6037218893Sdim    //    conversion sequence includes an lvalue-to-rvalue conversion, the
6038218893Sdim    //    program is ill-formed.
6039218893Sdim    if (ToType->isRValueReferenceType() &&
6040218893Sdim        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6041218893Sdim      Candidate.Viable = false;
6042218893Sdim      Candidate.FailureKind = ovl_fail_bad_final_conversion;
6043218893Sdim    }
6044193326Sed    break;
6045193326Sed
6046193326Sed  case ImplicitConversionSequence::BadConversion:
6047193326Sed    Candidate.Viable = false;
6048202879Srdivacky    Candidate.FailureKind = ovl_fail_bad_final_conversion;
6049193326Sed    break;
6050193326Sed
6051193326Sed  default:
6052226890Sdim    llvm_unreachable(
6053193326Sed           "Can only end up with a standard conversion sequence or failure");
6054193326Sed  }
6055193326Sed}
6056193326Sed
6057198092Srdivacky/// \brief Adds a conversion function template specialization
6058198092Srdivacky/// candidate to the overload set, using template argument deduction
6059198092Srdivacky/// to deduce the template arguments of the conversion function
6060198092Srdivacky/// template from the type that we are converting to (C++
6061198092Srdivacky/// [temp.deduct.conv]).
6062198092Srdivackyvoid
6063198092SrdivackySema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6064205408Srdivacky                                     DeclAccessPair FoundDecl,
6065200583Srdivacky                                     CXXRecordDecl *ActingDC,
6066198092Srdivacky                                     Expr *From, QualType ToType,
6067263509Sdim                                     OverloadCandidateSet &CandidateSet,
6068263509Sdim                                     bool AllowObjCConversionOnExplicit) {
6069198092Srdivacky  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6070198092Srdivacky         "Only conversion function templates permitted here");
6071198092Srdivacky
6072198092Srdivacky  if (!CandidateSet.isNewCandidate(FunctionTemplate))
6073198092Srdivacky    return;
6074198092Srdivacky
6075245431Sdim  TemplateDeductionInfo Info(CandidateSet.getLocation());
6076198092Srdivacky  CXXConversionDecl *Specialization = 0;
6077198092Srdivacky  if (TemplateDeductionResult Result
6078198092Srdivacky        = DeduceTemplateArguments(FunctionTemplate, ToType,
6079198092Srdivacky                                  Specialization, Info)) {
6080235633Sdim    OverloadCandidate &Candidate = CandidateSet.addCandidate();
6081208600Srdivacky    Candidate.FoundDecl = FoundDecl;
6082208600Srdivacky    Candidate.Function = FunctionTemplate->getTemplatedDecl();
6083208600Srdivacky    Candidate.Viable = false;
6084208600Srdivacky    Candidate.FailureKind = ovl_fail_bad_deduction;
6085208600Srdivacky    Candidate.IsSurrogate = false;
6086208600Srdivacky    Candidate.IgnoreObjectArgument = false;
6087218893Sdim    Candidate.ExplicitCallArguments = 1;
6088218893Sdim    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6089208600Srdivacky                                                          Info);
6090198092Srdivacky    return;
6091198092Srdivacky  }
6092198092Srdivacky
6093198092Srdivacky  // Add the conversion function template specialization produced by
6094198092Srdivacky  // template argument deduction as a candidate.
6095198092Srdivacky  assert(Specialization && "Missing function template specialization?");
6096205408Srdivacky  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6097263509Sdim                         CandidateSet, AllowObjCConversionOnExplicit);
6098198092Srdivacky}
6099198092Srdivacky
6100193326Sed/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6101193326Sed/// converts the given @c Object to a function pointer via the
6102193326Sed/// conversion function @c Conversion, and then attempts to call it
6103193326Sed/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6104193326Sed/// the type of function that we'll eventually be calling.
6105193326Sedvoid Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6106205408Srdivacky                                 DeclAccessPair FoundDecl,
6107200583Srdivacky                                 CXXRecordDecl *ActingContext,
6108193326Sed                                 const FunctionProtoType *Proto,
6109218893Sdim                                 Expr *Object,
6110252723Sdim                                 ArrayRef<Expr *> Args,
6111193326Sed                                 OverloadCandidateSet& CandidateSet) {
6112198092Srdivacky  if (!CandidateSet.isNewCandidate(Conversion))
6113198092Srdivacky    return;
6114198092Srdivacky
6115199990Srdivacky  // Overload resolution is always an unevaluated context.
6116212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6117199990Srdivacky
6118235633Sdim  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6119205408Srdivacky  Candidate.FoundDecl = FoundDecl;
6120193326Sed  Candidate.Function = 0;
6121193326Sed  Candidate.Surrogate = Conversion;
6122193326Sed  Candidate.Viable = true;
6123193326Sed  Candidate.IsSurrogate = true;
6124193326Sed  Candidate.IgnoreObjectArgument = false;
6125235633Sdim  Candidate.ExplicitCallArguments = Args.size();
6126193326Sed
6127193326Sed  // Determine the implicit conversion sequence for the implicit
6128193326Sed  // object parameter.
6129198092Srdivacky  ImplicitConversionSequence ObjectInit
6130218893Sdim    = TryObjectArgumentInitialization(*this, Object->getType(),
6131218893Sdim                                      Object->Classify(Context),
6132218893Sdim                                      Conversion, ActingContext);
6133202379Srdivacky  if (ObjectInit.isBad()) {
6134193326Sed    Candidate.Viable = false;
6135202379Srdivacky    Candidate.FailureKind = ovl_fail_bad_conversion;
6136202879Srdivacky    Candidate.Conversions[0] = ObjectInit;
6137193326Sed    return;
6138193326Sed  }
6139193326Sed
6140193326Sed  // The first conversion is actually a user-defined conversion whose
6141193326Sed  // first conversion is ObjectInit's standard conversion (which is
6142193326Sed  // effectively a reference binding). Record it as such.
6143202379Srdivacky  Candidate.Conversions[0].setUserDefined();
6144193326Sed  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6145199482Srdivacky  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6146226890Sdim  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6147193326Sed  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6148226890Sdim  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6149198092Srdivacky  Candidate.Conversions[0].UserDefined.After
6150193326Sed    = Candidate.Conversions[0].UserDefined.Before;
6151193326Sed  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6152193326Sed
6153198092Srdivacky  // Find the
6154193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
6155193326Sed
6156193326Sed  // (C++ 13.3.2p2): A candidate function having fewer than m
6157193326Sed  // parameters is viable only if it has an ellipsis in its parameter
6158193326Sed  // list (8.3.5).
6159235633Sdim  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
6160193326Sed    Candidate.Viable = false;
6161202379Srdivacky    Candidate.FailureKind = ovl_fail_too_many_arguments;
6162193326Sed    return;
6163193326Sed  }
6164193326Sed
6165193326Sed  // Function types don't have any default arguments, so just check if
6166193326Sed  // we have enough arguments.
6167235633Sdim  if (Args.size() < NumArgsInProto) {
6168193326Sed    // Not enough arguments.
6169193326Sed    Candidate.Viable = false;
6170202379Srdivacky    Candidate.FailureKind = ovl_fail_too_few_arguments;
6171193326Sed    return;
6172193326Sed  }
6173193326Sed
6174193326Sed  // Determine the implicit conversion sequences for each of the
6175193326Sed  // arguments.
6176252723Sdim  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6177193326Sed    if (ArgIdx < NumArgsInProto) {
6178193326Sed      // (C++ 13.3.2p3): for F to be a viable function, there shall
6179193326Sed      // exist for each argument an implicit conversion sequence
6180193326Sed      // (13.3.3.1) that converts that argument to the corresponding
6181193326Sed      // parameter of F.
6182193326Sed      QualType ParamType = Proto->getArgType(ArgIdx);
6183198092Srdivacky      Candidate.Conversions[ArgIdx + 1]
6184207619Srdivacky        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6185198092Srdivacky                                /*SuppressUserConversions=*/false,
6186224145Sdim                                /*InOverloadResolution=*/false,
6187224145Sdim                                /*AllowObjCWritebackConversion=*/
6188235633Sdim                                  getLangOpts().ObjCAutoRefCount);
6189202379Srdivacky      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6190193326Sed        Candidate.Viable = false;
6191202379Srdivacky        Candidate.FailureKind = ovl_fail_bad_conversion;
6192193326Sed        break;
6193193326Sed      }
6194193326Sed    } else {
6195193326Sed      // (C++ 13.3.2p2): For the purposes of overload resolution, any
6196193326Sed      // argument for which there is no corresponding parameter is
6197193326Sed      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6198202379Srdivacky      Candidate.Conversions[ArgIdx + 1].setEllipsis();
6199193326Sed    }
6200193326Sed  }
6201193326Sed}
6202193326Sed
6203193326Sed/// \brief Add overload candidates for overloaded operators that are
6204193326Sed/// member functions.
6205193326Sed///
6206193326Sed/// Add the overloaded operator candidates that are member functions
6207193326Sed/// for the operator Op that was used in an operator expression such
6208193326Sed/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6209193326Sed/// CandidateSet will store the added overload candidates. (C++
6210193326Sed/// [over.match.oper]).
6211193326Sedvoid Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6212193326Sed                                       SourceLocation OpLoc,
6213252723Sdim                                       ArrayRef<Expr *> Args,
6214193326Sed                                       OverloadCandidateSet& CandidateSet,
6215193326Sed                                       SourceRange OpRange) {
6216193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6217193326Sed
6218193326Sed  // C++ [over.match.oper]p3:
6219193326Sed  //   For a unary operator @ with an operand of a type whose
6220193326Sed  //   cv-unqualified version is T1, and for a binary operator @ with
6221193326Sed  //   a left operand of a type whose cv-unqualified version is T1 and
6222193326Sed  //   a right operand of a type whose cv-unqualified version is T2,
6223193326Sed  //   three sets of candidate functions, designated member
6224193326Sed  //   candidates, non-member candidates and built-in candidates, are
6225193326Sed  //   constructed as follows:
6226193326Sed  QualType T1 = Args[0]->getType();
6227193326Sed
6228252723Sdim  //     -- If T1 is a complete class type or a class currently being
6229252723Sdim  //        defined, the set of member candidates is the result of the
6230252723Sdim  //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6231252723Sdim  //        the set of member candidates is empty.
6232198092Srdivacky  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6233252723Sdim    // Complete the type if it can be completed.
6234252723Sdim    RequireCompleteType(OpLoc, T1, 0);
6235252723Sdim    // If the type is neither complete nor being defined, bail out now.
6236252723Sdim    if (!T1Rec->getDecl()->getDefinition())
6237198092Srdivacky      return;
6238198092Srdivacky
6239199482Srdivacky    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6240199482Srdivacky    LookupQualifiedName(Operators, T1Rec->getDecl());
6241199482Srdivacky    Operators.suppressDiagnostics();
6242199482Srdivacky
6243198092Srdivacky    for (LookupResult::iterator Oper = Operators.begin(),
6244198092Srdivacky                             OperEnd = Operators.end();
6245198092Srdivacky         Oper != OperEnd;
6246199482Srdivacky         ++Oper)
6247205408Srdivacky      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6248252723Sdim                         Args[0]->Classify(Context),
6249252723Sdim                         Args.slice(1),
6250218893Sdim                         CandidateSet,
6251199482Srdivacky                         /* SuppressUserConversions = */ false);
6252193326Sed  }
6253193326Sed}
6254193326Sed
6255193326Sed/// AddBuiltinCandidate - Add a candidate for a built-in
6256193326Sed/// operator. ResultTy and ParamTys are the result and parameter types
6257193326Sed/// of the built-in candidate, respectively. Args and NumArgs are the
6258193326Sed/// arguments being passed to the candidate. IsAssignmentOperator
6259193326Sed/// should be true when this built-in candidate is an assignment
6260193326Sed/// operator. NumContextualBoolArguments is the number of arguments
6261193326Sed/// (at the beginning of the argument list) that will be contextually
6262193326Sed/// converted to bool.
6263198092Srdivackyvoid Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6264252723Sdim                               ArrayRef<Expr *> Args,
6265193326Sed                               OverloadCandidateSet& CandidateSet,
6266193326Sed                               bool IsAssignmentOperator,
6267193326Sed                               unsigned NumContextualBoolArguments) {
6268199990Srdivacky  // Overload resolution is always an unevaluated context.
6269212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6270199990Srdivacky
6271193326Sed  // Add this candidate
6272252723Sdim  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6273205408Srdivacky  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6274193326Sed  Candidate.Function = 0;
6275193326Sed  Candidate.IsSurrogate = false;
6276193326Sed  Candidate.IgnoreObjectArgument = false;
6277193326Sed  Candidate.BuiltinTypes.ResultTy = ResultTy;
6278252723Sdim  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6279193326Sed    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6280193326Sed
6281193326Sed  // Determine the implicit conversion sequences for each of the
6282193326Sed  // arguments.
6283193326Sed  Candidate.Viable = true;
6284252723Sdim  Candidate.ExplicitCallArguments = Args.size();
6285252723Sdim  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6286193326Sed    // C++ [over.match.oper]p4:
6287193326Sed    //   For the built-in assignment operators, conversions of the
6288193326Sed    //   left operand are restricted as follows:
6289193326Sed    //     -- no temporaries are introduced to hold the left operand, and
6290193326Sed    //     -- no user-defined conversions are applied to the left
6291193326Sed    //        operand to achieve a type match with the left-most
6292198092Srdivacky    //        parameter of a built-in candidate.
6293193326Sed    //
6294193326Sed    // We block these conversions by turning off user-defined
6295193326Sed    // conversions, since that is the only way that initialization of
6296193326Sed    // a reference to a non-class type can occur from something that
6297193326Sed    // is not of the same type.
6298193326Sed    if (ArgIdx < NumContextualBoolArguments) {
6299198092Srdivacky      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6300193326Sed             "Contextual conversion to bool requires bool type");
6301212904Sdim      Candidate.Conversions[ArgIdx]
6302212904Sdim        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6303193326Sed    } else {
6304198092Srdivacky      Candidate.Conversions[ArgIdx]
6305207619Srdivacky        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6306198092Srdivacky                                ArgIdx == 0 && IsAssignmentOperator,
6307224145Sdim                                /*InOverloadResolution=*/false,
6308224145Sdim                                /*AllowObjCWritebackConversion=*/
6309235633Sdim                                  getLangOpts().ObjCAutoRefCount);
6310193326Sed    }
6311202379Srdivacky    if (Candidate.Conversions[ArgIdx].isBad()) {
6312193326Sed      Candidate.Viable = false;
6313202379Srdivacky      Candidate.FailureKind = ovl_fail_bad_conversion;
6314193326Sed      break;
6315193326Sed    }
6316193326Sed  }
6317193326Sed}
6318193326Sed
6319263509Sdimnamespace {
6320263509Sdim
6321193326Sed/// BuiltinCandidateTypeSet - A set of types that will be used for the
6322193326Sed/// candidate operator functions for built-in operators (C++
6323193326Sed/// [over.built]). The types are separated into pointer types and
6324193326Sed/// enumeration types.
6325193326Sedclass BuiltinCandidateTypeSet  {
6326193326Sed  /// TypeSet - A set of types.
6327193326Sed  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6328193326Sed
6329193326Sed  /// PointerTypes - The set of pointer types that will be used in the
6330193326Sed  /// built-in candidates.
6331193326Sed  TypeSet PointerTypes;
6332193326Sed
6333193326Sed  /// MemberPointerTypes - The set of member pointer types that will be
6334193326Sed  /// used in the built-in candidates.
6335193326Sed  TypeSet MemberPointerTypes;
6336193326Sed
6337193326Sed  /// EnumerationTypes - The set of enumeration types that will be
6338193326Sed  /// used in the built-in candidates.
6339193326Sed  TypeSet EnumerationTypes;
6340193326Sed
6341218893Sdim  /// \brief The set of vector types that will be used in the built-in
6342208600Srdivacky  /// candidates.
6343208600Srdivacky  TypeSet VectorTypes;
6344218893Sdim
6345218893Sdim  /// \brief A flag indicating non-record types are viable candidates
6346218893Sdim  bool HasNonRecordTypes;
6347218893Sdim
6348218893Sdim  /// \brief A flag indicating whether either arithmetic or enumeration types
6349218893Sdim  /// were present in the candidate set.
6350218893Sdim  bool HasArithmeticOrEnumeralTypes;
6351218893Sdim
6352223017Sdim  /// \brief A flag indicating whether the nullptr type was present in the
6353223017Sdim  /// candidate set.
6354223017Sdim  bool HasNullPtrType;
6355223017Sdim
6356198092Srdivacky  /// Sema - The semantic analysis instance where we are building the
6357198092Srdivacky  /// candidate type set.
6358198092Srdivacky  Sema &SemaRef;
6359198092Srdivacky
6360193326Sed  /// Context - The AST context in which we will build the type sets.
6361193326Sed  ASTContext &Context;
6362193326Sed
6363198398Srdivacky  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6364198398Srdivacky                                               const Qualifiers &VisibleQuals);
6365193326Sed  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6366193326Sed
6367193326Sedpublic:
6368193326Sed  /// iterator - Iterates through the types that are part of the set.
6369193326Sed  typedef TypeSet::iterator iterator;
6370193326Sed
6371198092Srdivacky  BuiltinCandidateTypeSet(Sema &SemaRef)
6372218893Sdim    : HasNonRecordTypes(false),
6373218893Sdim      HasArithmeticOrEnumeralTypes(false),
6374223017Sdim      HasNullPtrType(false),
6375218893Sdim      SemaRef(SemaRef),
6376218893Sdim      Context(SemaRef.Context) { }
6377193326Sed
6378218893Sdim  void AddTypesConvertedFrom(QualType Ty,
6379198398Srdivacky                             SourceLocation Loc,
6380198398Srdivacky                             bool AllowUserConversions,
6381198398Srdivacky                             bool AllowExplicitConversions,
6382198398Srdivacky                             const Qualifiers &VisibleTypeConversionsQuals);
6383193326Sed
6384193326Sed  /// pointer_begin - First pointer type found;
6385193326Sed  iterator pointer_begin() { return PointerTypes.begin(); }
6386193326Sed
6387193326Sed  /// pointer_end - Past the last pointer type found;
6388193326Sed  iterator pointer_end() { return PointerTypes.end(); }
6389193326Sed
6390193326Sed  /// member_pointer_begin - First member pointer type found;
6391193326Sed  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6392193326Sed
6393193326Sed  /// member_pointer_end - Past the last member pointer type found;
6394193326Sed  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6395193326Sed
6396193326Sed  /// enumeration_begin - First enumeration type found;
6397193326Sed  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6398193326Sed
6399193326Sed  /// enumeration_end - Past the last enumeration type found;
6400193326Sed  iterator enumeration_end() { return EnumerationTypes.end(); }
6401218893Sdim
6402208600Srdivacky  iterator vector_begin() { return VectorTypes.begin(); }
6403208600Srdivacky  iterator vector_end() { return VectorTypes.end(); }
6404218893Sdim
6405218893Sdim  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6406218893Sdim  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6407223017Sdim  bool hasNullPtrType() const { return HasNullPtrType; }
6408193326Sed};
6409193326Sed
6410263509Sdim} // end anonymous namespace
6411263509Sdim
6412193326Sed/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6413193326Sed/// the set of pointer types along with any more-qualified variants of
6414193326Sed/// that type. For example, if @p Ty is "int const *", this routine
6415193326Sed/// will add "int const *", "int const volatile *", "int const
6416193326Sed/// restrict *", and "int const volatile restrict *" to the set of
6417193326Sed/// pointer types. Returns true if the add of @p Ty itself succeeded,
6418193326Sed/// false otherwise.
6419198092Srdivacky///
6420198092Srdivacky/// FIXME: what to do about extended qualifiers?
6421193326Sedbool
6422198398SrdivackyBuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6423198398Srdivacky                                             const Qualifiers &VisibleQuals) {
6424198092Srdivacky
6425193326Sed  // Insert this type.
6426193326Sed  if (!PointerTypes.insert(Ty))
6427193326Sed    return false;
6428218893Sdim
6429212904Sdim  QualType PointeeTy;
6430198092Srdivacky  const PointerType *PointerTy = Ty->getAs<PointerType>();
6431212904Sdim  bool buildObjCPtr = false;
6432212904Sdim  if (!PointerTy) {
6433245431Sdim    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6434245431Sdim    PointeeTy = PTy->getPointeeType();
6435245431Sdim    buildObjCPtr = true;
6436245431Sdim  } else {
6437245431Sdim    PointeeTy = PointerTy->getPointeeType();
6438212904Sdim  }
6439245431Sdim
6440199512Srdivacky  // Don't add qualified variants of arrays. For one, they're not allowed
6441199512Srdivacky  // (the qualifier would sink to the element type), and for another, the
6442199512Srdivacky  // only overload situation where it matters is subscript or pointer +- int,
6443199512Srdivacky  // and those shouldn't have qualifier variants anyway.
6444199512Srdivacky  if (PointeeTy->isArrayType())
6445199512Srdivacky    return true;
6446245431Sdim
6447198092Srdivacky  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6448198398Srdivacky  bool hasVolatile = VisibleQuals.hasVolatile();
6449198398Srdivacky  bool hasRestrict = VisibleQuals.hasRestrict();
6450218893Sdim
6451198092Srdivacky  // Iterate through all strict supersets of BaseCVR.
6452198092Srdivacky  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6453198092Srdivacky    if ((CVR | BaseCVR) != CVR) continue;
6454245431Sdim    // Skip over volatile if no volatile found anywhere in the types.
6455198398Srdivacky    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6456245431Sdim
6457245431Sdim    // Skip over restrict if no restrict found anywhere in the types, or if
6458245431Sdim    // the type cannot be restrict-qualified.
6459245431Sdim    if ((CVR & Qualifiers::Restrict) &&
6460245431Sdim        (!hasRestrict ||
6461245431Sdim         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6462245431Sdim      continue;
6463245431Sdim
6464245431Sdim    // Build qualified pointee type.
6465198092Srdivacky    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6466245431Sdim
6467245431Sdim    // Build qualified pointer type.
6468245431Sdim    QualType QPointerTy;
6469212904Sdim    if (!buildObjCPtr)
6470245431Sdim      QPointerTy = Context.getPointerType(QPointeeTy);
6471212904Sdim    else
6472245431Sdim      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6473245431Sdim
6474245431Sdim    // Insert qualified pointer type.
6475245431Sdim    PointerTypes.insert(QPointerTy);
6476193326Sed  }
6477193326Sed
6478193326Sed  return true;
6479193326Sed}
6480193326Sed
6481193326Sed/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6482193326Sed/// to the set of pointer types along with any more-qualified variants of
6483193326Sed/// that type. For example, if @p Ty is "int const *", this routine
6484193326Sed/// will add "int const *", "int const volatile *", "int const
6485193326Sed/// restrict *", and "int const volatile restrict *" to the set of
6486193326Sed/// pointer types. Returns true if the add of @p Ty itself succeeded,
6487193326Sed/// false otherwise.
6488198092Srdivacky///
6489198092Srdivacky/// FIXME: what to do about extended qualifiers?
6490193326Sedbool
6491193326SedBuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6492193326Sed    QualType Ty) {
6493193326Sed  // Insert this type.
6494193326Sed  if (!MemberPointerTypes.insert(Ty))
6495193326Sed    return false;
6496193326Sed
6497198092Srdivacky  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6498198092Srdivacky  assert(PointerTy && "type was not a member pointer type!");
6499193326Sed
6500198092Srdivacky  QualType PointeeTy = PointerTy->getPointeeType();
6501199512Srdivacky  // Don't add qualified variants of arrays. For one, they're not allowed
6502199512Srdivacky  // (the qualifier would sink to the element type), and for another, the
6503199512Srdivacky  // only overload situation where it matters is subscript or pointer +- int,
6504199512Srdivacky  // and those shouldn't have qualifier variants anyway.
6505199512Srdivacky  if (PointeeTy->isArrayType())
6506199512Srdivacky    return true;
6507198092Srdivacky  const Type *ClassTy = PointerTy->getClass();
6508198092Srdivacky
6509198092Srdivacky  // Iterate through all strict supersets of the pointee type's CVR
6510198092Srdivacky  // qualifiers.
6511198092Srdivacky  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6512198092Srdivacky  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6513198092Srdivacky    if ((CVR | BaseCVR) != CVR) continue;
6514218893Sdim
6515198092Srdivacky    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6516218893Sdim    MemberPointerTypes.insert(
6517218893Sdim      Context.getMemberPointerType(QPointeeTy, ClassTy));
6518193326Sed  }
6519193326Sed
6520193326Sed  return true;
6521193326Sed}
6522193326Sed
6523193326Sed/// AddTypesConvertedFrom - Add each of the types to which the type @p
6524193326Sed/// Ty can be implicit converted to the given set of @p Types. We're
6525193326Sed/// primarily interested in pointer types and enumeration types. We also
6526193326Sed/// take member pointer types, for the conditional operator.
6527193326Sed/// AllowUserConversions is true if we should look at the conversion
6528193326Sed/// functions of a class type, and AllowExplicitConversions if we
6529193326Sed/// should also include the explicit conversion functions of a class
6530193326Sed/// type.
6531198092Srdivackyvoid
6532193326SedBuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6533198398Srdivacky                                               SourceLocation Loc,
6534193326Sed                                               bool AllowUserConversions,
6535198398Srdivacky                                               bool AllowExplicitConversions,
6536198398Srdivacky                                               const Qualifiers &VisibleQuals) {
6537193326Sed  // Only deal with canonical types.
6538193326Sed  Ty = Context.getCanonicalType(Ty);
6539193326Sed
6540193326Sed  // Look through reference types; they aren't part of the type of an
6541193326Sed  // expression for the purposes of conversions.
6542198092Srdivacky  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6543193326Sed    Ty = RefTy->getPointeeType();
6544193326Sed
6545198954Srdivacky  // If we're dealing with an array type, decay to the pointer.
6546198954Srdivacky  if (Ty->isArrayType())
6547198954Srdivacky    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6548218893Sdim
6549218893Sdim  // Otherwise, we don't care about qualifiers on the type.
6550218893Sdim  Ty = Ty.getLocalUnqualifiedType();
6551218893Sdim
6552218893Sdim  // Flag if we ever add a non-record type.
6553218893Sdim  const RecordType *TyRec = Ty->getAs<RecordType>();
6554218893Sdim  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6555218893Sdim
6556218893Sdim  // Flag if we encounter an arithmetic type.
6557218893Sdim  HasArithmeticOrEnumeralTypes =
6558218893Sdim    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6559218893Sdim
6560212904Sdim  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6561212904Sdim    PointerTypes.insert(Ty);
6562212904Sdim  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6563193326Sed    // Insert our type, and its more-qualified variants, into the set
6564193326Sed    // of types.
6565198398Srdivacky    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6566193326Sed      return;
6567193326Sed  } else if (Ty->isMemberPointerType()) {
6568193326Sed    // Member pointers are far easier, since the pointee can't be converted.
6569193326Sed    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6570193326Sed      return;
6571193326Sed  } else if (Ty->isEnumeralType()) {
6572218893Sdim    HasArithmeticOrEnumeralTypes = true;
6573193326Sed    EnumerationTypes.insert(Ty);
6574208600Srdivacky  } else if (Ty->isVectorType()) {
6575218893Sdim    // We treat vector types as arithmetic types in many contexts as an
6576218893Sdim    // extension.
6577218893Sdim    HasArithmeticOrEnumeralTypes = true;
6578208600Srdivacky    VectorTypes.insert(Ty);
6579223017Sdim  } else if (Ty->isNullPtrType()) {
6580223017Sdim    HasNullPtrType = true;
6581218893Sdim  } else if (AllowUserConversions && TyRec) {
6582218893Sdim    // No conversion functions in incomplete types.
6583218893Sdim    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6584218893Sdim      return;
6585198092Srdivacky
6586218893Sdim    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6587252723Sdim    std::pair<CXXRecordDecl::conversion_iterator,
6588252723Sdim              CXXRecordDecl::conversion_iterator>
6589252723Sdim      Conversions = ClassDecl->getVisibleConversionFunctions();
6590252723Sdim    for (CXXRecordDecl::conversion_iterator
6591252723Sdim           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6592218893Sdim      NamedDecl *D = I.getDecl();
6593218893Sdim      if (isa<UsingShadowDecl>(D))
6594218893Sdim        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6595198092Srdivacky
6596218893Sdim      // Skip conversion function templates; they don't tell us anything
6597218893Sdim      // about which builtin types we can convert to.
6598218893Sdim      if (isa<FunctionTemplateDecl>(D))
6599218893Sdim        continue;
6600198092Srdivacky
6601218893Sdim      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6602218893Sdim      if (AllowExplicitConversions || !Conv->isExplicit()) {
6603218893Sdim        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6604218893Sdim                              VisibleQuals);
6605193326Sed      }
6606193326Sed    }
6607193326Sed  }
6608193326Sed}
6609193326Sed
6610198092Srdivacky/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6611198092Srdivacky/// the volatile- and non-volatile-qualified assignment operators for the
6612198092Srdivacky/// given type to the candidate set.
6613198092Srdivackystatic void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6614198092Srdivacky                                                   QualType T,
6615252723Sdim                                                   ArrayRef<Expr *> Args,
6616198092Srdivacky                                    OverloadCandidateSet &CandidateSet) {
6617198092Srdivacky  QualType ParamTypes[2];
6618198092Srdivacky
6619198092Srdivacky  // T& operator=(T&, T)
6620198092Srdivacky  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6621198092Srdivacky  ParamTypes[1] = T;
6622252723Sdim  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6623198092Srdivacky                        /*IsAssignmentOperator=*/true);
6624198092Srdivacky
6625198092Srdivacky  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6626198092Srdivacky    // volatile T& operator=(volatile T&, T)
6627198092Srdivacky    ParamTypes[0]
6628198092Srdivacky      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6629198092Srdivacky    ParamTypes[1] = T;
6630252723Sdim    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6631198092Srdivacky                          /*IsAssignmentOperator=*/true);
6632198092Srdivacky  }
6633198092Srdivacky}
6634198092Srdivacky
6635198893Srdivacky/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6636198893Srdivacky/// if any, found in visible type conversion functions found in ArgExpr's type.
6637198398Srdivackystatic  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6638198398Srdivacky    Qualifiers VRQuals;
6639198398Srdivacky    const RecordType *TyRec;
6640198398Srdivacky    if (const MemberPointerType *RHSMPType =
6641198398Srdivacky        ArgExpr->getType()->getAs<MemberPointerType>())
6642207619Srdivacky      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6643198398Srdivacky    else
6644198398Srdivacky      TyRec = ArgExpr->getType()->getAs<RecordType>();
6645198398Srdivacky    if (!TyRec) {
6646198398Srdivacky      // Just to be safe, assume the worst case.
6647198398Srdivacky      VRQuals.addVolatile();
6648198398Srdivacky      VRQuals.addRestrict();
6649198398Srdivacky      return VRQuals;
6650198398Srdivacky    }
6651218893Sdim
6652198398Srdivacky    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6653203955Srdivacky    if (!ClassDecl->hasDefinition())
6654203955Srdivacky      return VRQuals;
6655203955Srdivacky
6656252723Sdim    std::pair<CXXRecordDecl::conversion_iterator,
6657252723Sdim              CXXRecordDecl::conversion_iterator>
6658252723Sdim      Conversions = ClassDecl->getVisibleConversionFunctions();
6659218893Sdim
6660252723Sdim    for (CXXRecordDecl::conversion_iterator
6661252723Sdim           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6662206084Srdivacky      NamedDecl *D = I.getDecl();
6663206084Srdivacky      if (isa<UsingShadowDecl>(D))
6664206084Srdivacky        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6665206084Srdivacky      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6666198398Srdivacky        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6667198398Srdivacky        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6668198398Srdivacky          CanTy = ResTypeRef->getPointeeType();
6669198398Srdivacky        // Need to go down the pointer/mempointer chain and add qualifiers
6670198398Srdivacky        // as see them.
6671198398Srdivacky        bool done = false;
6672198398Srdivacky        while (!done) {
6673245431Sdim          if (CanTy.isRestrictQualified())
6674245431Sdim            VRQuals.addRestrict();
6675198398Srdivacky          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6676198398Srdivacky            CanTy = ResTypePtr->getPointeeType();
6677218893Sdim          else if (const MemberPointerType *ResTypeMPtr =
6678198398Srdivacky                CanTy->getAs<MemberPointerType>())
6679198398Srdivacky            CanTy = ResTypeMPtr->getPointeeType();
6680198398Srdivacky          else
6681198398Srdivacky            done = true;
6682198398Srdivacky          if (CanTy.isVolatileQualified())
6683198398Srdivacky            VRQuals.addVolatile();
6684198398Srdivacky          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6685198398Srdivacky            return VRQuals;
6686198398Srdivacky        }
6687198398Srdivacky      }
6688198398Srdivacky    }
6689198398Srdivacky    return VRQuals;
6690198398Srdivacky}
6691218893Sdim
6692218893Sdimnamespace {
6693218893Sdim
6694218893Sdim/// \brief Helper class to manage the addition of builtin operator overload
6695218893Sdim/// candidates. It provides shared state and utility methods used throughout
6696218893Sdim/// the process, as well as a helper method to add each group of builtin
6697218893Sdim/// operator overloads from the standard to a candidate set.
6698218893Sdimclass BuiltinOperatorOverloadBuilder {
6699218893Sdim  // Common instance state available to all overload candidate addition methods.
6700218893Sdim  Sema &S;
6701252723Sdim  ArrayRef<Expr *> Args;
6702198398Srdivacky  Qualifiers VisibleTypeConversionsQuals;
6703218893Sdim  bool HasArithmeticOrEnumeralCandidateType;
6704226890Sdim  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6705218893Sdim  OverloadCandidateSet &CandidateSet;
6706193326Sed
6707218893Sdim  // Define some constants used to index and iterate over the arithemetic types
6708218893Sdim  // provided via the getArithmeticType() method below.
6709218893Sdim  // The "promoted arithmetic types" are the arithmetic
6710218893Sdim  // types are that preserved by promotion (C++ [over.built]p2).
6711218893Sdim  static const unsigned FirstIntegralType = 3;
6712245431Sdim  static const unsigned LastIntegralType = 20;
6713218893Sdim  static const unsigned FirstPromotedIntegralType = 3,
6714245431Sdim                        LastPromotedIntegralType = 11;
6715218893Sdim  static const unsigned FirstPromotedArithmeticType = 0,
6716245431Sdim                        LastPromotedArithmeticType = 11;
6717245431Sdim  static const unsigned NumArithmeticTypes = 20;
6718193326Sed
6719218893Sdim  /// \brief Get the canonical type for a given arithmetic type index.
6720218893Sdim  CanQualType getArithmeticType(unsigned index) {
6721218893Sdim    assert(index < NumArithmeticTypes);
6722218893Sdim    static CanQualType ASTContext::* const
6723218893Sdim      ArithmeticTypes[NumArithmeticTypes] = {
6724218893Sdim      // Start of promoted types.
6725218893Sdim      &ASTContext::FloatTy,
6726218893Sdim      &ASTContext::DoubleTy,
6727218893Sdim      &ASTContext::LongDoubleTy,
6728193326Sed
6729218893Sdim      // Start of integral types.
6730218893Sdim      &ASTContext::IntTy,
6731218893Sdim      &ASTContext::LongTy,
6732218893Sdim      &ASTContext::LongLongTy,
6733245431Sdim      &ASTContext::Int128Ty,
6734218893Sdim      &ASTContext::UnsignedIntTy,
6735218893Sdim      &ASTContext::UnsignedLongTy,
6736218893Sdim      &ASTContext::UnsignedLongLongTy,
6737245431Sdim      &ASTContext::UnsignedInt128Ty,
6738218893Sdim      // End of promoted types.
6739193326Sed
6740218893Sdim      &ASTContext::BoolTy,
6741218893Sdim      &ASTContext::CharTy,
6742218893Sdim      &ASTContext::WCharTy,
6743218893Sdim      &ASTContext::Char16Ty,
6744218893Sdim      &ASTContext::Char32Ty,
6745218893Sdim      &ASTContext::SignedCharTy,
6746218893Sdim      &ASTContext::ShortTy,
6747218893Sdim      &ASTContext::UnsignedCharTy,
6748218893Sdim      &ASTContext::UnsignedShortTy,
6749218893Sdim      // End of integral types.
6750245431Sdim      // FIXME: What about complex? What about half?
6751218893Sdim    };
6752218893Sdim    return S.Context.*ArithmeticTypes[index];
6753218893Sdim  }
6754193326Sed
6755218893Sdim  /// \brief Gets the canonical type resulting from the usual arithemetic
6756218893Sdim  /// converions for the given arithmetic types.
6757218893Sdim  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6758218893Sdim    // Accelerator table for performing the usual arithmetic conversions.
6759218893Sdim    // The rules are basically:
6760218893Sdim    //   - if either is floating-point, use the wider floating-point
6761218893Sdim    //   - if same signedness, use the higher rank
6762218893Sdim    //   - if same size, use unsigned of the higher rank
6763218893Sdim    //   - use the larger type
6764218893Sdim    // These rules, together with the axiom that higher ranks are
6765218893Sdim    // never smaller, are sufficient to precompute all of these results
6766218893Sdim    // *except* when dealing with signed types of higher rank.
6767218893Sdim    // (we could precompute SLL x UI for all known platforms, but it's
6768218893Sdim    // better not to make any assumptions).
6769245431Sdim    // We assume that int128 has a higher rank than long long on all platforms.
6770218893Sdim    enum PromotedType {
6771245431Sdim            Dep=-1,
6772245431Sdim            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6773218893Sdim    };
6774245431Sdim    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6775218893Sdim                                        [LastPromotedArithmeticType] = {
6776245431Sdim/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6777245431Sdim/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6778245431Sdim/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6779245431Sdim/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6780245431Sdim/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6781245431Sdim/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6782245431Sdim/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6783245431Sdim/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6784245431Sdim/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6785245431Sdim/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6786245431Sdim/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6787218893Sdim    };
6788218893Sdim
6789218893Sdim    assert(L < LastPromotedArithmeticType);
6790218893Sdim    assert(R < LastPromotedArithmeticType);
6791218893Sdim    int Idx = ConversionsTable[L][R];
6792218893Sdim
6793218893Sdim    // Fast path: the table gives us a concrete answer.
6794218893Sdim    if (Idx != Dep) return getArithmeticType(Idx);
6795218893Sdim
6796218893Sdim    // Slow path: we need to compare widths.
6797218893Sdim    // An invariant is that the signed type has higher rank.
6798218893Sdim    CanQualType LT = getArithmeticType(L),
6799218893Sdim                RT = getArithmeticType(R);
6800218893Sdim    unsigned LW = S.Context.getIntWidth(LT),
6801218893Sdim             RW = S.Context.getIntWidth(RT);
6802218893Sdim
6803218893Sdim    // If they're different widths, use the signed type.
6804218893Sdim    if (LW > RW) return LT;
6805218893Sdim    else if (LW < RW) return RT;
6806218893Sdim
6807218893Sdim    // Otherwise, use the unsigned type of the signed type's rank.
6808218893Sdim    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6809218893Sdim    assert(L == SLL || R == SLL);
6810218893Sdim    return S.Context.UnsignedLongLongTy;
6811218893Sdim  }
6812218893Sdim
6813218893Sdim  /// \brief Helper method to factor out the common pattern of adding overloads
6814218893Sdim  /// for '++' and '--' builtin operators.
6815218893Sdim  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6816245431Sdim                                           bool HasVolatile,
6817245431Sdim                                           bool HasRestrict) {
6818218893Sdim    QualType ParamTypes[2] = {
6819218893Sdim      S.Context.getLValueReferenceType(CandidateTy),
6820218893Sdim      S.Context.IntTy
6821218893Sdim    };
6822218893Sdim
6823218893Sdim    // Non-volatile version.
6824252723Sdim    if (Args.size() == 1)
6825252723Sdim      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6826193326Sed    else
6827252723Sdim      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6828193326Sed
6829218893Sdim    // Use a heuristic to reduce number of builtin candidates in the set:
6830218893Sdim    // add volatile version only if there are conversions to a volatile type.
6831218893Sdim    if (HasVolatile) {
6832218893Sdim      ParamTypes[0] =
6833218893Sdim        S.Context.getLValueReferenceType(
6834218893Sdim          S.Context.getVolatileType(CandidateTy));
6835252723Sdim      if (Args.size() == 1)
6836252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6837193326Sed      else
6838252723Sdim        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6839193326Sed    }
6840245431Sdim
6841245431Sdim    // Add restrict version only if there are conversions to a restrict type
6842245431Sdim    // and our candidate type is a non-restrict-qualified pointer.
6843245431Sdim    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6844245431Sdim        !CandidateTy.isRestrictQualified()) {
6845245431Sdim      ParamTypes[0]
6846245431Sdim        = S.Context.getLValueReferenceType(
6847245431Sdim            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6848252723Sdim      if (Args.size() == 1)
6849252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6850245431Sdim      else
6851252723Sdim        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6852245431Sdim
6853245431Sdim      if (HasVolatile) {
6854245431Sdim        ParamTypes[0]
6855245431Sdim          = S.Context.getLValueReferenceType(
6856245431Sdim              S.Context.getCVRQualifiedType(CandidateTy,
6857245431Sdim                                            (Qualifiers::Volatile |
6858245431Sdim                                             Qualifiers::Restrict)));
6859252723Sdim        if (Args.size() == 1)
6860252723Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6861245431Sdim        else
6862252723Sdim          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6863245431Sdim      }
6864245431Sdim    }
6865245431Sdim
6866218893Sdim  }
6867193326Sed
6868218893Sdimpublic:
6869218893Sdim  BuiltinOperatorOverloadBuilder(
6870252723Sdim    Sema &S, ArrayRef<Expr *> Args,
6871218893Sdim    Qualifiers VisibleTypeConversionsQuals,
6872218893Sdim    bool HasArithmeticOrEnumeralCandidateType,
6873226890Sdim    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6874218893Sdim    OverloadCandidateSet &CandidateSet)
6875252723Sdim    : S(S), Args(Args),
6876218893Sdim      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6877218893Sdim      HasArithmeticOrEnumeralCandidateType(
6878218893Sdim        HasArithmeticOrEnumeralCandidateType),
6879218893Sdim      CandidateTypes(CandidateTypes),
6880218893Sdim      CandidateSet(CandidateSet) {
6881218893Sdim    // Validate some of our static helper constants in debug builds.
6882218893Sdim    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6883218893Sdim           "Invalid first promoted integral type");
6884218893Sdim    assert(getArithmeticType(LastPromotedIntegralType - 1)
6885245431Sdim             == S.Context.UnsignedInt128Ty &&
6886218893Sdim           "Invalid last promoted integral type");
6887218893Sdim    assert(getArithmeticType(FirstPromotedArithmeticType)
6888218893Sdim             == S.Context.FloatTy &&
6889218893Sdim           "Invalid first promoted arithmetic type");
6890218893Sdim    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6891245431Sdim             == S.Context.UnsignedInt128Ty &&
6892218893Sdim           "Invalid last promoted arithmetic type");
6893218893Sdim  }
6894218893Sdim
6895218893Sdim  // C++ [over.built]p3:
6896218893Sdim  //
6897218893Sdim  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6898218893Sdim  //   is either volatile or empty, there exist candidate operator
6899218893Sdim  //   functions of the form
6900218893Sdim  //
6901218893Sdim  //       VQ T&      operator++(VQ T&);
6902218893Sdim  //       T          operator++(VQ T&, int);
6903218893Sdim  //
6904218893Sdim  // C++ [over.built]p4:
6905218893Sdim  //
6906218893Sdim  //   For every pair (T, VQ), where T is an arithmetic type other
6907218893Sdim  //   than bool, and VQ is either volatile or empty, there exist
6908218893Sdim  //   candidate operator functions of the form
6909218893Sdim  //
6910218893Sdim  //       VQ T&      operator--(VQ T&);
6911218893Sdim  //       T          operator--(VQ T&, int);
6912218893Sdim  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6913218893Sdim    if (!HasArithmeticOrEnumeralCandidateType)
6914218893Sdim      return;
6915218893Sdim
6916218893Sdim    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6917218893Sdim         Arith < NumArithmeticTypes; ++Arith) {
6918218893Sdim      addPlusPlusMinusMinusStyleOverloads(
6919218893Sdim        getArithmeticType(Arith),
6920245431Sdim        VisibleTypeConversionsQuals.hasVolatile(),
6921245431Sdim        VisibleTypeConversionsQuals.hasRestrict());
6922218893Sdim    }
6923218893Sdim  }
6924218893Sdim
6925218893Sdim  // C++ [over.built]p5:
6926218893Sdim  //
6927218893Sdim  //   For every pair (T, VQ), where T is a cv-qualified or
6928218893Sdim  //   cv-unqualified object type, and VQ is either volatile or
6929218893Sdim  //   empty, there exist candidate operator functions of the form
6930218893Sdim  //
6931218893Sdim  //       T*VQ&      operator++(T*VQ&);
6932218893Sdim  //       T*VQ&      operator--(T*VQ&);
6933218893Sdim  //       T*         operator++(T*VQ&, int);
6934218893Sdim  //       T*         operator--(T*VQ&, int);
6935218893Sdim  void addPlusPlusMinusMinusPointerOverloads() {
6936218893Sdim    for (BuiltinCandidateTypeSet::iterator
6937218893Sdim              Ptr = CandidateTypes[0].pointer_begin(),
6938218893Sdim           PtrEnd = CandidateTypes[0].pointer_end();
6939218893Sdim         Ptr != PtrEnd; ++Ptr) {
6940193326Sed      // Skip pointer types that aren't pointers to object types.
6941218893Sdim      if (!(*Ptr)->getPointeeType()->isObjectType())
6942193326Sed        continue;
6943193326Sed
6944218893Sdim      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6945245431Sdim        (!(*Ptr).isVolatileQualified() &&
6946245431Sdim         VisibleTypeConversionsQuals.hasVolatile()),
6947245431Sdim        (!(*Ptr).isRestrictQualified() &&
6948245431Sdim         VisibleTypeConversionsQuals.hasRestrict()));
6949193326Sed    }
6950218893Sdim  }
6951193326Sed
6952218893Sdim  // C++ [over.built]p6:
6953218893Sdim  //   For every cv-qualified or cv-unqualified object type T, there
6954218893Sdim  //   exist candidate operator functions of the form
6955218893Sdim  //
6956218893Sdim  //       T&         operator*(T*);
6957218893Sdim  //
6958218893Sdim  // C++ [over.built]p7:
6959218893Sdim  //   For every function type T that does not have cv-qualifiers or a
6960218893Sdim  //   ref-qualifier, there exist candidate operator functions of the form
6961218893Sdim  //       T&         operator*(T*);
6962218893Sdim  void addUnaryStarPointerOverloads() {
6963218893Sdim    for (BuiltinCandidateTypeSet::iterator
6964218893Sdim              Ptr = CandidateTypes[0].pointer_begin(),
6965218893Sdim           PtrEnd = CandidateTypes[0].pointer_end();
6966218893Sdim         Ptr != PtrEnd; ++Ptr) {
6967193326Sed      QualType ParamTy = *Ptr;
6968212904Sdim      QualType PointeeTy = ParamTy->getPointeeType();
6969218893Sdim      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6970218893Sdim        continue;
6971193326Sed
6972218893Sdim      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6973218893Sdim        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6974218893Sdim          continue;
6975218893Sdim
6976218893Sdim      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6977252723Sdim                            &ParamTy, Args, CandidateSet);
6978193326Sed    }
6979218893Sdim  }
6980198092Srdivacky
6981218893Sdim  // C++ [over.built]p9:
6982218893Sdim  //  For every promoted arithmetic type T, there exist candidate
6983218893Sdim  //  operator functions of the form
6984218893Sdim  //
6985218893Sdim  //       T         operator+(T);
6986218893Sdim  //       T         operator-(T);
6987218893Sdim  void addUnaryPlusOrMinusArithmeticOverloads() {
6988218893Sdim    if (!HasArithmeticOrEnumeralCandidateType)
6989218893Sdim      return;
6990193326Sed
6991198092Srdivacky    for (unsigned Arith = FirstPromotedArithmeticType;
6992193326Sed         Arith < LastPromotedArithmeticType; ++Arith) {
6993218893Sdim      QualType ArithTy = getArithmeticType(Arith);
6994252723Sdim      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
6995193326Sed    }
6996218893Sdim
6997208600Srdivacky    // Extension: We also add these operators for vector types.
6998218893Sdim    for (BuiltinCandidateTypeSet::iterator
6999218893Sdim              Vec = CandidateTypes[0].vector_begin(),
7000218893Sdim           VecEnd = CandidateTypes[0].vector_end();
7001208600Srdivacky         Vec != VecEnd; ++Vec) {
7002208600Srdivacky      QualType VecTy = *Vec;
7003252723Sdim      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7004208600Srdivacky    }
7005218893Sdim  }
7006193326Sed
7007218893Sdim  // C++ [over.built]p8:
7008218893Sdim  //   For every type T, there exist candidate operator functions of
7009218893Sdim  //   the form
7010218893Sdim  //
7011218893Sdim  //       T*         operator+(T*);
7012218893Sdim  void addUnaryPlusPointerOverloads() {
7013218893Sdim    for (BuiltinCandidateTypeSet::iterator
7014218893Sdim              Ptr = CandidateTypes[0].pointer_begin(),
7015218893Sdim           PtrEnd = CandidateTypes[0].pointer_end();
7016218893Sdim         Ptr != PtrEnd; ++Ptr) {
7017218893Sdim      QualType ParamTy = *Ptr;
7018252723Sdim      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7019218893Sdim    }
7020218893Sdim  }
7021218893Sdim
7022218893Sdim  // C++ [over.built]p10:
7023218893Sdim  //   For every promoted integral type T, there exist candidate
7024218893Sdim  //   operator functions of the form
7025218893Sdim  //
7026218893Sdim  //        T         operator~(T);
7027218893Sdim  void addUnaryTildePromotedIntegralOverloads() {
7028218893Sdim    if (!HasArithmeticOrEnumeralCandidateType)
7029218893Sdim      return;
7030218893Sdim
7031198092Srdivacky    for (unsigned Int = FirstPromotedIntegralType;
7032193326Sed         Int < LastPromotedIntegralType; ++Int) {
7033218893Sdim      QualType IntTy = getArithmeticType(Int);
7034252723Sdim      S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7035193326Sed    }
7036218893Sdim
7037208600Srdivacky    // Extension: We also add this operator for vector types.
7038218893Sdim    for (BuiltinCandidateTypeSet::iterator
7039218893Sdim              Vec = CandidateTypes[0].vector_begin(),
7040218893Sdim           VecEnd = CandidateTypes[0].vector_end();
7041208600Srdivacky         Vec != VecEnd; ++Vec) {
7042208600Srdivacky      QualType VecTy = *Vec;
7043252723Sdim      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7044218893Sdim    }
7045218893Sdim  }
7046193326Sed
7047218893Sdim  // C++ [over.match.oper]p16:
7048218893Sdim  //   For every pointer to member type T, there exist candidate operator
7049218893Sdim  //   functions of the form
7050218893Sdim  //
7051218893Sdim  //        bool operator==(T,T);
7052218893Sdim  //        bool operator!=(T,T);
7053218893Sdim  void addEqualEqualOrNotEqualMemberPointerOverloads() {
7054218893Sdim    /// Set of (canonical) types that we've already handled.
7055218893Sdim    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7056193326Sed
7057252723Sdim    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7058218893Sdim      for (BuiltinCandidateTypeSet::iterator
7059218893Sdim                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7060218893Sdim             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7061218893Sdim           MemPtr != MemPtrEnd;
7062218893Sdim           ++MemPtr) {
7063218893Sdim        // Don't add the same builtin candidate twice.
7064218893Sdim        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7065218893Sdim          continue;
7066193326Sed
7067218893Sdim        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7068252723Sdim        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7069218893Sdim      }
7070198092Srdivacky    }
7071218893Sdim  }
7072198092Srdivacky
7073218893Sdim  // C++ [over.built]p15:
7074218893Sdim  //
7075223017Sdim  //   For every T, where T is an enumeration type, a pointer type, or
7076223017Sdim  //   std::nullptr_t, there exist candidate operator functions of the form
7077218893Sdim  //
7078218893Sdim  //        bool       operator<(T, T);
7079218893Sdim  //        bool       operator>(T, T);
7080218893Sdim  //        bool       operator<=(T, T);
7081218893Sdim  //        bool       operator>=(T, T);
7082218893Sdim  //        bool       operator==(T, T);
7083218893Sdim  //        bool       operator!=(T, T);
7084218893Sdim  void addRelationalPointerOrEnumeralOverloads() {
7085245431Sdim    // C++ [over.match.oper]p3:
7086245431Sdim    //   [...]the built-in candidates include all of the candidate operator
7087245431Sdim    //   functions defined in 13.6 that, compared to the given operator, [...]
7088245431Sdim    //   do not have the same parameter-type-list as any non-template non-member
7089245431Sdim    //   candidate.
7090218893Sdim    //
7091245431Sdim    // Note that in practice, this only affects enumeration types because there
7092245431Sdim    // aren't any built-in candidates of record type, and a user-defined operator
7093245431Sdim    // must have an operand of record or enumeration type. Also, the only other
7094245431Sdim    // overloaded operator with enumeration arguments, operator=,
7095218893Sdim    // cannot be overloaded for enumeration types, so this is the only place
7096218893Sdim    // where we must suppress candidates like this.
7097218893Sdim    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7098218893Sdim      UserDefinedBinaryOperators;
7099198092Srdivacky
7100252723Sdim    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7101218893Sdim      if (CandidateTypes[ArgIdx].enumeration_begin() !=
7102218893Sdim          CandidateTypes[ArgIdx].enumeration_end()) {
7103218893Sdim        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7104218893Sdim                                         CEnd = CandidateSet.end();
7105218893Sdim             C != CEnd; ++C) {
7106218893Sdim          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7107218893Sdim            continue;
7108218893Sdim
7109245431Sdim          if (C->Function->isFunctionTemplateSpecialization())
7110245431Sdim            continue;
7111245431Sdim
7112218893Sdim          QualType FirstParamType =
7113218893Sdim            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7114218893Sdim          QualType SecondParamType =
7115218893Sdim            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7116218893Sdim
7117218893Sdim          // Skip if either parameter isn't of enumeral type.
7118218893Sdim          if (!FirstParamType->isEnumeralType() ||
7119218893Sdim              !SecondParamType->isEnumeralType())
7120218893Sdim            continue;
7121218893Sdim
7122218893Sdim          // Add this operator to the set of known user-defined operators.
7123218893Sdim          UserDefinedBinaryOperators.insert(
7124218893Sdim            std::make_pair(S.Context.getCanonicalType(FirstParamType),
7125218893Sdim                           S.Context.getCanonicalType(SecondParamType)));
7126218893Sdim        }
7127218893Sdim      }
7128193326Sed    }
7129193326Sed
7130218893Sdim    /// Set of (canonical) types that we've already handled.
7131218893Sdim    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7132193326Sed
7133252723Sdim    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7134218893Sdim      for (BuiltinCandidateTypeSet::iterator
7135218893Sdim                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7136218893Sdim             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7137218893Sdim           Ptr != PtrEnd; ++Ptr) {
7138218893Sdim        // Don't add the same builtin candidate twice.
7139218893Sdim        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7140218893Sdim          continue;
7141193326Sed
7142218893Sdim        QualType ParamTypes[2] = { *Ptr, *Ptr };
7143252723Sdim        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7144218893Sdim      }
7145218893Sdim      for (BuiltinCandidateTypeSet::iterator
7146218893Sdim                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7147218893Sdim             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7148218893Sdim           Enum != EnumEnd; ++Enum) {
7149218893Sdim        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7150193326Sed
7151218893Sdim        // Don't add the same builtin candidate twice, or if a user defined
7152218893Sdim        // candidate exists.
7153218893Sdim        if (!AddedTypes.insert(CanonType) ||
7154218893Sdim            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7155218893Sdim                                                            CanonType)))
7156218893Sdim          continue;
7157193326Sed
7158218893Sdim        QualType ParamTypes[2] = { *Enum, *Enum };
7159252723Sdim        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7160218893Sdim      }
7161223017Sdim
7162223017Sdim      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7163223017Sdim        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7164223017Sdim        if (AddedTypes.insert(NullPtrTy) &&
7165252723Sdim            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7166223017Sdim                                                             NullPtrTy))) {
7167223017Sdim          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7168252723Sdim          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7169223017Sdim                                CandidateSet);
7170223017Sdim        }
7171223017Sdim      }
7172218893Sdim    }
7173218893Sdim  }
7174218893Sdim
7175218893Sdim  // C++ [over.built]p13:
7176218893Sdim  //
7177218893Sdim  //   For every cv-qualified or cv-unqualified object type T
7178218893Sdim  //   there exist candidate operator functions of the form
7179218893Sdim  //
7180218893Sdim  //      T*         operator+(T*, ptrdiff_t);
7181218893Sdim  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7182218893Sdim  //      T*         operator-(T*, ptrdiff_t);
7183218893Sdim  //      T*         operator+(ptrdiff_t, T*);
7184218893Sdim  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7185218893Sdim  //
7186218893Sdim  // C++ [over.built]p14:
7187218893Sdim  //
7188218893Sdim  //   For every T, where T is a pointer to object type, there
7189218893Sdim  //   exist candidate operator functions of the form
7190218893Sdim  //
7191218893Sdim  //      ptrdiff_t  operator-(T, T);
7192218893Sdim  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7193218893Sdim    /// Set of (canonical) types that we've already handled.
7194218893Sdim    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7195218893Sdim
7196218893Sdim    for (int Arg = 0; Arg < 2; ++Arg) {
7197218893Sdim      QualType AsymetricParamTypes[2] = {
7198218893Sdim        S.Context.getPointerDiffType(),
7199218893Sdim        S.Context.getPointerDiffType(),
7200218893Sdim      };
7201218893Sdim      for (BuiltinCandidateTypeSet::iterator
7202218893Sdim                Ptr = CandidateTypes[Arg].pointer_begin(),
7203218893Sdim             PtrEnd = CandidateTypes[Arg].pointer_end();
7204218893Sdim           Ptr != PtrEnd; ++Ptr) {
7205218893Sdim        QualType PointeeTy = (*Ptr)->getPointeeType();
7206218893Sdim        if (!PointeeTy->isObjectType())
7207218893Sdim          continue;
7208218893Sdim
7209218893Sdim        AsymetricParamTypes[Arg] = *Ptr;
7210218893Sdim        if (Arg == 0 || Op == OO_Plus) {
7211218893Sdim          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7212193326Sed          // T* operator+(ptrdiff_t, T*);
7213252723Sdim          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7214218893Sdim        }
7215218893Sdim        if (Op == OO_Minus) {
7216193326Sed          // ptrdiff_t operator-(T, T);
7217218893Sdim          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7218218893Sdim            continue;
7219218893Sdim
7220218893Sdim          QualType ParamTypes[2] = { *Ptr, *Ptr };
7221218893Sdim          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7222252723Sdim                                Args, CandidateSet);
7223193326Sed        }
7224193326Sed      }
7225193326Sed    }
7226218893Sdim  }
7227193326Sed
7228218893Sdim  // C++ [over.built]p12:
7229218893Sdim  //
7230218893Sdim  //   For every pair of promoted arithmetic types L and R, there
7231218893Sdim  //   exist candidate operator functions of the form
7232218893Sdim  //
7233218893Sdim  //        LR         operator*(L, R);
7234218893Sdim  //        LR         operator/(L, R);
7235218893Sdim  //        LR         operator+(L, R);
7236218893Sdim  //        LR         operator-(L, R);
7237218893Sdim  //        bool       operator<(L, R);
7238218893Sdim  //        bool       operator>(L, R);
7239218893Sdim  //        bool       operator<=(L, R);
7240218893Sdim  //        bool       operator>=(L, R);
7241218893Sdim  //        bool       operator==(L, R);
7242218893Sdim  //        bool       operator!=(L, R);
7243218893Sdim  //
7244218893Sdim  //   where LR is the result of the usual arithmetic conversions
7245218893Sdim  //   between types L and R.
7246218893Sdim  //
7247218893Sdim  // C++ [over.built]p24:
7248218893Sdim  //
7249218893Sdim  //   For every pair of promoted arithmetic types L and R, there exist
7250218893Sdim  //   candidate operator functions of the form
7251218893Sdim  //
7252218893Sdim  //        LR       operator?(bool, L, R);
7253218893Sdim  //
7254218893Sdim  //   where LR is the result of the usual arithmetic conversions
7255218893Sdim  //   between types L and R.
7256218893Sdim  // Our candidates ignore the first parameter.
7257218893Sdim  void addGenericBinaryArithmeticOverloads(bool isComparison) {
7258218893Sdim    if (!HasArithmeticOrEnumeralCandidateType)
7259218893Sdim      return;
7260218893Sdim
7261198092Srdivacky    for (unsigned Left = FirstPromotedArithmeticType;
7262193326Sed         Left < LastPromotedArithmeticType; ++Left) {
7263198092Srdivacky      for (unsigned Right = FirstPromotedArithmeticType;
7264193326Sed           Right < LastPromotedArithmeticType; ++Right) {
7265218893Sdim        QualType LandR[2] = { getArithmeticType(Left),
7266218893Sdim                              getArithmeticType(Right) };
7267218893Sdim        QualType Result =
7268218893Sdim          isComparison ? S.Context.BoolTy
7269218893Sdim                       : getUsualArithmeticConversions(Left, Right);
7270252723Sdim        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7271193326Sed      }
7272193326Sed    }
7273208600Srdivacky
7274208600Srdivacky    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7275208600Srdivacky    // conditional operator for vector types.
7276218893Sdim    for (BuiltinCandidateTypeSet::iterator
7277218893Sdim              Vec1 = CandidateTypes[0].vector_begin(),
7278218893Sdim           Vec1End = CandidateTypes[0].vector_end();
7279218893Sdim         Vec1 != Vec1End; ++Vec1) {
7280218893Sdim      for (BuiltinCandidateTypeSet::iterator
7281218893Sdim                Vec2 = CandidateTypes[1].vector_begin(),
7282218893Sdim             Vec2End = CandidateTypes[1].vector_end();
7283208600Srdivacky           Vec2 != Vec2End; ++Vec2) {
7284208600Srdivacky        QualType LandR[2] = { *Vec1, *Vec2 };
7285218893Sdim        QualType Result = S.Context.BoolTy;
7286218893Sdim        if (!isComparison) {
7287208600Srdivacky          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7288208600Srdivacky            Result = *Vec1;
7289208600Srdivacky          else
7290208600Srdivacky            Result = *Vec2;
7291208600Srdivacky        }
7292218893Sdim
7293252723Sdim        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7294208600Srdivacky      }
7295218893Sdim    }
7296218893Sdim  }
7297193326Sed
7298218893Sdim  // C++ [over.built]p17:
7299218893Sdim  //
7300218893Sdim  //   For every pair of promoted integral types L and R, there
7301218893Sdim  //   exist candidate operator functions of the form
7302218893Sdim  //
7303218893Sdim  //      LR         operator%(L, R);
7304218893Sdim  //      LR         operator&(L, R);
7305218893Sdim  //      LR         operator^(L, R);
7306218893Sdim  //      LR         operator|(L, R);
7307218893Sdim  //      L          operator<<(L, R);
7308218893Sdim  //      L          operator>>(L, R);
7309218893Sdim  //
7310218893Sdim  //   where LR is the result of the usual arithmetic conversions
7311218893Sdim  //   between types L and R.
7312218893Sdim  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7313218893Sdim    if (!HasArithmeticOrEnumeralCandidateType)
7314218893Sdim      return;
7315218893Sdim
7316198092Srdivacky    for (unsigned Left = FirstPromotedIntegralType;
7317193326Sed         Left < LastPromotedIntegralType; ++Left) {
7318198092Srdivacky      for (unsigned Right = FirstPromotedIntegralType;
7319193326Sed           Right < LastPromotedIntegralType; ++Right) {
7320218893Sdim        QualType LandR[2] = { getArithmeticType(Left),
7321218893Sdim                              getArithmeticType(Right) };
7322193326Sed        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7323193326Sed            ? LandR[0]
7324218893Sdim            : getUsualArithmeticConversions(Left, Right);
7325252723Sdim        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7326193326Sed      }
7327193326Sed    }
7328218893Sdim  }
7329193326Sed
7330218893Sdim  // C++ [over.built]p20:
7331218893Sdim  //
7332218893Sdim  //   For every pair (T, VQ), where T is an enumeration or
7333218893Sdim  //   pointer to member type and VQ is either volatile or
7334218893Sdim  //   empty, there exist candidate operator functions of the form
7335218893Sdim  //
7336218893Sdim  //        VQ T&      operator=(VQ T&, T);
7337218893Sdim  void addAssignmentMemberPointerOrEnumeralOverloads() {
7338218893Sdim    /// Set of (canonical) types that we've already handled.
7339218893Sdim    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7340218893Sdim
7341218893Sdim    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7342218893Sdim      for (BuiltinCandidateTypeSet::iterator
7343218893Sdim                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7344218893Sdim             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7345218893Sdim           Enum != EnumEnd; ++Enum) {
7346218893Sdim        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7347218893Sdim          continue;
7348218893Sdim
7349252723Sdim        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7350218893Sdim      }
7351218893Sdim
7352218893Sdim      for (BuiltinCandidateTypeSet::iterator
7353218893Sdim                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7354218893Sdim             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7355218893Sdim           MemPtr != MemPtrEnd; ++MemPtr) {
7356218893Sdim        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7357218893Sdim          continue;
7358218893Sdim
7359252723Sdim        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7360218893Sdim      }
7361218893Sdim    }
7362218893Sdim  }
7363218893Sdim
7364218893Sdim  // C++ [over.built]p19:
7365218893Sdim  //
7366218893Sdim  //   For every pair (T, VQ), where T is any type and VQ is either
7367218893Sdim  //   volatile or empty, there exist candidate operator functions
7368218893Sdim  //   of the form
7369218893Sdim  //
7370218893Sdim  //        T*VQ&      operator=(T*VQ&, T*);
7371218893Sdim  //
7372218893Sdim  // C++ [over.built]p21:
7373218893Sdim  //
7374218893Sdim  //   For every pair (T, VQ), where T is a cv-qualified or
7375218893Sdim  //   cv-unqualified object type and VQ is either volatile or
7376218893Sdim  //   empty, there exist candidate operator functions of the form
7377218893Sdim  //
7378218893Sdim  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7379218893Sdim  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7380218893Sdim  void addAssignmentPointerOverloads(bool isEqualOp) {
7381218893Sdim    /// Set of (canonical) types that we've already handled.
7382218893Sdim    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7383218893Sdim
7384198092Srdivacky    for (BuiltinCandidateTypeSet::iterator
7385218893Sdim              Ptr = CandidateTypes[0].pointer_begin(),
7386218893Sdim           PtrEnd = CandidateTypes[0].pointer_end();
7387218893Sdim         Ptr != PtrEnd; ++Ptr) {
7388218893Sdim      // If this is operator=, keep track of the builtin candidates we added.
7389218893Sdim      if (isEqualOp)
7390218893Sdim        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7391218893Sdim      else if (!(*Ptr)->getPointeeType()->isObjectType())
7392218893Sdim        continue;
7393193326Sed
7394193326Sed      // non-volatile version
7395218893Sdim      QualType ParamTypes[2] = {
7396218893Sdim        S.Context.getLValueReferenceType(*Ptr),
7397218893Sdim        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7398218893Sdim      };
7399252723Sdim      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7400218893Sdim                            /*IsAssigmentOperator=*/ isEqualOp);
7401193326Sed
7402245431Sdim      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7403245431Sdim                          VisibleTypeConversionsQuals.hasVolatile();
7404245431Sdim      if (NeedVolatile) {
7405193326Sed        // volatile version
7406218893Sdim        ParamTypes[0] =
7407218893Sdim          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7408252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7409218893Sdim                              /*IsAssigmentOperator=*/isEqualOp);
7410193326Sed      }
7411245431Sdim
7412245431Sdim      if (!(*Ptr).isRestrictQualified() &&
7413245431Sdim          VisibleTypeConversionsQuals.hasRestrict()) {
7414245431Sdim        // restrict version
7415245431Sdim        ParamTypes[0]
7416245431Sdim          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7417252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7418245431Sdim                              /*IsAssigmentOperator=*/isEqualOp);
7419245431Sdim
7420245431Sdim        if (NeedVolatile) {
7421245431Sdim          // volatile restrict version
7422245431Sdim          ParamTypes[0]
7423245431Sdim            = S.Context.getLValueReferenceType(
7424245431Sdim                S.Context.getCVRQualifiedType(*Ptr,
7425245431Sdim                                              (Qualifiers::Volatile |
7426245431Sdim                                               Qualifiers::Restrict)));
7427252723Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7428245431Sdim                                /*IsAssigmentOperator=*/isEqualOp);
7429245431Sdim        }
7430245431Sdim      }
7431193326Sed    }
7432193326Sed
7433218893Sdim    if (isEqualOp) {
7434218893Sdim      for (BuiltinCandidateTypeSet::iterator
7435218893Sdim                Ptr = CandidateTypes[1].pointer_begin(),
7436218893Sdim             PtrEnd = CandidateTypes[1].pointer_end();
7437218893Sdim           Ptr != PtrEnd; ++Ptr) {
7438218893Sdim        // Make sure we don't add the same candidate twice.
7439218893Sdim        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7440218893Sdim          continue;
7441218893Sdim
7442218893Sdim        QualType ParamTypes[2] = {
7443218893Sdim          S.Context.getLValueReferenceType(*Ptr),
7444218893Sdim          *Ptr,
7445218893Sdim        };
7446218893Sdim
7447218893Sdim        // non-volatile version
7448252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7449218893Sdim                              /*IsAssigmentOperator=*/true);
7450218893Sdim
7451245431Sdim        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7452245431Sdim                           VisibleTypeConversionsQuals.hasVolatile();
7453245431Sdim        if (NeedVolatile) {
7454218893Sdim          // volatile version
7455218893Sdim          ParamTypes[0] =
7456218893Sdim            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7457252723Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7458252723Sdim                                /*IsAssigmentOperator=*/true);
7459218893Sdim        }
7460245431Sdim
7461245431Sdim        if (!(*Ptr).isRestrictQualified() &&
7462245431Sdim            VisibleTypeConversionsQuals.hasRestrict()) {
7463245431Sdim          // restrict version
7464245431Sdim          ParamTypes[0]
7465245431Sdim            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7466252723Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7467252723Sdim                                /*IsAssigmentOperator=*/true);
7468245431Sdim
7469245431Sdim          if (NeedVolatile) {
7470245431Sdim            // volatile restrict version
7471245431Sdim            ParamTypes[0]
7472245431Sdim              = S.Context.getLValueReferenceType(
7473245431Sdim                  S.Context.getCVRQualifiedType(*Ptr,
7474245431Sdim                                                (Qualifiers::Volatile |
7475245431Sdim                                                 Qualifiers::Restrict)));
7476252723Sdim            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7477252723Sdim                                  /*IsAssigmentOperator=*/true);
7478245431Sdim          }
7479245431Sdim        }
7480218893Sdim      }
7481218893Sdim    }
7482218893Sdim  }
7483218893Sdim
7484218893Sdim  // C++ [over.built]p18:
7485218893Sdim  //
7486218893Sdim  //   For every triple (L, VQ, R), where L is an arithmetic type,
7487218893Sdim  //   VQ is either volatile or empty, and R is a promoted
7488218893Sdim  //   arithmetic type, there exist candidate operator functions of
7489218893Sdim  //   the form
7490218893Sdim  //
7491218893Sdim  //        VQ L&      operator=(VQ L&, R);
7492218893Sdim  //        VQ L&      operator*=(VQ L&, R);
7493218893Sdim  //        VQ L&      operator/=(VQ L&, R);
7494218893Sdim  //        VQ L&      operator+=(VQ L&, R);
7495218893Sdim  //        VQ L&      operator-=(VQ L&, R);
7496218893Sdim  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7497218893Sdim    if (!HasArithmeticOrEnumeralCandidateType)
7498218893Sdim      return;
7499218893Sdim
7500193326Sed    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7501198092Srdivacky      for (unsigned Right = FirstPromotedArithmeticType;
7502193326Sed           Right < LastPromotedArithmeticType; ++Right) {
7503193326Sed        QualType ParamTypes[2];
7504218893Sdim        ParamTypes[1] = getArithmeticType(Right);
7505193326Sed
7506193326Sed        // Add this built-in operator as a candidate (VQ is empty).
7507218893Sdim        ParamTypes[0] =
7508218893Sdim          S.Context.getLValueReferenceType(getArithmeticType(Left));
7509252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7510218893Sdim                              /*IsAssigmentOperator=*/isEqualOp);
7511193326Sed
7512193326Sed        // Add this built-in operator as a candidate (VQ is 'volatile').
7513198398Srdivacky        if (VisibleTypeConversionsQuals.hasVolatile()) {
7514218893Sdim          ParamTypes[0] =
7515218893Sdim            S.Context.getVolatileType(getArithmeticType(Left));
7516218893Sdim          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7517252723Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7518218893Sdim                                /*IsAssigmentOperator=*/isEqualOp);
7519198398Srdivacky        }
7520193326Sed      }
7521193326Sed    }
7522218893Sdim
7523208600Srdivacky    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7524218893Sdim    for (BuiltinCandidateTypeSet::iterator
7525218893Sdim              Vec1 = CandidateTypes[0].vector_begin(),
7526218893Sdim           Vec1End = CandidateTypes[0].vector_end();
7527218893Sdim         Vec1 != Vec1End; ++Vec1) {
7528218893Sdim      for (BuiltinCandidateTypeSet::iterator
7529218893Sdim                Vec2 = CandidateTypes[1].vector_begin(),
7530218893Sdim             Vec2End = CandidateTypes[1].vector_end();
7531208600Srdivacky           Vec2 != Vec2End; ++Vec2) {
7532208600Srdivacky        QualType ParamTypes[2];
7533208600Srdivacky        ParamTypes[1] = *Vec2;
7534208600Srdivacky        // Add this built-in operator as a candidate (VQ is empty).
7535218893Sdim        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7536252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7537218893Sdim                              /*IsAssigmentOperator=*/isEqualOp);
7538218893Sdim
7539208600Srdivacky        // Add this built-in operator as a candidate (VQ is 'volatile').
7540208600Srdivacky        if (VisibleTypeConversionsQuals.hasVolatile()) {
7541218893Sdim          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7542218893Sdim          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7543252723Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7544218893Sdim                                /*IsAssigmentOperator=*/isEqualOp);
7545208600Srdivacky        }
7546208600Srdivacky      }
7547218893Sdim    }
7548218893Sdim  }
7549193326Sed
7550218893Sdim  // C++ [over.built]p22:
7551218893Sdim  //
7552218893Sdim  //   For every triple (L, VQ, R), where L is an integral type, VQ
7553218893Sdim  //   is either volatile or empty, and R is a promoted integral
7554218893Sdim  //   type, there exist candidate operator functions of the form
7555218893Sdim  //
7556218893Sdim  //        VQ L&       operator%=(VQ L&, R);
7557218893Sdim  //        VQ L&       operator<<=(VQ L&, R);
7558218893Sdim  //        VQ L&       operator>>=(VQ L&, R);
7559218893Sdim  //        VQ L&       operator&=(VQ L&, R);
7560218893Sdim  //        VQ L&       operator^=(VQ L&, R);
7561218893Sdim  //        VQ L&       operator|=(VQ L&, R);
7562218893Sdim  void addAssignmentIntegralOverloads() {
7563218893Sdim    if (!HasArithmeticOrEnumeralCandidateType)
7564218893Sdim      return;
7565218893Sdim
7566193326Sed    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7567198092Srdivacky      for (unsigned Right = FirstPromotedIntegralType;
7568193326Sed           Right < LastPromotedIntegralType; ++Right) {
7569193326Sed        QualType ParamTypes[2];
7570218893Sdim        ParamTypes[1] = getArithmeticType(Right);
7571193326Sed
7572193326Sed        // Add this built-in operator as a candidate (VQ is empty).
7573218893Sdim        ParamTypes[0] =
7574218893Sdim          S.Context.getLValueReferenceType(getArithmeticType(Left));
7575252723Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7576198398Srdivacky        if (VisibleTypeConversionsQuals.hasVolatile()) {
7577198398Srdivacky          // Add this built-in operator as a candidate (VQ is 'volatile').
7578218893Sdim          ParamTypes[0] = getArithmeticType(Left);
7579218893Sdim          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7580218893Sdim          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7581252723Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7582198398Srdivacky        }
7583193326Sed      }
7584193326Sed    }
7585193326Sed  }
7586193326Sed
7587218893Sdim  // C++ [over.operator]p23:
7588218893Sdim  //
7589218893Sdim  //   There also exist candidate operator functions of the form
7590218893Sdim  //
7591218893Sdim  //        bool        operator!(bool);
7592218893Sdim  //        bool        operator&&(bool, bool);
7593218893Sdim  //        bool        operator||(bool, bool);
7594218893Sdim  void addExclaimOverload() {
7595218893Sdim    QualType ParamTy = S.Context.BoolTy;
7596252723Sdim    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7597218893Sdim                          /*IsAssignmentOperator=*/false,
7598218893Sdim                          /*NumContextualBoolArguments=*/1);
7599193326Sed  }
7600218893Sdim  void addAmpAmpOrPipePipeOverload() {
7601218893Sdim    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7602252723Sdim    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7603218893Sdim                          /*IsAssignmentOperator=*/false,
7604218893Sdim                          /*NumContextualBoolArguments=*/2);
7605218893Sdim  }
7606193326Sed
7607218893Sdim  // C++ [over.built]p13:
7608218893Sdim  //
7609218893Sdim  //   For every cv-qualified or cv-unqualified object type T there
7610218893Sdim  //   exist candidate operator functions of the form
7611218893Sdim  //
7612218893Sdim  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7613218893Sdim  //        T&         operator[](T*, ptrdiff_t);
7614218893Sdim  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7615218893Sdim  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7616218893Sdim  //        T&         operator[](ptrdiff_t, T*);
7617218893Sdim  void addSubscriptOverloads() {
7618218893Sdim    for (BuiltinCandidateTypeSet::iterator
7619218893Sdim              Ptr = CandidateTypes[0].pointer_begin(),
7620218893Sdim           PtrEnd = CandidateTypes[0].pointer_end();
7621218893Sdim         Ptr != PtrEnd; ++Ptr) {
7622218893Sdim      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7623212904Sdim      QualType PointeeType = (*Ptr)->getPointeeType();
7624218893Sdim      if (!PointeeType->isObjectType())
7625218893Sdim        continue;
7626193326Sed
7627218893Sdim      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7628218893Sdim
7629193326Sed      // T& operator[](T*, ptrdiff_t)
7630252723Sdim      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7631218893Sdim    }
7632193326Sed
7633218893Sdim    for (BuiltinCandidateTypeSet::iterator
7634218893Sdim              Ptr = CandidateTypes[1].pointer_begin(),
7635218893Sdim           PtrEnd = CandidateTypes[1].pointer_end();
7636218893Sdim         Ptr != PtrEnd; ++Ptr) {
7637218893Sdim      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7638218893Sdim      QualType PointeeType = (*Ptr)->getPointeeType();
7639218893Sdim      if (!PointeeType->isObjectType())
7640218893Sdim        continue;
7641193326Sed
7642218893Sdim      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7643218893Sdim
7644218893Sdim      // T& operator[](ptrdiff_t, T*)
7645252723Sdim      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7646218893Sdim    }
7647218893Sdim  }
7648218893Sdim
7649218893Sdim  // C++ [over.built]p11:
7650218893Sdim  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7651218893Sdim  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7652218893Sdim  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7653218893Sdim  //    there exist candidate operator functions of the form
7654218893Sdim  //
7655218893Sdim  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7656218893Sdim  //
7657218893Sdim  //    where CV12 is the union of CV1 and CV2.
7658218893Sdim  void addArrowStarOverloads() {
7659218893Sdim    for (BuiltinCandidateTypeSet::iterator
7660218893Sdim             Ptr = CandidateTypes[0].pointer_begin(),
7661218893Sdim           PtrEnd = CandidateTypes[0].pointer_end();
7662218893Sdim         Ptr != PtrEnd; ++Ptr) {
7663218893Sdim      QualType C1Ty = (*Ptr);
7664218893Sdim      QualType C1;
7665218893Sdim      QualifierCollector Q1;
7666218893Sdim      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7667218893Sdim      if (!isa<RecordType>(C1))
7668218893Sdim        continue;
7669218893Sdim      // heuristic to reduce number of builtin candidates in the set.
7670218893Sdim      // Add volatile/restrict version only if there are conversions to a
7671218893Sdim      // volatile/restrict type.
7672218893Sdim      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7673218893Sdim        continue;
7674218893Sdim      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7675218893Sdim        continue;
7676218893Sdim      for (BuiltinCandidateTypeSet::iterator
7677218893Sdim                MemPtr = CandidateTypes[1].member_pointer_begin(),
7678218893Sdim             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7679218893Sdim           MemPtr != MemPtrEnd; ++MemPtr) {
7680218893Sdim        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7681218893Sdim        QualType C2 = QualType(mptr->getClass(), 0);
7682218893Sdim        C2 = C2.getUnqualifiedType();
7683218893Sdim        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7684218893Sdim          break;
7685218893Sdim        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7686218893Sdim        // build CV12 T&
7687218893Sdim        QualType T = mptr->getPointeeType();
7688218893Sdim        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7689218893Sdim            T.isVolatileQualified())
7690212904Sdim          continue;
7691218893Sdim        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7692218893Sdim            T.isRestrictQualified())
7693212904Sdim          continue;
7694218893Sdim        T = Q1.apply(S.Context, T);
7695218893Sdim        QualType ResultTy = S.Context.getLValueReferenceType(T);
7696252723Sdim        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7697218893Sdim      }
7698218893Sdim    }
7699218893Sdim  }
7700218893Sdim
7701218893Sdim  // Note that we don't consider the first argument, since it has been
7702218893Sdim  // contextually converted to bool long ago. The candidates below are
7703218893Sdim  // therefore added as binary.
7704218893Sdim  //
7705218893Sdim  // C++ [over.built]p25:
7706218893Sdim  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7707218893Sdim  //   enumeration type, there exist candidate operator functions of the form
7708218893Sdim  //
7709218893Sdim  //        T        operator?(bool, T, T);
7710218893Sdim  //
7711218893Sdim  void addConditionalOperatorOverloads() {
7712218893Sdim    /// Set of (canonical) types that we've already handled.
7713218893Sdim    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7714218893Sdim
7715218893Sdim    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7716218893Sdim      for (BuiltinCandidateTypeSet::iterator
7717218893Sdim                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7718218893Sdim             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7719218893Sdim           Ptr != PtrEnd; ++Ptr) {
7720218893Sdim        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7721212904Sdim          continue;
7722218893Sdim
7723218893Sdim        QualType ParamTypes[2] = { *Ptr, *Ptr };
7724252723Sdim        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7725218893Sdim      }
7726218893Sdim
7727218893Sdim      for (BuiltinCandidateTypeSet::iterator
7728218893Sdim                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7729218893Sdim             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7730218893Sdim           MemPtr != MemPtrEnd; ++MemPtr) {
7731218893Sdim        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7732218893Sdim          continue;
7733218893Sdim
7734218893Sdim        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7735252723Sdim        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7736218893Sdim      }
7737218893Sdim
7738252723Sdim      if (S.getLangOpts().CPlusPlus11) {
7739198092Srdivacky        for (BuiltinCandidateTypeSet::iterator
7740218893Sdim                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7741218893Sdim               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7742218893Sdim             Enum != EnumEnd; ++Enum) {
7743218893Sdim          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7744198398Srdivacky            continue;
7745218893Sdim
7746218893Sdim          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7747198398Srdivacky            continue;
7748218893Sdim
7749218893Sdim          QualType ParamTypes[2] = { *Enum, *Enum };
7750252723Sdim          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7751198092Srdivacky        }
7752198092Srdivacky      }
7753198092Srdivacky    }
7754218893Sdim  }
7755218893Sdim};
7756218893Sdim
7757218893Sdim} // end anonymous namespace
7758218893Sdim
7759218893Sdim/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7760218893Sdim/// operator overloads to the candidate set (C++ [over.built]), based
7761218893Sdim/// on the operator @p Op and the arguments given. For example, if the
7762218893Sdim/// operator is a binary '+', this routine might add "int
7763218893Sdim/// operator+(int, int)" to cover integer addition.
7764263509Sdimvoid Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7765263509Sdim                                        SourceLocation OpLoc,
7766263509Sdim                                        ArrayRef<Expr *> Args,
7767263509Sdim                                        OverloadCandidateSet &CandidateSet) {
7768218893Sdim  // Find all of the types that the arguments can convert to, but only
7769218893Sdim  // if the operator we're looking at has built-in operator candidates
7770218893Sdim  // that make use of these types. Also record whether we encounter non-record
7771218893Sdim  // candidate types or either arithmetic or enumeral candidate types.
7772218893Sdim  Qualifiers VisibleTypeConversionsQuals;
7773218893Sdim  VisibleTypeConversionsQuals.addConst();
7774252723Sdim  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7775218893Sdim    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7776218893Sdim
7777218893Sdim  bool HasNonRecordCandidateType = false;
7778218893Sdim  bool HasArithmeticOrEnumeralCandidateType = false;
7779226890Sdim  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7780252723Sdim  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7781218893Sdim    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7782218893Sdim    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7783218893Sdim                                                 OpLoc,
7784218893Sdim                                                 true,
7785218893Sdim                                                 (Op == OO_Exclaim ||
7786218893Sdim                                                  Op == OO_AmpAmp ||
7787218893Sdim                                                  Op == OO_PipePipe),
7788218893Sdim                                                 VisibleTypeConversionsQuals);
7789218893Sdim    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7790218893Sdim        CandidateTypes[ArgIdx].hasNonRecordTypes();
7791218893Sdim    HasArithmeticOrEnumeralCandidateType =
7792218893Sdim        HasArithmeticOrEnumeralCandidateType ||
7793218893Sdim        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7794218893Sdim  }
7795218893Sdim
7796218893Sdim  // Exit early when no non-record types have been added to the candidate set
7797218893Sdim  // for any of the arguments to the operator.
7798226890Sdim  //
7799226890Sdim  // We can't exit early for !, ||, or &&, since there we have always have
7800226890Sdim  // 'bool' overloads.
7801252723Sdim  if (!HasNonRecordCandidateType &&
7802226890Sdim      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7803218893Sdim    return;
7804218893Sdim
7805218893Sdim  // Setup an object to manage the common state for building overloads.
7806252723Sdim  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7807218893Sdim                                           VisibleTypeConversionsQuals,
7808218893Sdim                                           HasArithmeticOrEnumeralCandidateType,
7809218893Sdim                                           CandidateTypes, CandidateSet);
7810218893Sdim
7811218893Sdim  // Dispatch over the operation to add in only those overloads which apply.
7812218893Sdim  switch (Op) {
7813218893Sdim  case OO_None:
7814218893Sdim  case NUM_OVERLOADED_OPERATORS:
7815226890Sdim    llvm_unreachable("Expected an overloaded operator");
7816193326Sed
7817218893Sdim  case OO_New:
7818218893Sdim  case OO_Delete:
7819218893Sdim  case OO_Array_New:
7820218893Sdim  case OO_Array_Delete:
7821218893Sdim  case OO_Call:
7822226890Sdim    llvm_unreachable(
7823226890Sdim                    "Special operators don't use AddBuiltinOperatorCandidates");
7824218893Sdim
7825218893Sdim  case OO_Comma:
7826218893Sdim  case OO_Arrow:
7827218893Sdim    // C++ [over.match.oper]p3:
7828218893Sdim    //   -- For the operator ',', the unary operator '&', or the
7829218893Sdim    //      operator '->', the built-in candidates set is empty.
7830218893Sdim    break;
7831218893Sdim
7832218893Sdim  case OO_Plus: // '+' is either unary or binary
7833252723Sdim    if (Args.size() == 1)
7834218893Sdim      OpBuilder.addUnaryPlusPointerOverloads();
7835218893Sdim    // Fall through.
7836218893Sdim
7837218893Sdim  case OO_Minus: // '-' is either unary or binary
7838252723Sdim    if (Args.size() == 1) {
7839218893Sdim      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7840218893Sdim    } else {
7841218893Sdim      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7842218893Sdim      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7843218893Sdim    }
7844218893Sdim    break;
7845218893Sdim
7846218893Sdim  case OO_Star: // '*' is either unary or binary
7847252723Sdim    if (Args.size() == 1)
7848218893Sdim      OpBuilder.addUnaryStarPointerOverloads();
7849218893Sdim    else
7850218893Sdim      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7851218893Sdim    break;
7852218893Sdim
7853218893Sdim  case OO_Slash:
7854218893Sdim    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7855218893Sdim    break;
7856218893Sdim
7857218893Sdim  case OO_PlusPlus:
7858218893Sdim  case OO_MinusMinus:
7859218893Sdim    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7860218893Sdim    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7861218893Sdim    break;
7862218893Sdim
7863218893Sdim  case OO_EqualEqual:
7864218893Sdim  case OO_ExclaimEqual:
7865218893Sdim    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7866218893Sdim    // Fall through.
7867218893Sdim
7868218893Sdim  case OO_Less:
7869218893Sdim  case OO_Greater:
7870218893Sdim  case OO_LessEqual:
7871218893Sdim  case OO_GreaterEqual:
7872218893Sdim    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7873218893Sdim    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7874218893Sdim    break;
7875218893Sdim
7876218893Sdim  case OO_Percent:
7877218893Sdim  case OO_Caret:
7878218893Sdim  case OO_Pipe:
7879218893Sdim  case OO_LessLess:
7880218893Sdim  case OO_GreaterGreater:
7881218893Sdim    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7882218893Sdim    break;
7883218893Sdim
7884218893Sdim  case OO_Amp: // '&' is either unary or binary
7885252723Sdim    if (Args.size() == 1)
7886218893Sdim      // C++ [over.match.oper]p3:
7887218893Sdim      //   -- For the operator ',', the unary operator '&', or the
7888218893Sdim      //      operator '->', the built-in candidates set is empty.
7889218893Sdim      break;
7890218893Sdim
7891218893Sdim    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7892218893Sdim    break;
7893218893Sdim
7894218893Sdim  case OO_Tilde:
7895218893Sdim    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7896218893Sdim    break;
7897218893Sdim
7898218893Sdim  case OO_Equal:
7899218893Sdim    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7900218893Sdim    // Fall through.
7901218893Sdim
7902218893Sdim  case OO_PlusEqual:
7903218893Sdim  case OO_MinusEqual:
7904218893Sdim    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7905218893Sdim    // Fall through.
7906218893Sdim
7907218893Sdim  case OO_StarEqual:
7908218893Sdim  case OO_SlashEqual:
7909218893Sdim    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7910218893Sdim    break;
7911218893Sdim
7912218893Sdim  case OO_PercentEqual:
7913218893Sdim  case OO_LessLessEqual:
7914218893Sdim  case OO_GreaterGreaterEqual:
7915218893Sdim  case OO_AmpEqual:
7916218893Sdim  case OO_CaretEqual:
7917218893Sdim  case OO_PipeEqual:
7918218893Sdim    OpBuilder.addAssignmentIntegralOverloads();
7919218893Sdim    break;
7920218893Sdim
7921218893Sdim  case OO_Exclaim:
7922218893Sdim    OpBuilder.addExclaimOverload();
7923218893Sdim    break;
7924218893Sdim
7925218893Sdim  case OO_AmpAmp:
7926218893Sdim  case OO_PipePipe:
7927218893Sdim    OpBuilder.addAmpAmpOrPipePipeOverload();
7928218893Sdim    break;
7929218893Sdim
7930218893Sdim  case OO_Subscript:
7931218893Sdim    OpBuilder.addSubscriptOverloads();
7932218893Sdim    break;
7933218893Sdim
7934218893Sdim  case OO_ArrowStar:
7935218893Sdim    OpBuilder.addArrowStarOverloads();
7936218893Sdim    break;
7937218893Sdim
7938193326Sed  case OO_Conditional:
7939218893Sdim    OpBuilder.addConditionalOperatorOverloads();
7940218893Sdim    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7941218893Sdim    break;
7942193326Sed  }
7943193326Sed}
7944193326Sed
7945193326Sed/// \brief Add function candidates found via argument-dependent lookup
7946193326Sed/// to the set of overloading candidates.
7947193326Sed///
7948193326Sed/// This routine performs argument-dependent name lookup based on the
7949193326Sed/// given function name (which may also be an operator name) and adds
7950193326Sed/// all of the overload candidates found by ADL to the overload
7951193326Sed/// candidate set (C++ [basic.lookup.argdep]).
7952198092Srdivackyvoid
7953193326SedSema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7954235633Sdim                                           bool Operator, SourceLocation Loc,
7955252723Sdim                                           ArrayRef<Expr *> Args,
7956221345Sdim                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7957198092Srdivacky                                           OverloadCandidateSet& CandidateSet,
7958245431Sdim                                           bool PartialOverloading) {
7959203955Srdivacky  ADLResult Fns;
7960193326Sed
7961203955Srdivacky  // FIXME: This approach for uniquing ADL results (and removing
7962203955Srdivacky  // redundant candidates from the set) relies on pointer-equality,
7963203955Srdivacky  // which means we need to key off the canonical decl.  However,
7964203955Srdivacky  // always going back to the canonical decl might not get us the
7965203955Srdivacky  // right set of default arguments.  What default arguments are
7966203955Srdivacky  // we supposed to consider on ADL candidates, anyway?
7967193326Sed
7968198092Srdivacky  // FIXME: Pass in the explicit template arguments?
7969245431Sdim  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7970193326Sed
7971193326Sed  // Erase all of the candidates we already knew about.
7972193326Sed  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7973193326Sed                                   CandEnd = CandidateSet.end();
7974193326Sed       Cand != CandEnd; ++Cand)
7975195341Sed    if (Cand->Function) {
7976203955Srdivacky      Fns.erase(Cand->Function);
7977195341Sed      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7978203955Srdivacky        Fns.erase(FunTmpl);
7979195341Sed    }
7980193326Sed
7981193326Sed  // For each of the ADL candidates we found, add it to the overload
7982193326Sed  // set.
7983203955Srdivacky  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7984205408Srdivacky    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7985203955Srdivacky    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7986199990Srdivacky      if (ExplicitTemplateArgs)
7987198092Srdivacky        continue;
7988218893Sdim
7989235633Sdim      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7990235633Sdim                           PartialOverloading);
7991198092Srdivacky    } else
7992203955Srdivacky      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7993205408Srdivacky                                   FoundDecl, ExplicitTemplateArgs,
7994235633Sdim                                   Args, CandidateSet);
7995195341Sed  }
7996193326Sed}
7997193326Sed
7998193326Sed/// isBetterOverloadCandidate - Determines whether the first overload
7999193326Sed/// candidate is a better candidate than the second (C++ 13.3.3p1).
8000198092Srdivackybool
8001212904SdimisBetterOverloadCandidate(Sema &S,
8002218893Sdim                          const OverloadCandidate &Cand1,
8003218893Sdim                          const OverloadCandidate &Cand2,
8004218893Sdim                          SourceLocation Loc,
8005218893Sdim                          bool UserDefinedConversion) {
8006193326Sed  // Define viable functions to be better candidates than non-viable
8007193326Sed  // functions.
8008193326Sed  if (!Cand2.Viable)
8009193326Sed    return Cand1.Viable;
8010193326Sed  else if (!Cand1.Viable)
8011193326Sed    return false;
8012193326Sed
8013193326Sed  // C++ [over.match.best]p1:
8014193326Sed  //
8015193326Sed  //   -- if F is a static member function, ICS1(F) is defined such
8016193326Sed  //      that ICS1(F) is neither better nor worse than ICS1(G) for
8017193326Sed  //      any function G, and, symmetrically, ICS1(G) is neither
8018193326Sed  //      better nor worse than ICS1(F).
8019193326Sed  unsigned StartArg = 0;
8020193326Sed  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8021193326Sed    StartArg = 1;
8022193326Sed
8023198092Srdivacky  // C++ [over.match.best]p1:
8024198092Srdivacky  //   A viable function F1 is defined to be a better function than another
8025198092Srdivacky  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8026198092Srdivacky  //   conversion sequence than ICSi(F2), and then...
8027235633Sdim  unsigned NumArgs = Cand1.NumConversions;
8028235633Sdim  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8029193326Sed  bool HasBetterConversion = false;
8030193326Sed  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8031212904Sdim    switch (CompareImplicitConversionSequences(S,
8032212904Sdim                                               Cand1.Conversions[ArgIdx],
8033193326Sed                                               Cand2.Conversions[ArgIdx])) {
8034193326Sed    case ImplicitConversionSequence::Better:
8035193326Sed      // Cand1 has a better conversion sequence.
8036193326Sed      HasBetterConversion = true;
8037193326Sed      break;
8038193326Sed
8039193326Sed    case ImplicitConversionSequence::Worse:
8040193326Sed      // Cand1 can't be better than Cand2.
8041193326Sed      return false;
8042193326Sed
8043193326Sed    case ImplicitConversionSequence::Indistinguishable:
8044193326Sed      // Do nothing.
8045193326Sed      break;
8046193326Sed    }
8047193326Sed  }
8048193326Sed
8049198092Srdivacky  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8050198092Srdivacky  //       ICSj(F2), or, if not that,
8051193326Sed  if (HasBetterConversion)
8052193326Sed    return true;
8053193326Sed
8054198092Srdivacky  //     - F1 is a non-template function and F2 is a function template
8055198092Srdivacky  //       specialization, or, if not that,
8056210299Sed  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
8057198092Srdivacky      Cand2.Function && Cand2.Function->getPrimaryTemplate())
8058198092Srdivacky    return true;
8059193326Sed
8060198092Srdivacky  //   -- F1 and F2 are function template specializations, and the function
8061198092Srdivacky  //      template for F1 is more specialized than the template for F2
8062198092Srdivacky  //      according to the partial ordering rules described in 14.5.5.2, or,
8063198092Srdivacky  //      if not that,
8064198092Srdivacky  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
8065218893Sdim      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
8066198092Srdivacky    if (FunctionTemplateDecl *BetterTemplate
8067212904Sdim          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8068212904Sdim                                         Cand2.Function->getPrimaryTemplate(),
8069212904Sdim                                         Loc,
8070218893Sdim                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8071218893Sdim                                                             : TPOC_Call,
8072263509Sdim                                         Cand1.ExplicitCallArguments,
8073263509Sdim                                         Cand2.ExplicitCallArguments))
8074198092Srdivacky      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8075218893Sdim  }
8076198092Srdivacky
8077193326Sed  //   -- the context is an initialization by user-defined conversion
8078193326Sed  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8079193326Sed  //      from the return type of F1 to the destination type (i.e.,
8080193326Sed  //      the type of the entity being initialized) is a better
8081193326Sed  //      conversion sequence than the standard conversion sequence
8082193326Sed  //      from the return type of F2 to the destination type.
8083218893Sdim  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8084198092Srdivacky      isa<CXXConversionDecl>(Cand1.Function) &&
8085193326Sed      isa<CXXConversionDecl>(Cand2.Function)) {
8086235633Sdim    // First check whether we prefer one of the conversion functions over the
8087235633Sdim    // other. This only distinguishes the results in non-standard, extension
8088235633Sdim    // cases such as the conversion from a lambda closure type to a function
8089235633Sdim    // pointer or block.
8090235633Sdim    ImplicitConversionSequence::CompareKind FuncResult
8091235633Sdim      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8092235633Sdim    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8093235633Sdim      return FuncResult;
8094235633Sdim
8095212904Sdim    switch (CompareStandardConversionSequences(S,
8096212904Sdim                                               Cand1.FinalConversion,
8097193326Sed                                               Cand2.FinalConversion)) {
8098193326Sed    case ImplicitConversionSequence::Better:
8099193326Sed      // Cand1 has a better conversion sequence.
8100193326Sed      return true;
8101193326Sed
8102193326Sed    case ImplicitConversionSequence::Worse:
8103193326Sed      // Cand1 can't be better than Cand2.
8104193326Sed      return false;
8105193326Sed
8106193326Sed    case ImplicitConversionSequence::Indistinguishable:
8107193326Sed      // Do nothing
8108193326Sed      break;
8109193326Sed    }
8110193326Sed  }
8111193326Sed
8112193326Sed  return false;
8113193326Sed}
8114193326Sed
8115198092Srdivacky/// \brief Computes the best viable function (C++ 13.3.3)
8116194613Sed/// within an overload candidate set.
8117194613Sed///
8118245431Sdim/// \param Loc The location of the function name (or operator symbol) for
8119194613Sed/// which overload resolution occurs.
8120194613Sed///
8121245431Sdim/// \param Best If overload resolution was successful or found a deleted
8122245431Sdim/// function, \p Best points to the candidate function found.
8123194613Sed///
8124194613Sed/// \returns The result of overload resolution.
8125212904SdimOverloadingResult
8126212904SdimOverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8127218893Sdim                                         iterator &Best,
8128218893Sdim                                         bool UserDefinedConversion) {
8129193326Sed  // Find the best viable function.
8130212904Sdim  Best = end();
8131212904Sdim  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8132212904Sdim    if (Cand->Viable)
8133218893Sdim      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8134218893Sdim                                                     UserDefinedConversion))
8135193326Sed        Best = Cand;
8136193326Sed  }
8137193326Sed
8138193326Sed  // If we didn't find any viable functions, abort.
8139212904Sdim  if (Best == end())
8140193326Sed    return OR_No_Viable_Function;
8141193326Sed
8142193326Sed  // Make sure that this function is better than every other viable
8143193326Sed  // function. If not, we have an ambiguity.
8144212904Sdim  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8145198092Srdivacky    if (Cand->Viable &&
8146193326Sed        Cand != Best &&
8147218893Sdim        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8148218893Sdim                                   UserDefinedConversion)) {
8149212904Sdim      Best = end();
8150193326Sed      return OR_Ambiguous;
8151193326Sed    }
8152193326Sed  }
8153198092Srdivacky
8154193326Sed  // Best is the best viable function.
8155193326Sed  if (Best->Function &&
8156224145Sdim      (Best->Function->isDeleted() ||
8157224145Sdim       S.isFunctionConsideredUnavailable(Best->Function)))
8158193326Sed    return OR_Deleted;
8159193326Sed
8160193326Sed  return OR_Success;
8161193326Sed}
8162193326Sed
8163202379Srdivackynamespace {
8164202379Srdivacky
8165202379Srdivackyenum OverloadCandidateKind {
8166202379Srdivacky  oc_function,
8167202379Srdivacky  oc_method,
8168202379Srdivacky  oc_constructor,
8169202379Srdivacky  oc_function_template,
8170202379Srdivacky  oc_method_template,
8171202379Srdivacky  oc_constructor_template,
8172202379Srdivacky  oc_implicit_default_constructor,
8173202379Srdivacky  oc_implicit_copy_constructor,
8174223017Sdim  oc_implicit_move_constructor,
8175218893Sdim  oc_implicit_copy_assignment,
8176223017Sdim  oc_implicit_move_assignment,
8177218893Sdim  oc_implicit_inherited_constructor
8178202379Srdivacky};
8179202379Srdivacky
8180202379SrdivackyOverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8181202379Srdivacky                                                FunctionDecl *Fn,
8182202379Srdivacky                                                std::string &Description) {
8183202379Srdivacky  bool isTemplate = false;
8184202379Srdivacky
8185202379Srdivacky  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8186202379Srdivacky    isTemplate = true;
8187202379Srdivacky    Description = S.getTemplateArgumentBindingsText(
8188202379Srdivacky      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8189202379Srdivacky  }
8190202379Srdivacky
8191202379Srdivacky  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8192202379Srdivacky    if (!Ctor->isImplicit())
8193202379Srdivacky      return isTemplate ? oc_constructor_template : oc_constructor;
8194202379Srdivacky
8195218893Sdim    if (Ctor->getInheritedConstructor())
8196218893Sdim      return oc_implicit_inherited_constructor;
8197218893Sdim
8198223017Sdim    if (Ctor->isDefaultConstructor())
8199223017Sdim      return oc_implicit_default_constructor;
8200223017Sdim
8201223017Sdim    if (Ctor->isMoveConstructor())
8202223017Sdim      return oc_implicit_move_constructor;
8203223017Sdim
8204223017Sdim    assert(Ctor->isCopyConstructor() &&
8205223017Sdim           "unexpected sort of implicit constructor");
8206223017Sdim    return oc_implicit_copy_constructor;
8207202379Srdivacky  }
8208202379Srdivacky
8209202379Srdivacky  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8210202379Srdivacky    // This actually gets spelled 'candidate function' for now, but
8211202379Srdivacky    // it doesn't hurt to split it out.
8212202379Srdivacky    if (!Meth->isImplicit())
8213202379Srdivacky      return isTemplate ? oc_method_template : oc_method;
8214202379Srdivacky
8215223017Sdim    if (Meth->isMoveAssignmentOperator())
8216223017Sdim      return oc_implicit_move_assignment;
8217223017Sdim
8218235633Sdim    if (Meth->isCopyAssignmentOperator())
8219235633Sdim      return oc_implicit_copy_assignment;
8220235633Sdim
8221235633Sdim    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8222235633Sdim    return oc_method;
8223202379Srdivacky  }
8224202379Srdivacky
8225202379Srdivacky  return isTemplate ? oc_function_template : oc_function;
8226202379Srdivacky}
8227202379Srdivacky
8228263509Sdimvoid MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8229218893Sdim  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8230218893Sdim  if (!Ctor) return;
8231218893Sdim
8232218893Sdim  Ctor = Ctor->getInheritedConstructor();
8233218893Sdim  if (!Ctor) return;
8234218893Sdim
8235218893Sdim  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8236218893Sdim}
8237218893Sdim
8238202379Srdivacky} // end anonymous namespace
8239202379Srdivacky
8240202379Srdivacky// Notes the location of an overload candidate.
8241235633Sdimvoid Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8242202379Srdivacky  std::string FnDesc;
8243202379Srdivacky  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8244235633Sdim  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8245235633Sdim                             << (unsigned) K << FnDesc;
8246235633Sdim  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8247235633Sdim  Diag(Fn->getLocation(), PD);
8248218893Sdim  MaybeEmitInheritedConstructorNote(*this, Fn);
8249202379Srdivacky}
8250202379Srdivacky
8251263509Sdim// Notes the location of all overload candidates designated through
8252218893Sdim// OverloadedExpr
8253235633Sdimvoid Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8254218893Sdim  assert(OverloadedExpr->getType() == Context.OverloadTy);
8255218893Sdim
8256218893Sdim  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8257218893Sdim  OverloadExpr *OvlExpr = Ovl.Expression;
8258218893Sdim
8259218893Sdim  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8260218893Sdim                            IEnd = OvlExpr->decls_end();
8261218893Sdim       I != IEnd; ++I) {
8262218893Sdim    if (FunctionTemplateDecl *FunTmpl =
8263218893Sdim                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8264235633Sdim      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8265218893Sdim    } else if (FunctionDecl *Fun
8266218893Sdim                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8267235633Sdim      NoteOverloadCandidate(Fun, DestType);
8268218893Sdim    }
8269218893Sdim  }
8270218893Sdim}
8271218893Sdim
8272202379Srdivacky/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8273202379Srdivacky/// "lead" diagnostic; it will be given two arguments, the source and
8274202379Srdivacky/// target types of the conversion.
8275212904Sdimvoid ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8276212904Sdim                                 Sema &S,
8277212904Sdim                                 SourceLocation CaretLoc,
8278212904Sdim                                 const PartialDiagnostic &PDiag) const {
8279212904Sdim  S.Diag(CaretLoc, PDiag)
8280212904Sdim    << Ambiguous.getFromType() << Ambiguous.getToType();
8281245431Sdim  // FIXME: The note limiting machinery is borrowed from
8282245431Sdim  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8283245431Sdim  // refactoring here.
8284245431Sdim  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8285245431Sdim  unsigned CandsShown = 0;
8286245431Sdim  AmbiguousConversionSequence::const_iterator I, E;
8287245431Sdim  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8288245431Sdim    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8289245431Sdim      break;
8290245431Sdim    ++CandsShown;
8291212904Sdim    S.NoteOverloadCandidate(*I);
8292202379Srdivacky  }
8293245431Sdim  if (I != E)
8294245431Sdim    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8295202379Srdivacky}
8296202379Srdivacky
8297202379Srdivackynamespace {
8298202379Srdivacky
8299202379Srdivackyvoid DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8300202379Srdivacky  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8301202379Srdivacky  assert(Conv.isBad());
8302202379Srdivacky  assert(Cand->Function && "for now, candidate must be a function");
8303202379Srdivacky  FunctionDecl *Fn = Cand->Function;
8304202379Srdivacky
8305202379Srdivacky  // There's a conversion slot for the object argument if this is a
8306202379Srdivacky  // non-constructor method.  Note that 'I' corresponds the
8307202379Srdivacky  // conversion-slot index.
8308202379Srdivacky  bool isObjectArgument = false;
8309202379Srdivacky  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8310202379Srdivacky    if (I == 0)
8311202379Srdivacky      isObjectArgument = true;
8312202379Srdivacky    else
8313202379Srdivacky      I--;
8314202379Srdivacky  }
8315202379Srdivacky
8316202379Srdivacky  std::string FnDesc;
8317202379Srdivacky  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8318202379Srdivacky
8319202379Srdivacky  Expr *FromExpr = Conv.Bad.FromExpr;
8320202379Srdivacky  QualType FromTy = Conv.Bad.getFromType();
8321202379Srdivacky  QualType ToTy = Conv.Bad.getToType();
8322202379Srdivacky
8323203955Srdivacky  if (FromTy == S.Context.OverloadTy) {
8324204643Srdivacky    assert(FromExpr && "overload set argument came from implicit argument?");
8325203955Srdivacky    Expr *E = FromExpr->IgnoreParens();
8326203955Srdivacky    if (isa<UnaryOperator>(E))
8327203955Srdivacky      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8328203955Srdivacky    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8329203955Srdivacky
8330203955Srdivacky    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8331203955Srdivacky      << (unsigned) FnKind << FnDesc
8332203955Srdivacky      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8333203955Srdivacky      << ToTy << Name << I+1;
8334218893Sdim    MaybeEmitInheritedConstructorNote(S, Fn);
8335203955Srdivacky    return;
8336203955Srdivacky  }
8337203955Srdivacky
8338202879Srdivacky  // Do some hand-waving analysis to see if the non-viability is due
8339202879Srdivacky  // to a qualifier mismatch.
8340202379Srdivacky  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8341202379Srdivacky  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8342202379Srdivacky  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8343202379Srdivacky    CToTy = RT->getPointeeType();
8344202379Srdivacky  else {
8345202379Srdivacky    // TODO: detect and diagnose the full richness of const mismatches.
8346202379Srdivacky    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8347202379Srdivacky      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8348202379Srdivacky        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8349202379Srdivacky  }
8350202379Srdivacky
8351202379Srdivacky  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8352202379Srdivacky      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8353202379Srdivacky    Qualifiers FromQs = CFromTy.getQualifiers();
8354202379Srdivacky    Qualifiers ToQs = CToTy.getQualifiers();
8355202379Srdivacky
8356202379Srdivacky    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8357202379Srdivacky      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8358202379Srdivacky        << (unsigned) FnKind << FnDesc
8359202379Srdivacky        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8360202379Srdivacky        << FromTy
8361202379Srdivacky        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8362202379Srdivacky        << (unsigned) isObjectArgument << I+1;
8363218893Sdim      MaybeEmitInheritedConstructorNote(S, Fn);
8364202379Srdivacky      return;
8365202379Srdivacky    }
8366202379Srdivacky
8367224145Sdim    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8368224145Sdim      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8369224145Sdim        << (unsigned) FnKind << FnDesc
8370224145Sdim        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8371224145Sdim        << FromTy
8372224145Sdim        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8373224145Sdim        << (unsigned) isObjectArgument << I+1;
8374224145Sdim      MaybeEmitInheritedConstructorNote(S, Fn);
8375224145Sdim      return;
8376224145Sdim    }
8377224145Sdim
8378221345Sdim    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8379221345Sdim      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8380221345Sdim      << (unsigned) FnKind << FnDesc
8381221345Sdim      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8382221345Sdim      << FromTy
8383221345Sdim      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8384221345Sdim      << (unsigned) isObjectArgument << I+1;
8385221345Sdim      MaybeEmitInheritedConstructorNote(S, Fn);
8386221345Sdim      return;
8387221345Sdim    }
8388221345Sdim
8389202379Srdivacky    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8390202379Srdivacky    assert(CVR && "unexpected qualifiers mismatch");
8391202379Srdivacky
8392202379Srdivacky    if (isObjectArgument) {
8393202379Srdivacky      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8394202379Srdivacky        << (unsigned) FnKind << FnDesc
8395202379Srdivacky        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8396202379Srdivacky        << FromTy << (CVR - 1);
8397202379Srdivacky    } else {
8398202379Srdivacky      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8399202379Srdivacky        << (unsigned) FnKind << FnDesc
8400202379Srdivacky        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8401202379Srdivacky        << FromTy << (CVR - 1) << I+1;
8402202379Srdivacky    }
8403218893Sdim    MaybeEmitInheritedConstructorNote(S, Fn);
8404202379Srdivacky    return;
8405202379Srdivacky  }
8406202379Srdivacky
8407226890Sdim  // Special diagnostic for failure to convert an initializer list, since
8408226890Sdim  // telling the user that it has type void is not useful.
8409226890Sdim  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8410226890Sdim    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8411226890Sdim      << (unsigned) FnKind << FnDesc
8412226890Sdim      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8413226890Sdim      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8414226890Sdim    MaybeEmitInheritedConstructorNote(S, Fn);
8415226890Sdim    return;
8416226890Sdim  }
8417226890Sdim
8418202879Srdivacky  // Diagnose references or pointers to incomplete types differently,
8419202879Srdivacky  // since it's far from impossible that the incompleteness triggered
8420202879Srdivacky  // the failure.
8421202879Srdivacky  QualType TempFromTy = FromTy.getNonReferenceType();
8422202879Srdivacky  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8423202879Srdivacky    TempFromTy = PTy->getPointeeType();
8424202879Srdivacky  if (TempFromTy->isIncompleteType()) {
8425202879Srdivacky    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8426202879Srdivacky      << (unsigned) FnKind << FnDesc
8427202879Srdivacky      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8428202879Srdivacky      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8429218893Sdim    MaybeEmitInheritedConstructorNote(S, Fn);
8430202879Srdivacky    return;
8431202879Srdivacky  }
8432202879Srdivacky
8433210299Sed  // Diagnose base -> derived pointer conversions.
8434210299Sed  unsigned BaseToDerivedConversion = 0;
8435210299Sed  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8436210299Sed    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8437210299Sed      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8438210299Sed                                               FromPtrTy->getPointeeType()) &&
8439210299Sed          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8440210299Sed          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8441218893Sdim          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8442210299Sed                          FromPtrTy->getPointeeType()))
8443210299Sed        BaseToDerivedConversion = 1;
8444210299Sed    }
8445210299Sed  } else if (const ObjCObjectPointerType *FromPtrTy
8446210299Sed                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8447210299Sed    if (const ObjCObjectPointerType *ToPtrTy
8448210299Sed                                        = ToTy->getAs<ObjCObjectPointerType>())
8449210299Sed      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8450210299Sed        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8451210299Sed          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8452210299Sed                                                FromPtrTy->getPointeeType()) &&
8453210299Sed              FromIface->isSuperClassOf(ToIface))
8454210299Sed            BaseToDerivedConversion = 2;
8455210299Sed  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8456245431Sdim    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8457245431Sdim        !FromTy->isIncompleteType() &&
8458245431Sdim        !ToRefTy->getPointeeType()->isIncompleteType() &&
8459245431Sdim        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8460245431Sdim      BaseToDerivedConversion = 3;
8461245431Sdim    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8462245431Sdim               ToTy.getNonReferenceType().getCanonicalType() ==
8463245431Sdim               FromTy.getNonReferenceType().getCanonicalType()) {
8464245431Sdim      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8465245431Sdim        << (unsigned) FnKind << FnDesc
8466245431Sdim        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8467245431Sdim        << (unsigned) isObjectArgument << I + 1;
8468245431Sdim      MaybeEmitInheritedConstructorNote(S, Fn);
8469245431Sdim      return;
8470210299Sed    }
8471245431Sdim  }
8472218893Sdim
8473210299Sed  if (BaseToDerivedConversion) {
8474218893Sdim    S.Diag(Fn->getLocation(),
8475210299Sed           diag::note_ovl_candidate_bad_base_to_derived_conv)
8476210299Sed      << (unsigned) FnKind << FnDesc
8477210299Sed      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8478210299Sed      << (BaseToDerivedConversion - 1)
8479218893Sdim      << FromTy << ToTy << I+1;
8480218893Sdim    MaybeEmitInheritedConstructorNote(S, Fn);
8481210299Sed    return;
8482210299Sed  }
8483218893Sdim
8484226890Sdim  if (isa<ObjCObjectPointerType>(CFromTy) &&
8485226890Sdim      isa<PointerType>(CToTy)) {
8486226890Sdim      Qualifiers FromQs = CFromTy.getQualifiers();
8487226890Sdim      Qualifiers ToQs = CToTy.getQualifiers();
8488226890Sdim      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8489226890Sdim        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8490226890Sdim        << (unsigned) FnKind << FnDesc
8491226890Sdim        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8492226890Sdim        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8493226890Sdim        MaybeEmitInheritedConstructorNote(S, Fn);
8494226890Sdim        return;
8495226890Sdim      }
8496226890Sdim  }
8497226890Sdim
8498226890Sdim  // Emit the generic diagnostic and, optionally, add the hints to it.
8499226890Sdim  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8500226890Sdim  FDiag << (unsigned) FnKind << FnDesc
8501202379Srdivacky    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8502226890Sdim    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8503226890Sdim    << (unsigned) (Cand->Fix.Kind);
8504226890Sdim
8505226890Sdim  // If we can fix the conversion, suggest the FixIts.
8506235633Sdim  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8507235633Sdim       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8508226890Sdim    FDiag << *HI;
8509226890Sdim  S.Diag(Fn->getLocation(), FDiag);
8510226890Sdim
8511218893Sdim  MaybeEmitInheritedConstructorNote(S, Fn);
8512202379Srdivacky}
8513202379Srdivacky
8514263509Sdim/// Additional arity mismatch diagnosis specific to a function overload
8515263509Sdim/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8516263509Sdim/// over a candidate in any candidate set.
8517263509Sdimbool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8518263509Sdim                        unsigned NumArgs) {
8519202379Srdivacky  FunctionDecl *Fn = Cand->Function;
8520202379Srdivacky  unsigned MinParams = Fn->getMinRequiredArguments();
8521218893Sdim
8522223017Sdim  // With invalid overloaded operators, it's possible that we think we
8523263509Sdim  // have an arity mismatch when in fact it looks like we have the
8524223017Sdim  // right number of arguments, because only overloaded operators have
8525223017Sdim  // the weird behavior of overloading member and non-member functions.
8526223017Sdim  // Just don't report anything.
8527223017Sdim  if (Fn->isInvalidDecl() &&
8528223017Sdim      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8529263509Sdim    return true;
8530223017Sdim
8531263509Sdim  if (NumArgs < MinParams) {
8532263509Sdim    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8533263509Sdim           (Cand->FailureKind == ovl_fail_bad_deduction &&
8534263509Sdim            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8535263509Sdim  } else {
8536263509Sdim    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8537263509Sdim           (Cand->FailureKind == ovl_fail_bad_deduction &&
8538263509Sdim            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8539263509Sdim  }
8540263509Sdim
8541263509Sdim  return false;
8542263509Sdim}
8543263509Sdim
8544263509Sdim/// General arity mismatch diagnosis over a candidate in a candidate set.
8545263509Sdimvoid DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8546263509Sdim  assert(isa<FunctionDecl>(D) &&
8547263509Sdim      "The templated declaration should at least be a function"
8548263509Sdim      " when diagnosing bad template argument deduction due to too many"
8549263509Sdim      " or too few arguments");
8550263509Sdim
8551263509Sdim  FunctionDecl *Fn = cast<FunctionDecl>(D);
8552263509Sdim
8553263509Sdim  // TODO: treat calls to a missing default constructor as a special case
8554263509Sdim  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8555263509Sdim  unsigned MinParams = Fn->getMinRequiredArguments();
8556263509Sdim
8557202379Srdivacky  // at least / at most / exactly
8558202379Srdivacky  unsigned mode, modeCount;
8559202379Srdivacky  if (NumFormalArgs < MinParams) {
8560218893Sdim    if (MinParams != FnTy->getNumArgs() ||
8561218893Sdim        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8562202379Srdivacky      mode = 0; // "at least"
8563202379Srdivacky    else
8564202379Srdivacky      mode = 2; // "exactly"
8565202379Srdivacky    modeCount = MinParams;
8566202379Srdivacky  } else {
8567202379Srdivacky    if (MinParams != FnTy->getNumArgs())
8568202379Srdivacky      mode = 1; // "at most"
8569202379Srdivacky    else
8570202379Srdivacky      mode = 2; // "exactly"
8571202379Srdivacky    modeCount = FnTy->getNumArgs();
8572202379Srdivacky  }
8573202379Srdivacky
8574202379Srdivacky  std::string Description;
8575202379Srdivacky  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8576202379Srdivacky
8577245431Sdim  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8578245431Sdim    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8579245431Sdim      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8580245431Sdim      << Fn->getParamDecl(0) << NumFormalArgs;
8581245431Sdim  else
8582245431Sdim    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8583245431Sdim      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8584245431Sdim      << modeCount << NumFormalArgs;
8585218893Sdim  MaybeEmitInheritedConstructorNote(S, Fn);
8586202379Srdivacky}
8587202379Srdivacky
8588263509Sdim/// Arity mismatch diagnosis specific to a function overload candidate.
8589263509Sdimvoid DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8590263509Sdim                           unsigned NumFormalArgs) {
8591263509Sdim  if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8592263509Sdim    DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8593263509Sdim}
8594263509Sdim
8595263509SdimTemplateDecl *getDescribedTemplate(Decl *Templated) {
8596263509Sdim  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8597263509Sdim    return FD->getDescribedFunctionTemplate();
8598263509Sdim  else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8599263509Sdim    return RD->getDescribedClassTemplate();
8600263509Sdim
8601263509Sdim  llvm_unreachable("Unsupported: Getting the described template declaration"
8602263509Sdim                   " for bad deduction diagnosis");
8603263509Sdim}
8604263509Sdim
8605203955Srdivacky/// Diagnose a failed template-argument deduction.
8606263509Sdimvoid DiagnoseBadDeduction(Sema &S, Decl *Templated,
8607263509Sdim                          DeductionFailureInfo &DeductionFailure,
8608235633Sdim                          unsigned NumArgs) {
8609263509Sdim  TemplateParameter Param = DeductionFailure.getTemplateParameter();
8610208600Srdivacky  NamedDecl *ParamD;
8611208600Srdivacky  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8612208600Srdivacky  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8613208600Srdivacky  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8614263509Sdim  switch (DeductionFailure.Result) {
8615203955Srdivacky  case Sema::TDK_Success:
8616203955Srdivacky    llvm_unreachable("TDK_success while diagnosing bad deduction");
8617203955Srdivacky
8618203955Srdivacky  case Sema::TDK_Incomplete: {
8619203955Srdivacky    assert(ParamD && "no parameter found for incomplete deduction result");
8620263509Sdim    S.Diag(Templated->getLocation(),
8621263509Sdim           diag::note_ovl_candidate_incomplete_deduction)
8622263509Sdim        << ParamD->getDeclName();
8623263509Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8624203955Srdivacky    return;
8625203955Srdivacky  }
8626203955Srdivacky
8627212904Sdim  case Sema::TDK_Underqualified: {
8628212904Sdim    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8629212904Sdim    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8630212904Sdim
8631263509Sdim    QualType Param = DeductionFailure.getFirstArg()->getAsType();
8632212904Sdim
8633212904Sdim    // Param will have been canonicalized, but it should just be a
8634212904Sdim    // qualified version of ParamD, so move the qualifiers to that.
8635218893Sdim    QualifierCollector Qs;
8636212904Sdim    Qs.strip(Param);
8637218893Sdim    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8638212904Sdim    assert(S.Context.hasSameType(Param, NonCanonParam));
8639212904Sdim
8640212904Sdim    // Arg has also been canonicalized, but there's nothing we can do
8641212904Sdim    // about that.  It also doesn't matter as much, because it won't
8642212904Sdim    // have any template parameters in it (because deduction isn't
8643212904Sdim    // done on dependent types).
8644263509Sdim    QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8645212904Sdim
8646263509Sdim    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8647263509Sdim        << ParamD->getDeclName() << Arg << NonCanonParam;
8648263509Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8649212904Sdim    return;
8650212904Sdim  }
8651212904Sdim
8652212904Sdim  case Sema::TDK_Inconsistent: {
8653218893Sdim    assert(ParamD && "no parameter found for inconsistent deduction result");
8654208600Srdivacky    int which = 0;
8655208600Srdivacky    if (isa<TemplateTypeParmDecl>(ParamD))
8656208600Srdivacky      which = 0;
8657208600Srdivacky    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8658208600Srdivacky      which = 1;
8659208600Srdivacky    else {
8660208600Srdivacky      which = 2;
8661208600Srdivacky    }
8662218893Sdim
8663263509Sdim    S.Diag(Templated->getLocation(),
8664263509Sdim           diag::note_ovl_candidate_inconsistent_deduction)
8665263509Sdim        << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8666263509Sdim        << *DeductionFailure.getSecondArg();
8667263509Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8668208600Srdivacky    return;
8669208600Srdivacky  }
8670208600Srdivacky
8671208600Srdivacky  case Sema::TDK_InvalidExplicitArguments:
8672218893Sdim    assert(ParamD && "no parameter found for invalid explicit arguments");
8673208600Srdivacky    if (ParamD->getDeclName())
8674263509Sdim      S.Diag(Templated->getLocation(),
8675208600Srdivacky             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8676263509Sdim          << ParamD->getDeclName();
8677208600Srdivacky    else {
8678208600Srdivacky      int index = 0;
8679208600Srdivacky      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8680208600Srdivacky        index = TTP->getIndex();
8681208600Srdivacky      else if (NonTypeTemplateParmDecl *NTTP
8682208600Srdivacky                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8683208600Srdivacky        index = NTTP->getIndex();
8684208600Srdivacky      else
8685208600Srdivacky        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8686263509Sdim      S.Diag(Templated->getLocation(),
8687208600Srdivacky             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8688263509Sdim          << (index + 1);
8689208600Srdivacky    }
8690263509Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8691208600Srdivacky    return;
8692218893Sdim
8693208600Srdivacky  case Sema::TDK_TooManyArguments:
8694208600Srdivacky  case Sema::TDK_TooFewArguments:
8695263509Sdim    DiagnoseArityMismatch(S, Templated, NumArgs);
8696208600Srdivacky    return;
8697208600Srdivacky
8698208600Srdivacky  case Sema::TDK_InstantiationDepth:
8699263509Sdim    S.Diag(Templated->getLocation(),
8700263509Sdim           diag::note_ovl_candidate_instantiation_depth);
8701263509Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8702208600Srdivacky    return;
8703208600Srdivacky
8704208600Srdivacky  case Sema::TDK_SubstitutionFailure: {
8705245431Sdim    // Format the template argument list into the argument string.
8706252723Sdim    SmallString<128> TemplateArgString;
8707245431Sdim    if (TemplateArgumentList *Args =
8708263509Sdim            DeductionFailure.getTemplateArgumentList()) {
8709245431Sdim      TemplateArgString = " ";
8710245431Sdim      TemplateArgString += S.getTemplateArgumentBindingsText(
8711263509Sdim          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8712245431Sdim    }
8713245431Sdim
8714245431Sdim    // If this candidate was disabled by enable_if, say so.
8715263509Sdim    PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8716245431Sdim    if (PDiag && PDiag->second.getDiagID() ==
8717245431Sdim          diag::err_typename_nested_not_found_enable_if) {
8718245431Sdim      // FIXME: Use the source range of the condition, and the fully-qualified
8719245431Sdim      //        name of the enable_if template. These are both present in PDiag.
8720245431Sdim      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8721245431Sdim        << "'enable_if'" << TemplateArgString;
8722245431Sdim      return;
8723245431Sdim    }
8724245431Sdim
8725245431Sdim    // Format the SFINAE diagnostic into the argument string.
8726245431Sdim    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8727245431Sdim    //        formatted message in another diagnostic.
8728252723Sdim    SmallString<128> SFINAEArgString;
8729245431Sdim    SourceRange R;
8730245431Sdim    if (PDiag) {
8731245431Sdim      SFINAEArgString = ": ";
8732245431Sdim      R = SourceRange(PDiag->first, PDiag->first);
8733245431Sdim      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8734245431Sdim    }
8735245431Sdim
8736263509Sdim    S.Diag(Templated->getLocation(),
8737263509Sdim           diag::note_ovl_candidate_substitution_failure)
8738263509Sdim        << TemplateArgString << SFINAEArgString << R;
8739263509Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8740208600Srdivacky    return;
8741208600Srdivacky  }
8742218893Sdim
8743252723Sdim  case Sema::TDK_FailedOverloadResolution: {
8744263509Sdim    OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8745263509Sdim    S.Diag(Templated->getLocation(),
8746252723Sdim           diag::note_ovl_candidate_failed_overload_resolution)
8747263509Sdim        << R.Expression->getName();
8748252723Sdim    return;
8749252723Sdim  }
8750252723Sdim
8751252723Sdim  case Sema::TDK_NonDeducedMismatch: {
8752252723Sdim    // FIXME: Provide a source location to indicate what we couldn't match.
8753263509Sdim    TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8754263509Sdim    TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8755252723Sdim    if (FirstTA.getKind() == TemplateArgument::Template &&
8756252723Sdim        SecondTA.getKind() == TemplateArgument::Template) {
8757252723Sdim      TemplateName FirstTN = FirstTA.getAsTemplate();
8758252723Sdim      TemplateName SecondTN = SecondTA.getAsTemplate();
8759252723Sdim      if (FirstTN.getKind() == TemplateName::Template &&
8760252723Sdim          SecondTN.getKind() == TemplateName::Template) {
8761252723Sdim        if (FirstTN.getAsTemplateDecl()->getName() ==
8762252723Sdim            SecondTN.getAsTemplateDecl()->getName()) {
8763252723Sdim          // FIXME: This fixes a bad diagnostic where both templates are named
8764252723Sdim          // the same.  This particular case is a bit difficult since:
8765252723Sdim          // 1) It is passed as a string to the diagnostic printer.
8766252723Sdim          // 2) The diagnostic printer only attempts to find a better
8767252723Sdim          //    name for types, not decls.
8768252723Sdim          // Ideally, this should folded into the diagnostic printer.
8769263509Sdim          S.Diag(Templated->getLocation(),
8770252723Sdim                 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8771252723Sdim              << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8772252723Sdim          return;
8773252723Sdim        }
8774252723Sdim      }
8775252723Sdim    }
8776263509Sdim    // FIXME: For generic lambda parameters, check if the function is a lambda
8777263509Sdim    // call operator, and if so, emit a prettier and more informative
8778263509Sdim    // diagnostic that mentions 'auto' and lambda in addition to
8779263509Sdim    // (or instead of?) the canonical template type parameters.
8780263509Sdim    S.Diag(Templated->getLocation(),
8781263509Sdim           diag::note_ovl_candidate_non_deduced_mismatch)
8782263509Sdim        << FirstTA << SecondTA;
8783252723Sdim    return;
8784252723Sdim  }
8785203955Srdivacky  // TODO: diagnose these individually, then kill off
8786203955Srdivacky  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8787252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
8788263509Sdim    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8789263509Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8790203955Srdivacky    return;
8791203955Srdivacky  }
8792203955Srdivacky}
8793203955Srdivacky
8794263509Sdim/// Diagnose a failed template-argument deduction, for function calls.
8795263509Sdimvoid DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8796263509Sdim  unsigned TDK = Cand->DeductionFailure.Result;
8797263509Sdim  if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8798263509Sdim    if (CheckArityMismatch(S, Cand, NumArgs))
8799263509Sdim      return;
8800263509Sdim  }
8801263509Sdim  DiagnoseBadDeduction(S, Cand->Function, // pattern
8802263509Sdim                       Cand->DeductionFailure, NumArgs);
8803263509Sdim}
8804263509Sdim
8805226890Sdim/// CUDA: diagnose an invalid call across targets.
8806226890Sdimvoid DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8807226890Sdim  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8808226890Sdim  FunctionDecl *Callee = Cand->Function;
8809226890Sdim
8810226890Sdim  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8811226890Sdim                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8812226890Sdim
8813226890Sdim  std::string FnDesc;
8814226890Sdim  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8815226890Sdim
8816226890Sdim  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8817226890Sdim      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8818226890Sdim}
8819226890Sdim
8820203955Srdivacky/// Generates a 'note' diagnostic for an overload candidate.  We've
8821203955Srdivacky/// already generated a primary error at the call site.
8822203955Srdivacky///
8823203955Srdivacky/// It really does need to be a single diagnostic with its caret
8824203955Srdivacky/// pointed at the candidate declaration.  Yes, this creates some
8825203955Srdivacky/// major challenges of technical writing.  Yes, this makes pointing
8826203955Srdivacky/// out problems with specific arguments quite awkward.  It's still
8827203955Srdivacky/// better than generating twenty screens of text for every failed
8828203955Srdivacky/// overload.
8829203955Srdivacky///
8830203955Srdivacky/// It would be great to be able to express per-candidate problems
8831203955Srdivacky/// more richly for those diagnostic clients that cared, but we'd
8832203955Srdivacky/// still have to be just as careful with the default diagnostics.
8833202379Srdivackyvoid NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8834235633Sdim                           unsigned NumArgs) {
8835202379Srdivacky  FunctionDecl *Fn = Cand->Function;
8836202379Srdivacky
8837202379Srdivacky  // Note deleted candidates, but only if they're viable.
8838224145Sdim  if (Cand->Viable && (Fn->isDeleted() ||
8839224145Sdim      S.isFunctionConsideredUnavailable(Fn))) {
8840202379Srdivacky    std::string FnDesc;
8841202379Srdivacky    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8842202379Srdivacky
8843202379Srdivacky    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8844235633Sdim      << FnKind << FnDesc
8845235633Sdim      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8846218893Sdim    MaybeEmitInheritedConstructorNote(S, Fn);
8847202379Srdivacky    return;
8848202379Srdivacky  }
8849202379Srdivacky
8850202379Srdivacky  // We don't really have anything else to say about viable candidates.
8851202379Srdivacky  if (Cand->Viable) {
8852202379Srdivacky    S.NoteOverloadCandidate(Fn);
8853202379Srdivacky    return;
8854202379Srdivacky  }
8855202379Srdivacky
8856202379Srdivacky  switch (Cand->FailureKind) {
8857202379Srdivacky  case ovl_fail_too_many_arguments:
8858202379Srdivacky  case ovl_fail_too_few_arguments:
8859202379Srdivacky    return DiagnoseArityMismatch(S, Cand, NumArgs);
8860202379Srdivacky
8861202379Srdivacky  case ovl_fail_bad_deduction:
8862235633Sdim    return DiagnoseBadDeduction(S, Cand, NumArgs);
8863203955Srdivacky
8864202879Srdivacky  case ovl_fail_trivial_conversion:
8865202879Srdivacky  case ovl_fail_bad_final_conversion:
8866207619Srdivacky  case ovl_fail_final_conversion_not_exact:
8867202379Srdivacky    return S.NoteOverloadCandidate(Fn);
8868202379Srdivacky
8869204643Srdivacky  case ovl_fail_bad_conversion: {
8870204643Srdivacky    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8871235633Sdim    for (unsigned N = Cand->NumConversions; I != N; ++I)
8872202379Srdivacky      if (Cand->Conversions[I].isBad())
8873202379Srdivacky        return DiagnoseBadConversion(S, Cand, I);
8874218893Sdim
8875202379Srdivacky    // FIXME: this currently happens when we're called from SemaInit
8876202379Srdivacky    // when user-conversion overload fails.  Figure out how to handle
8877202379Srdivacky    // those conditions and diagnose them well.
8878202379Srdivacky    return S.NoteOverloadCandidate(Fn);
8879202379Srdivacky  }
8880226890Sdim
8881226890Sdim  case ovl_fail_bad_target:
8882226890Sdim    return DiagnoseBadTarget(S, Cand);
8883204643Srdivacky  }
8884202379Srdivacky}
8885202379Srdivacky
8886202379Srdivackyvoid NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8887202379Srdivacky  // Desugar the type of the surrogate down to a function type,
8888202379Srdivacky  // retaining as many typedefs as possible while still showing
8889202379Srdivacky  // the function type (and, therefore, its parameter types).
8890202379Srdivacky  QualType FnType = Cand->Surrogate->getConversionType();
8891202379Srdivacky  bool isLValueReference = false;
8892202379Srdivacky  bool isRValueReference = false;
8893202379Srdivacky  bool isPointer = false;
8894202379Srdivacky  if (const LValueReferenceType *FnTypeRef =
8895202379Srdivacky        FnType->getAs<LValueReferenceType>()) {
8896202379Srdivacky    FnType = FnTypeRef->getPointeeType();
8897202379Srdivacky    isLValueReference = true;
8898202379Srdivacky  } else if (const RValueReferenceType *FnTypeRef =
8899202379Srdivacky               FnType->getAs<RValueReferenceType>()) {
8900202379Srdivacky    FnType = FnTypeRef->getPointeeType();
8901202379Srdivacky    isRValueReference = true;
8902202379Srdivacky  }
8903202379Srdivacky  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8904202379Srdivacky    FnType = FnTypePtr->getPointeeType();
8905202379Srdivacky    isPointer = true;
8906202379Srdivacky  }
8907202379Srdivacky  // Desugar down to a function type.
8908202379Srdivacky  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8909202379Srdivacky  // Reconstruct the pointer/reference as appropriate.
8910202379Srdivacky  if (isPointer) FnType = S.Context.getPointerType(FnType);
8911202379Srdivacky  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8912202379Srdivacky  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8913202379Srdivacky
8914202379Srdivacky  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8915202379Srdivacky    << FnType;
8916218893Sdim  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8917202379Srdivacky}
8918202379Srdivacky
8919202379Srdivackyvoid NoteBuiltinOperatorCandidate(Sema &S,
8920245431Sdim                                  StringRef Opc,
8921202379Srdivacky                                  SourceLocation OpLoc,
8922202379Srdivacky                                  OverloadCandidate *Cand) {
8923235633Sdim  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8924202379Srdivacky  std::string TypeStr("operator");
8925202379Srdivacky  TypeStr += Opc;
8926202379Srdivacky  TypeStr += "(";
8927202379Srdivacky  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8928235633Sdim  if (Cand->NumConversions == 1) {
8929202379Srdivacky    TypeStr += ")";
8930202379Srdivacky    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8931202379Srdivacky  } else {
8932202379Srdivacky    TypeStr += ", ";
8933202379Srdivacky    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8934202379Srdivacky    TypeStr += ")";
8935202379Srdivacky    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8936202379Srdivacky  }
8937202379Srdivacky}
8938202379Srdivacky
8939202379Srdivackyvoid NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8940202379Srdivacky                                  OverloadCandidate *Cand) {
8941235633Sdim  unsigned NoOperands = Cand->NumConversions;
8942202379Srdivacky  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8943202379Srdivacky    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8944202379Srdivacky    if (ICS.isBad()) break; // all meaningless after first invalid
8945202379Srdivacky    if (!ICS.isAmbiguous()) continue;
8946202379Srdivacky
8947212904Sdim    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8948206084Srdivacky                              S.PDiag(diag::note_ambiguous_type_conversion));
8949202379Srdivacky  }
8950202379Srdivacky}
8951202379Srdivacky
8952263509Sdimstatic SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8953202879Srdivacky  if (Cand->Function)
8954202879Srdivacky    return Cand->Function->getLocation();
8955202879Srdivacky  if (Cand->IsSurrogate)
8956202879Srdivacky    return Cand->Surrogate->getLocation();
8957202879Srdivacky  return SourceLocation();
8958202879Srdivacky}
8959202879Srdivacky
8960263509Sdimstatic unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
8961226890Sdim  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8962226890Sdim  case Sema::TDK_Success:
8963226890Sdim    llvm_unreachable("TDK_success while diagnosing bad deduction");
8964226890Sdim
8965245431Sdim  case Sema::TDK_Invalid:
8966226890Sdim  case Sema::TDK_Incomplete:
8967226890Sdim    return 1;
8968226890Sdim
8969226890Sdim  case Sema::TDK_Underqualified:
8970226890Sdim  case Sema::TDK_Inconsistent:
8971226890Sdim    return 2;
8972226890Sdim
8973226890Sdim  case Sema::TDK_SubstitutionFailure:
8974226890Sdim  case Sema::TDK_NonDeducedMismatch:
8975252723Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
8976226890Sdim    return 3;
8977226890Sdim
8978226890Sdim  case Sema::TDK_InstantiationDepth:
8979226890Sdim  case Sema::TDK_FailedOverloadResolution:
8980226890Sdim    return 4;
8981226890Sdim
8982226890Sdim  case Sema::TDK_InvalidExplicitArguments:
8983226890Sdim    return 5;
8984226890Sdim
8985226890Sdim  case Sema::TDK_TooManyArguments:
8986226890Sdim  case Sema::TDK_TooFewArguments:
8987226890Sdim    return 6;
8988226890Sdim  }
8989226890Sdim  llvm_unreachable("Unhandled deduction result");
8990226890Sdim}
8991226890Sdim
8992202379Srdivackystruct CompareOverloadCandidatesForDisplay {
8993202379Srdivacky  Sema &S;
8994202379Srdivacky  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8995202379Srdivacky
8996202379Srdivacky  bool operator()(const OverloadCandidate *L,
8997202379Srdivacky                  const OverloadCandidate *R) {
8998202879Srdivacky    // Fast-path this check.
8999202879Srdivacky    if (L == R) return false;
9000202879Srdivacky
9001202379Srdivacky    // Order first by viability.
9002202379Srdivacky    if (L->Viable) {
9003202379Srdivacky      if (!R->Viable) return true;
9004202379Srdivacky
9005202379Srdivacky      // TODO: introduce a tri-valued comparison for overload
9006202379Srdivacky      // candidates.  Would be more worthwhile if we had a sort
9007202379Srdivacky      // that could exploit it.
9008212904Sdim      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9009212904Sdim      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9010202379Srdivacky    } else if (R->Viable)
9011202379Srdivacky      return false;
9012202379Srdivacky
9013202879Srdivacky    assert(L->Viable == R->Viable);
9014202379Srdivacky
9015202879Srdivacky    // Criteria by which we can sort non-viable candidates:
9016202879Srdivacky    if (!L->Viable) {
9017202879Srdivacky      // 1. Arity mismatches come after other candidates.
9018202879Srdivacky      if (L->FailureKind == ovl_fail_too_many_arguments ||
9019202879Srdivacky          L->FailureKind == ovl_fail_too_few_arguments)
9020202879Srdivacky        return false;
9021202879Srdivacky      if (R->FailureKind == ovl_fail_too_many_arguments ||
9022202879Srdivacky          R->FailureKind == ovl_fail_too_few_arguments)
9023202879Srdivacky        return true;
9024202379Srdivacky
9025202879Srdivacky      // 2. Bad conversions come first and are ordered by the number
9026202879Srdivacky      // of bad conversions and quality of good conversions.
9027202879Srdivacky      if (L->FailureKind == ovl_fail_bad_conversion) {
9028202879Srdivacky        if (R->FailureKind != ovl_fail_bad_conversion)
9029202879Srdivacky          return true;
9030202879Srdivacky
9031226890Sdim        // The conversion that can be fixed with a smaller number of changes,
9032226890Sdim        // comes first.
9033226890Sdim        unsigned numLFixes = L->Fix.NumConversionsFixed;
9034226890Sdim        unsigned numRFixes = R->Fix.NumConversionsFixed;
9035226890Sdim        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9036226890Sdim        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9037226890Sdim        if (numLFixes != numRFixes) {
9038226890Sdim          if (numLFixes < numRFixes)
9039226890Sdim            return true;
9040226890Sdim          else
9041226890Sdim            return false;
9042226890Sdim        }
9043226890Sdim
9044202879Srdivacky        // If there's any ordering between the defined conversions...
9045202879Srdivacky        // FIXME: this might not be transitive.
9046235633Sdim        assert(L->NumConversions == R->NumConversions);
9047202879Srdivacky
9048202879Srdivacky        int leftBetter = 0;
9049204643Srdivacky        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9050235633Sdim        for (unsigned E = L->NumConversions; I != E; ++I) {
9051212904Sdim          switch (CompareImplicitConversionSequences(S,
9052212904Sdim                                                     L->Conversions[I],
9053212904Sdim                                                     R->Conversions[I])) {
9054202879Srdivacky          case ImplicitConversionSequence::Better:
9055202879Srdivacky            leftBetter++;
9056202879Srdivacky            break;
9057202879Srdivacky
9058202879Srdivacky          case ImplicitConversionSequence::Worse:
9059202879Srdivacky            leftBetter--;
9060202879Srdivacky            break;
9061202879Srdivacky
9062202879Srdivacky          case ImplicitConversionSequence::Indistinguishable:
9063202879Srdivacky            break;
9064202879Srdivacky          }
9065202879Srdivacky        }
9066202879Srdivacky        if (leftBetter > 0) return true;
9067202879Srdivacky        if (leftBetter < 0) return false;
9068202879Srdivacky
9069202879Srdivacky      } else if (R->FailureKind == ovl_fail_bad_conversion)
9070202879Srdivacky        return false;
9071202879Srdivacky
9072226890Sdim      if (L->FailureKind == ovl_fail_bad_deduction) {
9073226890Sdim        if (R->FailureKind != ovl_fail_bad_deduction)
9074226890Sdim          return true;
9075226890Sdim
9076226890Sdim        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9077226890Sdim          return RankDeductionFailure(L->DeductionFailure)
9078226890Sdim               < RankDeductionFailure(R->DeductionFailure);
9079226890Sdim      } else if (R->FailureKind == ovl_fail_bad_deduction)
9080226890Sdim        return false;
9081226890Sdim
9082202879Srdivacky      // TODO: others?
9083202879Srdivacky    }
9084202879Srdivacky
9085202879Srdivacky    // Sort everything else by location.
9086202879Srdivacky    SourceLocation LLoc = GetLocationForCandidate(L);
9087202879Srdivacky    SourceLocation RLoc = GetLocationForCandidate(R);
9088202879Srdivacky
9089202879Srdivacky    // Put candidates without locations (e.g. builtins) at the end.
9090202879Srdivacky    if (LLoc.isInvalid()) return false;
9091202879Srdivacky    if (RLoc.isInvalid()) return true;
9092202879Srdivacky
9093202879Srdivacky    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9094202379Srdivacky  }
9095202379Srdivacky};
9096202379Srdivacky
9097202879Srdivacky/// CompleteNonViableCandidate - Normally, overload resolution only
9098226890Sdim/// computes up to the first. Produces the FixIt set if possible.
9099202879Srdivackyvoid CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9100252723Sdim                                ArrayRef<Expr *> Args) {
9101202879Srdivacky  assert(!Cand->Viable);
9102202879Srdivacky
9103202879Srdivacky  // Don't do anything on failures other than bad conversion.
9104202879Srdivacky  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9105202879Srdivacky
9106226890Sdim  // We only want the FixIts if all the arguments can be corrected.
9107226890Sdim  bool Unfixable = false;
9108226890Sdim  // Use a implicit copy initialization to check conversion fixes.
9109226890Sdim  Cand->Fix.setConversionChecker(TryCopyInitialization);
9110226890Sdim
9111202879Srdivacky  // Skip forward to the first bad conversion.
9112204643Srdivacky  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9113235633Sdim  unsigned ConvCount = Cand->NumConversions;
9114202879Srdivacky  while (true) {
9115202879Srdivacky    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9116202879Srdivacky    ConvIdx++;
9117226890Sdim    if (Cand->Conversions[ConvIdx - 1].isBad()) {
9118226890Sdim      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9119202879Srdivacky      break;
9120226890Sdim    }
9121202879Srdivacky  }
9122202879Srdivacky
9123202879Srdivacky  if (ConvIdx == ConvCount)
9124202879Srdivacky    return;
9125202879Srdivacky
9126204643Srdivacky  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9127204643Srdivacky         "remaining conversion is initialized?");
9128204643Srdivacky
9129207619Srdivacky  // FIXME: this should probably be preserved from the overload
9130202879Srdivacky  // operation somehow.
9131202879Srdivacky  bool SuppressUserConversions = false;
9132202879Srdivacky
9133202879Srdivacky  const FunctionProtoType* Proto;
9134202879Srdivacky  unsigned ArgIdx = ConvIdx;
9135202879Srdivacky
9136202879Srdivacky  if (Cand->IsSurrogate) {
9137202879Srdivacky    QualType ConvType
9138202879Srdivacky      = Cand->Surrogate->getConversionType().getNonReferenceType();
9139202879Srdivacky    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9140202879Srdivacky      ConvType = ConvPtrType->getPointeeType();
9141202879Srdivacky    Proto = ConvType->getAs<FunctionProtoType>();
9142202879Srdivacky    ArgIdx--;
9143202879Srdivacky  } else if (Cand->Function) {
9144202879Srdivacky    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9145202879Srdivacky    if (isa<CXXMethodDecl>(Cand->Function) &&
9146202879Srdivacky        !isa<CXXConstructorDecl>(Cand->Function))
9147202879Srdivacky      ArgIdx--;
9148202879Srdivacky  } else {
9149202879Srdivacky    // Builtin binary operator with a bad first conversion.
9150202879Srdivacky    assert(ConvCount <= 3);
9151202879Srdivacky    for (; ConvIdx != ConvCount; ++ConvIdx)
9152202879Srdivacky      Cand->Conversions[ConvIdx]
9153207619Srdivacky        = TryCopyInitialization(S, Args[ConvIdx],
9154207619Srdivacky                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
9155218893Sdim                                SuppressUserConversions,
9156224145Sdim                                /*InOverloadResolution*/ true,
9157224145Sdim                                /*AllowObjCWritebackConversion=*/
9158235633Sdim                                  S.getLangOpts().ObjCAutoRefCount);
9159202879Srdivacky    return;
9160202879Srdivacky  }
9161202879Srdivacky
9162202879Srdivacky  // Fill in the rest of the conversions.
9163202879Srdivacky  unsigned NumArgsInProto = Proto->getNumArgs();
9164202879Srdivacky  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9165226890Sdim    if (ArgIdx < NumArgsInProto) {
9166202879Srdivacky      Cand->Conversions[ConvIdx]
9167207619Srdivacky        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
9168218893Sdim                                SuppressUserConversions,
9169224145Sdim                                /*InOverloadResolution=*/true,
9170224145Sdim                                /*AllowObjCWritebackConversion=*/
9171235633Sdim                                  S.getLangOpts().ObjCAutoRefCount);
9172226890Sdim      // Store the FixIt in the candidate if it exists.
9173226890Sdim      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9174226890Sdim        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9175226890Sdim    }
9176202879Srdivacky    else
9177202879Srdivacky      Cand->Conversions[ConvIdx].setEllipsis();
9178202879Srdivacky  }
9179202879Srdivacky}
9180202879Srdivacky
9181202379Srdivacky} // end anonymous namespace
9182202379Srdivacky
9183193326Sed/// PrintOverloadCandidates - When overload resolution fails, prints
9184193326Sed/// diagnostic messages containing the candidates in the candidate
9185202379Srdivacky/// set.
9186212904Sdimvoid OverloadCandidateSet::NoteCandidates(Sema &S,
9187212904Sdim                                          OverloadCandidateDisplayKind OCD,
9188252723Sdim                                          ArrayRef<Expr *> Args,
9189245431Sdim                                          StringRef Opc,
9190212904Sdim                                          SourceLocation OpLoc) {
9191202379Srdivacky  // Sort the candidates by viability and position.  Sorting directly would
9192202379Srdivacky  // be prohibitive, so we make a set of pointers and sort those.
9193226890Sdim  SmallVector<OverloadCandidate*, 32> Cands;
9194212904Sdim  if (OCD == OCD_AllCandidates) Cands.reserve(size());
9195212904Sdim  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9196202879Srdivacky    if (Cand->Viable)
9197202379Srdivacky      Cands.push_back(Cand);
9198202879Srdivacky    else if (OCD == OCD_AllCandidates) {
9199235633Sdim      CompleteNonViableCandidate(S, Cand, Args);
9200210299Sed      if (Cand->Function || Cand->IsSurrogate)
9201210299Sed        Cands.push_back(Cand);
9202210299Sed      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9203210299Sed      // want to list every possible builtin candidate.
9204202879Srdivacky    }
9205202879Srdivacky  }
9206202879Srdivacky
9207202379Srdivacky  std::sort(Cands.begin(), Cands.end(),
9208212904Sdim            CompareOverloadCandidatesForDisplay(S));
9209218893Sdim
9210202379Srdivacky  bool ReportedAmbiguousConversions = false;
9211193326Sed
9212226890Sdim  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9213245431Sdim  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9214210299Sed  unsigned CandsShown = 0;
9215202379Srdivacky  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9216202379Srdivacky    OverloadCandidate *Cand = *I;
9217202379Srdivacky
9218210299Sed    // Set an arbitrary limit on the number of candidate functions we'll spam
9219210299Sed    // the user with.  FIXME: This limit should depend on details of the
9220210299Sed    // candidate list.
9221245431Sdim    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9222210299Sed      break;
9223210299Sed    }
9224210299Sed    ++CandsShown;
9225210299Sed
9226202379Srdivacky    if (Cand->Function)
9227235633Sdim      NoteFunctionCandidate(S, Cand, Args.size());
9228202379Srdivacky    else if (Cand->IsSurrogate)
9229212904Sdim      NoteSurrogateCandidate(S, Cand);
9230210299Sed    else {
9231210299Sed      assert(Cand->Viable &&
9232210299Sed             "Non-viable built-in candidates are not added to Cands.");
9233202379Srdivacky      // Generally we only see ambiguities including viable builtin
9234202379Srdivacky      // operators if overload resolution got screwed up by an
9235202379Srdivacky      // ambiguous user-defined conversion.
9236202379Srdivacky      //
9237202379Srdivacky      // FIXME: It's quite possible for different conversions to see
9238202379Srdivacky      // different ambiguities, though.
9239202379Srdivacky      if (!ReportedAmbiguousConversions) {
9240212904Sdim        NoteAmbiguousUserConversions(S, OpLoc, Cand);
9241202379Srdivacky        ReportedAmbiguousConversions = true;
9242193326Sed      }
9243202379Srdivacky
9244202379Srdivacky      // If this is a viable builtin, print it.
9245212904Sdim      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9246193326Sed    }
9247193326Sed  }
9248210299Sed
9249210299Sed  if (I != E)
9250212904Sdim    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9251193326Sed}
9252193326Sed
9253263509Sdimstatic SourceLocation
9254263509SdimGetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9255263509Sdim  return Cand->Specialization ? Cand->Specialization->getLocation()
9256263509Sdim                              : SourceLocation();
9257263509Sdim}
9258263509Sdim
9259263509Sdimstruct CompareTemplateSpecCandidatesForDisplay {
9260263509Sdim  Sema &S;
9261263509Sdim  CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9262263509Sdim
9263263509Sdim  bool operator()(const TemplateSpecCandidate *L,
9264263509Sdim                  const TemplateSpecCandidate *R) {
9265263509Sdim    // Fast-path this check.
9266263509Sdim    if (L == R)
9267263509Sdim      return false;
9268263509Sdim
9269263509Sdim    // Assuming that both candidates are not matches...
9270263509Sdim
9271263509Sdim    // Sort by the ranking of deduction failures.
9272263509Sdim    if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9273263509Sdim      return RankDeductionFailure(L->DeductionFailure) <
9274263509Sdim             RankDeductionFailure(R->DeductionFailure);
9275263509Sdim
9276263509Sdim    // Sort everything else by location.
9277263509Sdim    SourceLocation LLoc = GetLocationForCandidate(L);
9278263509Sdim    SourceLocation RLoc = GetLocationForCandidate(R);
9279263509Sdim
9280263509Sdim    // Put candidates without locations (e.g. builtins) at the end.
9281263509Sdim    if (LLoc.isInvalid())
9282263509Sdim      return false;
9283263509Sdim    if (RLoc.isInvalid())
9284263509Sdim      return true;
9285263509Sdim
9286263509Sdim    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9287263509Sdim  }
9288263509Sdim};
9289263509Sdim
9290263509Sdim/// Diagnose a template argument deduction failure.
9291263509Sdim/// We are treating these failures as overload failures due to bad
9292263509Sdim/// deductions.
9293263509Sdimvoid TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9294263509Sdim  DiagnoseBadDeduction(S, Specialization, // pattern
9295263509Sdim                       DeductionFailure, /*NumArgs=*/0);
9296263509Sdim}
9297263509Sdim
9298263509Sdimvoid TemplateSpecCandidateSet::destroyCandidates() {
9299263509Sdim  for (iterator i = begin(), e = end(); i != e; ++i) {
9300263509Sdim    i->DeductionFailure.Destroy();
9301263509Sdim  }
9302263509Sdim}
9303263509Sdim
9304263509Sdimvoid TemplateSpecCandidateSet::clear() {
9305263509Sdim  destroyCandidates();
9306263509Sdim  Candidates.clear();
9307263509Sdim}
9308263509Sdim
9309263509Sdim/// NoteCandidates - When no template specialization match is found, prints
9310263509Sdim/// diagnostic messages containing the non-matching specializations that form
9311263509Sdim/// the candidate set.
9312263509Sdim/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9313263509Sdim/// OCD == OCD_AllCandidates and Cand->Viable == false.
9314263509Sdimvoid TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9315263509Sdim  // Sort the candidates by position (assuming no candidate is a match).
9316263509Sdim  // Sorting directly would be prohibitive, so we make a set of pointers
9317263509Sdim  // and sort those.
9318263509Sdim  SmallVector<TemplateSpecCandidate *, 32> Cands;
9319263509Sdim  Cands.reserve(size());
9320263509Sdim  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9321263509Sdim    if (Cand->Specialization)
9322263509Sdim      Cands.push_back(Cand);
9323263509Sdim    // Otherwise, this is a non matching builtin candidate.  We do not,
9324263509Sdim    // in general, want to list every possible builtin candidate.
9325263509Sdim  }
9326263509Sdim
9327263509Sdim  std::sort(Cands.begin(), Cands.end(),
9328263509Sdim            CompareTemplateSpecCandidatesForDisplay(S));
9329263509Sdim
9330263509Sdim  // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9331263509Sdim  // for generalization purposes (?).
9332263509Sdim  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9333263509Sdim
9334263509Sdim  SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9335263509Sdim  unsigned CandsShown = 0;
9336263509Sdim  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9337263509Sdim    TemplateSpecCandidate *Cand = *I;
9338263509Sdim
9339263509Sdim    // Set an arbitrary limit on the number of candidates we'll spam
9340263509Sdim    // the user with.  FIXME: This limit should depend on details of the
9341263509Sdim    // candidate list.
9342263509Sdim    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9343263509Sdim      break;
9344263509Sdim    ++CandsShown;
9345263509Sdim
9346263509Sdim    assert(Cand->Specialization &&
9347263509Sdim           "Non-matching built-in candidates are not added to Cands.");
9348263509Sdim    Cand->NoteDeductionFailure(S);
9349263509Sdim  }
9350263509Sdim
9351263509Sdim  if (I != E)
9352263509Sdim    S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9353263509Sdim}
9354263509Sdim
9355218893Sdim// [PossiblyAFunctionType]  -->   [Return]
9356218893Sdim// NonFunctionType --> NonFunctionType
9357218893Sdim// R (A) --> R(A)
9358218893Sdim// R (*)(A) --> R (A)
9359218893Sdim// R (&)(A) --> R (A)
9360218893Sdim// R (S::*)(A) --> R (A)
9361218893SdimQualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9362218893Sdim  QualType Ret = PossiblyAFunctionType;
9363218893Sdim  if (const PointerType *ToTypePtr =
9364218893Sdim    PossiblyAFunctionType->getAs<PointerType>())
9365218893Sdim    Ret = ToTypePtr->getPointeeType();
9366218893Sdim  else if (const ReferenceType *ToTypeRef =
9367218893Sdim    PossiblyAFunctionType->getAs<ReferenceType>())
9368218893Sdim    Ret = ToTypeRef->getPointeeType();
9369218893Sdim  else if (const MemberPointerType *MemTypePtr =
9370218893Sdim    PossiblyAFunctionType->getAs<MemberPointerType>())
9371218893Sdim    Ret = MemTypePtr->getPointeeType();
9372218893Sdim  Ret =
9373218893Sdim    Context.getCanonicalType(Ret).getUnqualifiedType();
9374218893Sdim  return Ret;
9375218893Sdim}
9376212904Sdim
9377218893Sdim// A helper class to help with address of function resolution
9378218893Sdim// - allows us to avoid passing around all those ugly parameters
9379218893Sdimclass AddressOfFunctionResolver
9380218893Sdim{
9381218893Sdim  Sema& S;
9382218893Sdim  Expr* SourceExpr;
9383218893Sdim  const QualType& TargetType;
9384218893Sdim  QualType TargetFunctionType; // Extracted function type from target type
9385218893Sdim
9386218893Sdim  bool Complain;
9387218893Sdim  //DeclAccessPair& ResultFunctionAccessPair;
9388218893Sdim  ASTContext& Context;
9389212904Sdim
9390218893Sdim  bool TargetTypeIsNonStaticMemberFunction;
9391218893Sdim  bool FoundNonTemplateFunction;
9392263509Sdim  bool StaticMemberFunctionFromBoundPointer;
9393207619Srdivacky
9394218893Sdim  OverloadExpr::FindResult OvlExprInfo;
9395218893Sdim  OverloadExpr *OvlExpr;
9396218893Sdim  TemplateArgumentListInfo OvlExplicitTemplateArgs;
9397226890Sdim  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9398263509Sdim  TemplateSpecCandidateSet FailedCandidates;
9399206084Srdivacky
9400218893Sdimpublic:
9401263509Sdim  AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9402263509Sdim                            const QualType &TargetType, bool Complain)
9403263509Sdim      : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9404263509Sdim        Complain(Complain), Context(S.getASTContext()),
9405263509Sdim        TargetTypeIsNonStaticMemberFunction(
9406263509Sdim            !!TargetType->getAs<MemberPointerType>()),
9407263509Sdim        FoundNonTemplateFunction(false),
9408263509Sdim        StaticMemberFunctionFromBoundPointer(false),
9409263509Sdim        OvlExprInfo(OverloadExpr::find(SourceExpr)),
9410263509Sdim        OvlExpr(OvlExprInfo.Expression),
9411263509Sdim        FailedCandidates(OvlExpr->getNameLoc()) {
9412218893Sdim    ExtractUnqualifiedFunctionTypeFromTargetType();
9413221345Sdim
9414263509Sdim    if (TargetFunctionType->isFunctionType()) {
9415263509Sdim      if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9416263509Sdim        if (!UME->isImplicitAccess() &&
9417263509Sdim            !S.ResolveSingleFunctionTemplateSpecialization(UME))
9418263509Sdim          StaticMemberFunctionFromBoundPointer = true;
9419263509Sdim    } else if (OvlExpr->hasExplicitTemplateArgs()) {
9420263509Sdim      DeclAccessPair dap;
9421263509Sdim      if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9422263509Sdim              OvlExpr, false, &dap)) {
9423263509Sdim        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9424263509Sdim          if (!Method->isStatic()) {
9425263509Sdim            // If the target type is a non-function type and the function found
9426263509Sdim            // is a non-static member function, pretend as if that was the
9427263509Sdim            // target, it's the only possible type to end up with.
9428263509Sdim            TargetTypeIsNonStaticMemberFunction = true;
9429221345Sdim
9430263509Sdim            // And skip adding the function if its not in the proper form.
9431263509Sdim            // We'll diagnose this due to an empty set of functions.
9432263509Sdim            if (!OvlExprInfo.HasFormOfMemberPointer)
9433263509Sdim              return;
9434221345Sdim          }
9435221345Sdim
9436263509Sdim        Matches.push_back(std::make_pair(dap, Fn));
9437218893Sdim      }
9438218893Sdim      return;
9439218893Sdim    }
9440218893Sdim
9441218893Sdim    if (OvlExpr->hasExplicitTemplateArgs())
9442218893Sdim      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9443201361Srdivacky
9444218893Sdim    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9445218893Sdim      // C++ [over.over]p4:
9446218893Sdim      //   If more than one function is selected, [...]
9447218893Sdim      if (Matches.size() > 1) {
9448218893Sdim        if (FoundNonTemplateFunction)
9449218893Sdim          EliminateAllTemplateMatches();
9450218893Sdim        else
9451218893Sdim          EliminateAllExceptMostSpecializedTemplate();
9452218893Sdim      }
9453218893Sdim    }
9454218893Sdim  }
9455218893Sdim
9456218893Sdimprivate:
9457218893Sdim  bool isTargetTypeAFunction() const {
9458218893Sdim    return TargetFunctionType->isFunctionType();
9459218893Sdim  }
9460198092Srdivacky
9461218893Sdim  // [ToType]     [Return]
9462198092Srdivacky
9463218893Sdim  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9464218893Sdim  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9465218893Sdim  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9466218893Sdim  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9467218893Sdim    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9468218893Sdim  }
9469199990Srdivacky
9470218893Sdim  // return true if any matching specializations were found
9471218893Sdim  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9472218893Sdim                                   const DeclAccessPair& CurAccessFunPair) {
9473218893Sdim    if (CXXMethodDecl *Method
9474218893Sdim              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9475218893Sdim      // Skip non-static function templates when converting to pointer, and
9476218893Sdim      // static when converting to member pointer.
9477218893Sdim      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9478218893Sdim        return false;
9479218893Sdim    }
9480218893Sdim    else if (TargetTypeIsNonStaticMemberFunction)
9481218893Sdim      return false;
9482198092Srdivacky
9483218893Sdim    // C++ [over.over]p2:
9484218893Sdim    //   If the name is a function template, template argument deduction is
9485218893Sdim    //   done (14.8.2.2), and if the argument deduction succeeds, the
9486218893Sdim    //   resulting template argument list is used to generate a single
9487218893Sdim    //   function template specialization, which is added to the set of
9488218893Sdim    //   overloaded functions considered.
9489218893Sdim    FunctionDecl *Specialization = 0;
9490263509Sdim    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9491218893Sdim    if (Sema::TemplateDeductionResult Result
9492218893Sdim          = S.DeduceTemplateArguments(FunctionTemplate,
9493218893Sdim                                      &OvlExplicitTemplateArgs,
9494218893Sdim                                      TargetFunctionType, Specialization,
9495252723Sdim                                      Info, /*InOverloadResolution=*/true)) {
9496263509Sdim      // Make a note of the failed deduction for diagnostics.
9497263509Sdim      FailedCandidates.addCandidate()
9498263509Sdim          .set(FunctionTemplate->getTemplatedDecl(),
9499263509Sdim               MakeDeductionFailureInfo(Context, Result, Info));
9500218893Sdim      return false;
9501218893Sdim    }
9502218893Sdim
9503252723Sdim    // Template argument deduction ensures that we have an exact match or
9504252723Sdim    // compatible pointer-to-function arguments that would be adjusted by ICS.
9505218893Sdim    // This function template specicalization works.
9506218893Sdim    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9507252723Sdim    assert(S.isSameOrCompatibleFunctionType(
9508252723Sdim              Context.getCanonicalType(Specialization->getType()),
9509252723Sdim              Context.getCanonicalType(TargetFunctionType)));
9510218893Sdim    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9511218893Sdim    return true;
9512218893Sdim  }
9513218893Sdim
9514218893Sdim  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9515218893Sdim                                      const DeclAccessPair& CurAccessFunPair) {
9516201361Srdivacky    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9517193326Sed      // Skip non-static functions when converting to pointer, and static
9518193326Sed      // when converting to member pointer.
9519218893Sdim      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9520218893Sdim        return false;
9521218893Sdim    }
9522218893Sdim    else if (TargetTypeIsNonStaticMemberFunction)
9523218893Sdim      return false;
9524193326Sed
9525201361Srdivacky    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9526235633Sdim      if (S.getLangOpts().CUDA)
9527226890Sdim        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9528226890Sdim          if (S.CheckCUDATarget(Caller, FunDecl))
9529226890Sdim            return false;
9530226890Sdim
9531252723Sdim      // If any candidate has a placeholder return type, trigger its deduction
9532252723Sdim      // now.
9533252723Sdim      if (S.getLangOpts().CPlusPlus1y &&
9534252723Sdim          FunDecl->getResultType()->isUndeducedType() &&
9535252723Sdim          S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9536252723Sdim        return false;
9537252723Sdim
9538200583Srdivacky      QualType ResultTy;
9539218893Sdim      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9540218893Sdim                                         FunDecl->getType()) ||
9541224145Sdim          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9542224145Sdim                                 ResultTy)) {
9543218893Sdim        Matches.push_back(std::make_pair(CurAccessFunPair,
9544218893Sdim          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9545198092Srdivacky        FoundNonTemplateFunction = true;
9546218893Sdim        return true;
9547198092Srdivacky      }
9548195099Sed    }
9549218893Sdim
9550218893Sdim    return false;
9551193326Sed  }
9552218893Sdim
9553218893Sdim  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9554218893Sdim    bool Ret = false;
9555218893Sdim
9556218893Sdim    // If the overload expression doesn't have the form of a pointer to
9557218893Sdim    // member, don't try to convert it to a pointer-to-member type.
9558218893Sdim    if (IsInvalidFormOfPointerToMemberFunction())
9559218893Sdim      return false;
9560193326Sed
9561218893Sdim    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9562218893Sdim                               E = OvlExpr->decls_end();
9563218893Sdim         I != E; ++I) {
9564218893Sdim      // Look through any using declarations to find the underlying function.
9565218893Sdim      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9566218893Sdim
9567218893Sdim      // C++ [over.over]p3:
9568218893Sdim      //   Non-member functions and static member functions match
9569218893Sdim      //   targets of type "pointer-to-function" or "reference-to-function."
9570218893Sdim      //   Nonstatic member functions match targets of
9571218893Sdim      //   type "pointer-to-member-function."
9572218893Sdim      // Note that according to DR 247, the containing class does not matter.
9573218893Sdim      if (FunctionTemplateDecl *FunctionTemplate
9574218893Sdim                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9575218893Sdim        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9576218893Sdim          Ret = true;
9577218893Sdim      }
9578218893Sdim      // If we have explicit template arguments supplied, skip non-templates.
9579218893Sdim      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9580218893Sdim               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9581218893Sdim        Ret = true;
9582207619Srdivacky    }
9583218893Sdim    assert(Ret || Matches.empty());
9584218893Sdim    return Ret;
9585198398Srdivacky  }
9586198092Srdivacky
9587218893Sdim  void EliminateAllExceptMostSpecializedTemplate() {
9588198092Srdivacky    //   [...] and any given function template specialization F1 is
9589198092Srdivacky    //   eliminated if the set contains a second function template
9590198092Srdivacky    //   specialization whose function template is more specialized
9591198092Srdivacky    //   than the function template of F1 according to the partial
9592198092Srdivacky    //   ordering rules of 14.5.5.2.
9593198092Srdivacky
9594198092Srdivacky    // The algorithm specified above is quadratic. We instead use a
9595198092Srdivacky    // two-pass algorithm (similar to the one used to identify the
9596198092Srdivacky    // best viable function in an overload set) that identifies the
9597198092Srdivacky    // best function template (if it exists).
9598205408Srdivacky
9599205408Srdivacky    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9600205408Srdivacky    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9601205408Srdivacky      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9602218893Sdim
9603263509Sdim    // TODO: It looks like FailedCandidates does not serve much purpose
9604263509Sdim    // here, since the no_viable diagnostic has index 0.
9605263509Sdim    UnresolvedSetIterator Result = S.getMostSpecialized(
9606263509Sdim        MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9607263509Sdim        SourceExpr->getLocStart(), S.PDiag(),
9608263509Sdim        S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9609263509Sdim                                                     .second->getDeclName(),
9610263509Sdim        S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9611263509Sdim        Complain, TargetFunctionType);
9612218893Sdim
9613218893Sdim    if (Result != MatchesCopy.end()) {
9614218893Sdim      // Make it the first and only element
9615218893Sdim      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9616218893Sdim      Matches[0].second = cast<FunctionDecl>(*Result);
9617218893Sdim      Matches.resize(1);
9618208600Srdivacky    }
9619198092Srdivacky  }
9620198092Srdivacky
9621218893Sdim  void EliminateAllTemplateMatches() {
9622218893Sdim    //   [...] any function template specializations in the set are
9623218893Sdim    //   eliminated if the set also contains a non-template function, [...]
9624218893Sdim    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9625218893Sdim      if (Matches[I].second->getPrimaryTemplate() == 0)
9626218893Sdim        ++I;
9627218893Sdim      else {
9628218893Sdim        Matches[I] = Matches[--N];
9629218893Sdim        Matches.set_size(N);
9630218893Sdim      }
9631203955Srdivacky    }
9632203955Srdivacky  }
9633218893Sdim
9634218893Sdimpublic:
9635218893Sdim  void ComplainNoMatchesFound() const {
9636218893Sdim    assert(Matches.empty());
9637218893Sdim    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9638218893Sdim        << OvlExpr->getName() << TargetFunctionType
9639218893Sdim        << OvlExpr->getSourceRange();
9640263509Sdim    if (FailedCandidates.empty())
9641263509Sdim      S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9642263509Sdim    else {
9643263509Sdim      // We have some deduction failure messages. Use them to diagnose
9644263509Sdim      // the function templates, and diagnose the non-template candidates
9645263509Sdim      // normally.
9646263509Sdim      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9647263509Sdim                                 IEnd = OvlExpr->decls_end();
9648263509Sdim           I != IEnd; ++I)
9649263509Sdim        if (FunctionDecl *Fun =
9650263509Sdim                dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9651263509Sdim          S.NoteOverloadCandidate(Fun, TargetFunctionType);
9652263509Sdim      FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9653263509Sdim    }
9654263509Sdim  }
9655263509Sdim
9656218893Sdim  bool IsInvalidFormOfPointerToMemberFunction() const {
9657218893Sdim    return TargetTypeIsNonStaticMemberFunction &&
9658218893Sdim      !OvlExprInfo.HasFormOfMemberPointer;
9659198398Srdivacky  }
9660263509Sdim
9661218893Sdim  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9662218893Sdim      // TODO: Should we condition this on whether any functions might
9663218893Sdim      // have matched, or is it more appropriate to do that in callers?
9664218893Sdim      // TODO: a fixit wouldn't hurt.
9665218893Sdim      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9666218893Sdim        << TargetType << OvlExpr->getSourceRange();
9667218893Sdim  }
9668263509Sdim
9669263509Sdim  bool IsStaticMemberFunctionFromBoundPointer() const {
9670263509Sdim    return StaticMemberFunctionFromBoundPointer;
9671263509Sdim  }
9672263509Sdim
9673263509Sdim  void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9674263509Sdim    S.Diag(OvlExpr->getLocStart(),
9675263509Sdim           diag::err_invalid_form_pointer_member_function)
9676263509Sdim      << OvlExpr->getSourceRange();
9677263509Sdim  }
9678263509Sdim
9679218893Sdim  void ComplainOfInvalidConversion() const {
9680218893Sdim    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9681218893Sdim      << OvlExpr->getName() << TargetType;
9682218893Sdim  }
9683198092Srdivacky
9684218893Sdim  void ComplainMultipleMatchesFound() const {
9685218893Sdim    assert(Matches.size() > 1);
9686218893Sdim    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9687218893Sdim      << OvlExpr->getName()
9688218893Sdim      << OvlExpr->getSourceRange();
9689235633Sdim    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9690218893Sdim  }
9691235633Sdim
9692235633Sdim  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9693235633Sdim
9694218893Sdim  int getNumMatches() const { return Matches.size(); }
9695218893Sdim
9696218893Sdim  FunctionDecl* getMatchingFunctionDecl() const {
9697218893Sdim    if (Matches.size() != 1) return 0;
9698218893Sdim    return Matches[0].second;
9699218893Sdim  }
9700218893Sdim
9701218893Sdim  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9702218893Sdim    if (Matches.size() != 1) return 0;
9703218893Sdim    return &Matches[0].first;
9704218893Sdim  }
9705218893Sdim};
9706218893Sdim
9707218893Sdim/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9708218893Sdim/// an overloaded function (C++ [over.over]), where @p From is an
9709218893Sdim/// expression with overloaded function type and @p ToType is the type
9710218893Sdim/// we're trying to resolve to. For example:
9711218893Sdim///
9712218893Sdim/// @code
9713218893Sdim/// int f(double);
9714218893Sdim/// int f(int);
9715218893Sdim///
9716218893Sdim/// int (*pfd)(double) = f; // selects f(double)
9717218893Sdim/// @endcode
9718218893Sdim///
9719218893Sdim/// This routine returns the resulting FunctionDecl if it could be
9720218893Sdim/// resolved, and NULL otherwise. When @p Complain is true, this
9721218893Sdim/// routine will emit diagnostics if there is an error.
9722218893SdimFunctionDecl *
9723235633SdimSema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9724235633Sdim                                         QualType TargetType,
9725235633Sdim                                         bool Complain,
9726235633Sdim                                         DeclAccessPair &FoundResult,
9727235633Sdim                                         bool *pHadMultipleCandidates) {
9728235633Sdim  assert(AddressOfExpr->getType() == Context.OverloadTy);
9729218893Sdim
9730235633Sdim  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9731235633Sdim                                     Complain);
9732218893Sdim  int NumMatches = Resolver.getNumMatches();
9733218893Sdim  FunctionDecl* Fn = 0;
9734235633Sdim  if (NumMatches == 0 && Complain) {
9735218893Sdim    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9736218893Sdim      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9737218893Sdim    else
9738218893Sdim      Resolver.ComplainNoMatchesFound();
9739218893Sdim  }
9740218893Sdim  else if (NumMatches > 1 && Complain)
9741218893Sdim    Resolver.ComplainMultipleMatchesFound();
9742218893Sdim  else if (NumMatches == 1) {
9743218893Sdim    Fn = Resolver.getMatchingFunctionDecl();
9744218893Sdim    assert(Fn);
9745218893Sdim    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9746263509Sdim    if (Complain) {
9747263509Sdim      if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9748263509Sdim        Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9749263509Sdim      else
9750263509Sdim        CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9751263509Sdim    }
9752218893Sdim  }
9753235633Sdim
9754235633Sdim  if (pHadMultipleCandidates)
9755235633Sdim    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9756218893Sdim  return Fn;
9757193326Sed}
9758193326Sed
9759218893Sdim/// \brief Given an expression that refers to an overloaded function, try to
9760201361Srdivacky/// resolve that overloaded function expression down to a single function.
9761201361Srdivacky///
9762201361Srdivacky/// This routine can only resolve template-ids that refer to a single function
9763201361Srdivacky/// template, where that template-id refers to a single template whose template
9764218893Sdim/// arguments are either provided by the template-id or have defaults,
9765201361Srdivacky/// as described in C++0x [temp.arg.explicit]p3.
9766263509Sdim///
9767263509Sdim/// If no template-ids are found, no diagnostics are emitted and NULL is
9768263509Sdim/// returned.
9769221345SdimFunctionDecl *
9770221345SdimSema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9771221345Sdim                                                  bool Complain,
9772221345Sdim                                                  DeclAccessPair *FoundResult) {
9773201361Srdivacky  // C++ [over.over]p1:
9774201361Srdivacky  //   [...] [Note: any redundant set of parentheses surrounding the
9775201361Srdivacky  //   overloaded function name is ignored (5.1). ]
9776201361Srdivacky  // C++ [over.over]p1:
9777201361Srdivacky  //   [...] The overloaded function name can be preceded by the &
9778201361Srdivacky  //   operator.
9779203955Srdivacky
9780201361Srdivacky  // If we didn't actually find any template-ids, we're done.
9781221345Sdim  if (!ovl->hasExplicitTemplateArgs())
9782201361Srdivacky    return 0;
9783203955Srdivacky
9784203955Srdivacky  TemplateArgumentListInfo ExplicitTemplateArgs;
9785221345Sdim  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9786263509Sdim  TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
9787218893Sdim
9788201361Srdivacky  // Look through all of the overloaded functions, searching for one
9789201361Srdivacky  // whose type matches exactly.
9790201361Srdivacky  FunctionDecl *Matched = 0;
9791221345Sdim  for (UnresolvedSetIterator I = ovl->decls_begin(),
9792221345Sdim         E = ovl->decls_end(); I != E; ++I) {
9793201361Srdivacky    // C++0x [temp.arg.explicit]p3:
9794201361Srdivacky    //   [...] In contexts where deduction is done and fails, or in contexts
9795218893Sdim    //   where deduction is not done, if a template argument list is
9796218893Sdim    //   specified and it, along with any default template arguments,
9797218893Sdim    //   identifies a single function template specialization, then the
9798201361Srdivacky    //   template-id is an lvalue for the function template specialization.
9799210299Sed    FunctionTemplateDecl *FunctionTemplate
9800210299Sed      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9801218893Sdim
9802201361Srdivacky    // C++ [over.over]p2:
9803201361Srdivacky    //   If the name is a function template, template argument deduction is
9804201361Srdivacky    //   done (14.8.2.2), and if the argument deduction succeeds, the
9805201361Srdivacky    //   resulting template argument list is used to generate a single
9806201361Srdivacky    //   function template specialization, which is added to the set of
9807201361Srdivacky    //   overloaded functions considered.
9808201361Srdivacky    FunctionDecl *Specialization = 0;
9809263509Sdim    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9810201361Srdivacky    if (TemplateDeductionResult Result
9811201361Srdivacky          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9812252723Sdim                                    Specialization, Info,
9813252723Sdim                                    /*InOverloadResolution=*/true)) {
9814263509Sdim      // Make a note of the failed deduction for diagnostics.
9815263509Sdim      // TODO: Actually use the failed-deduction info?
9816263509Sdim      FailedCandidates.addCandidate()
9817263509Sdim          .set(FunctionTemplate->getTemplatedDecl(),
9818263509Sdim               MakeDeductionFailureInfo(Context, Result, Info));
9819201361Srdivacky      continue;
9820218893Sdim    }
9821218893Sdim
9822221345Sdim    assert(Specialization && "no specialization and no error?");
9823221345Sdim
9824201361Srdivacky    // Multiple matches; we can't resolve to a single declaration.
9825218893Sdim    if (Matched) {
9826218893Sdim      if (Complain) {
9827221345Sdim        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9828221345Sdim          << ovl->getName();
9829221345Sdim        NoteAllOverloadCandidates(ovl);
9830218893Sdim      }
9831201361Srdivacky      return 0;
9832221345Sdim    }
9833218893Sdim
9834221345Sdim    Matched = Specialization;
9835221345Sdim    if (FoundResult) *FoundResult = I.getPair();
9836201361Srdivacky  }
9837201361Srdivacky
9838252723Sdim  if (Matched && getLangOpts().CPlusPlus1y &&
9839252723Sdim      Matched->getResultType()->isUndeducedType() &&
9840252723Sdim      DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9841252723Sdim    return 0;
9842252723Sdim
9843201361Srdivacky  return Matched;
9844201361Srdivacky}
9845218893Sdim
9846221345Sdim
9847221345Sdim
9848221345Sdim
9849226890Sdim// Resolve and fix an overloaded expression that can be resolved
9850226890Sdim// because it identifies a single function template specialization.
9851226890Sdim//
9852221345Sdim// Last three arguments should only be supplied if Complain = true
9853226890Sdim//
9854226890Sdim// Return true if it was logically possible to so resolve the
9855226890Sdim// expression, regardless of whether or not it succeeded.  Always
9856226890Sdim// returns true if 'complain' is set.
9857226890Sdimbool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9858226890Sdim                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9859226890Sdim                   bool complain, const SourceRange& OpRangeForComplaining,
9860221345Sdim                                           QualType DestTypeForComplaining,
9861221345Sdim                                            unsigned DiagIDForComplaining) {
9862226890Sdim  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9863221345Sdim
9864226890Sdim  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9865221345Sdim
9866221345Sdim  DeclAccessPair found;
9867221345Sdim  ExprResult SingleFunctionExpression;
9868221345Sdim  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9869221345Sdim                           ovl.Expression, /*complain*/ false, &found)) {
9870235633Sdim    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9871226890Sdim      SrcExpr = ExprError();
9872226890Sdim      return true;
9873226890Sdim    }
9874221345Sdim
9875221345Sdim    // It is only correct to resolve to an instance method if we're
9876221345Sdim    // resolving a form that's permitted to be a pointer to member.
9877221345Sdim    // Otherwise we'll end up making a bound member expression, which
9878221345Sdim    // is illegal in all the contexts we resolve like this.
9879221345Sdim    if (!ovl.HasFormOfMemberPointer &&
9880221345Sdim        isa<CXXMethodDecl>(fn) &&
9881221345Sdim        cast<CXXMethodDecl>(fn)->isInstance()) {
9882226890Sdim      if (!complain) return false;
9883226890Sdim
9884226890Sdim      Diag(ovl.Expression->getExprLoc(),
9885226890Sdim           diag::err_bound_member_function)
9886226890Sdim        << 0 << ovl.Expression->getSourceRange();
9887226890Sdim
9888226890Sdim      // TODO: I believe we only end up here if there's a mix of
9889226890Sdim      // static and non-static candidates (otherwise the expression
9890226890Sdim      // would have 'bound member' type, not 'overload' type).
9891226890Sdim      // Ideally we would note which candidate was chosen and why
9892226890Sdim      // the static candidates were rejected.
9893226890Sdim      SrcExpr = ExprError();
9894226890Sdim      return true;
9895221345Sdim    }
9896221345Sdim
9897245431Sdim    // Fix the expression to refer to 'fn'.
9898221345Sdim    SingleFunctionExpression =
9899226890Sdim      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9900221345Sdim
9901221345Sdim    // If desired, do function-to-pointer decay.
9902226890Sdim    if (doFunctionPointerConverion) {
9903221345Sdim      SingleFunctionExpression =
9904221345Sdim        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9905226890Sdim      if (SingleFunctionExpression.isInvalid()) {
9906226890Sdim        SrcExpr = ExprError();
9907226890Sdim        return true;
9908226890Sdim      }
9909226890Sdim    }
9910221345Sdim  }
9911221345Sdim
9912221345Sdim  if (!SingleFunctionExpression.isUsable()) {
9913221345Sdim    if (complain) {
9914221345Sdim      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9915221345Sdim        << ovl.Expression->getName()
9916221345Sdim        << DestTypeForComplaining
9917221345Sdim        << OpRangeForComplaining
9918221345Sdim        << ovl.Expression->getQualifierLoc().getSourceRange();
9919226890Sdim      NoteAllOverloadCandidates(SrcExpr.get());
9920226890Sdim
9921226890Sdim      SrcExpr = ExprError();
9922226890Sdim      return true;
9923226890Sdim    }
9924226890Sdim
9925226890Sdim    return false;
9926221345Sdim  }
9927221345Sdim
9928226890Sdim  SrcExpr = SingleFunctionExpression;
9929226890Sdim  return true;
9930221345Sdim}
9931221345Sdim
9932198092Srdivacky/// \brief Add a single candidate to the overload set.
9933198092Srdivackystatic void AddOverloadedCallCandidate(Sema &S,
9934205408Srdivacky                                       DeclAccessPair FoundDecl,
9935221345Sdim                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9936252723Sdim                                       ArrayRef<Expr *> Args,
9937198092Srdivacky                                       OverloadCandidateSet &CandidateSet,
9938224145Sdim                                       bool PartialOverloading,
9939224145Sdim                                       bool KnownValid) {
9940205408Srdivacky  NamedDecl *Callee = FoundDecl.getDecl();
9941199990Srdivacky  if (isa<UsingShadowDecl>(Callee))
9942199990Srdivacky    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9943199990Srdivacky
9944198092Srdivacky  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9945224145Sdim    if (ExplicitTemplateArgs) {
9946224145Sdim      assert(!KnownValid && "Explicit template arguments?");
9947224145Sdim      return;
9948224145Sdim    }
9949235633Sdim    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9950235633Sdim                           PartialOverloading);
9951198092Srdivacky    return;
9952199990Srdivacky  }
9953199990Srdivacky
9954199990Srdivacky  if (FunctionTemplateDecl *FuncTemplate
9955199990Srdivacky      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9956205408Srdivacky    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9957235633Sdim                                   ExplicitTemplateArgs, Args, CandidateSet);
9958199990Srdivacky    return;
9959199990Srdivacky  }
9960199990Srdivacky
9961224145Sdim  assert(!KnownValid && "unhandled case in overloaded call candidate");
9962198092Srdivacky}
9963218893Sdim
9964198092Srdivacky/// \brief Add the overload candidates named by callee and/or found by argument
9965198092Srdivacky/// dependent lookup to the given overload set.
9966201361Srdivackyvoid Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9967252723Sdim                                       ArrayRef<Expr *> Args,
9968198092Srdivacky                                       OverloadCandidateSet &CandidateSet,
9969198092Srdivacky                                       bool PartialOverloading) {
9970199990Srdivacky
9971199990Srdivacky#ifndef NDEBUG
9972199990Srdivacky  // Verify that ArgumentDependentLookup is consistent with the rules
9973199990Srdivacky  // in C++0x [basic.lookup.argdep]p3:
9974193326Sed  //
9975193326Sed  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9976193326Sed  //   and let Y be the lookup set produced by argument dependent
9977193326Sed  //   lookup (defined as follows). If X contains
9978193326Sed  //
9979198092Srdivacky  //     -- a declaration of a class member, or
9980193326Sed  //
9981193326Sed  //     -- a block-scope function declaration that is not a
9982199990Srdivacky  //        using-declaration, or
9983198092Srdivacky  //
9984193326Sed  //     -- a declaration that is neither a function or a function
9985193326Sed  //        template
9986193326Sed  //
9987198092Srdivacky  //   then Y is empty.
9988199990Srdivacky
9989201361Srdivacky  if (ULE->requiresADL()) {
9990201361Srdivacky    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9991201361Srdivacky           E = ULE->decls_end(); I != E; ++I) {
9992201361Srdivacky      assert(!(*I)->getDeclContext()->isRecord());
9993201361Srdivacky      assert(isa<UsingShadowDecl>(*I) ||
9994201361Srdivacky             !(*I)->getDeclContext()->isFunctionOrMethod());
9995201361Srdivacky      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9996199990Srdivacky    }
9997199990Srdivacky  }
9998199990Srdivacky#endif
9999199990Srdivacky
10000201361Srdivacky  // It would be nice to avoid this copy.
10001201361Srdivacky  TemplateArgumentListInfo TABuffer;
10002221345Sdim  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
10003201361Srdivacky  if (ULE->hasExplicitTemplateArgs()) {
10004201361Srdivacky    ULE->copyTemplateArgumentsInto(TABuffer);
10005201361Srdivacky    ExplicitTemplateArgs = &TABuffer;
10006201361Srdivacky  }
10007201361Srdivacky
10008201361Srdivacky  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10009201361Srdivacky         E = ULE->decls_end(); I != E; ++I)
10010235633Sdim    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10011235633Sdim                               CandidateSet, PartialOverloading,
10012235633Sdim                               /*KnownValid*/ true);
10013199990Srdivacky
10014201361Srdivacky  if (ULE->requiresADL())
10015203955Srdivacky    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
10016235633Sdim                                         ULE->getExprLoc(),
10017235633Sdim                                         Args, ExplicitTemplateArgs,
10018245431Sdim                                         CandidateSet, PartialOverloading);
10019198092Srdivacky}
10020201361Srdivacky
10021263509Sdim/// Determine whether a declaration with the specified name could be moved into
10022263509Sdim/// a different namespace.
10023263509Sdimstatic bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10024263509Sdim  switch (Name.getCXXOverloadedOperator()) {
10025263509Sdim  case OO_New: case OO_Array_New:
10026263509Sdim  case OO_Delete: case OO_Array_Delete:
10027263509Sdim    return false;
10028263509Sdim
10029263509Sdim  default:
10030263509Sdim    return true;
10031263509Sdim  }
10032263509Sdim}
10033263509Sdim
10034223017Sdim/// Attempt to recover from an ill-formed use of a non-dependent name in a
10035223017Sdim/// template, where the non-dependent name was declared after the template
10036223017Sdim/// was defined. This is common in code written for a compilers which do not
10037223017Sdim/// correctly implement two-stage name lookup.
10038223017Sdim///
10039223017Sdim/// Returns true if a viable candidate was found and a diagnostic was issued.
10040223017Sdimstatic bool
10041223017SdimDiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10042223017Sdim                       const CXXScopeSpec &SS, LookupResult &R,
10043223017Sdim                       TemplateArgumentListInfo *ExplicitTemplateArgs,
10044252723Sdim                       ArrayRef<Expr *> Args) {
10045223017Sdim  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10046223017Sdim    return false;
10047223017Sdim
10048223017Sdim  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10049235633Sdim    if (DC->isTransparentContext())
10050235633Sdim      continue;
10051235633Sdim
10052223017Sdim    SemaRef.LookupQualifiedName(R, DC);
10053223017Sdim
10054223017Sdim    if (!R.empty()) {
10055223017Sdim      R.suppressDiagnostics();
10056223017Sdim
10057223017Sdim      if (isa<CXXRecordDecl>(DC)) {
10058223017Sdim        // Don't diagnose names we find in classes; we get much better
10059223017Sdim        // diagnostics for these from DiagnoseEmptyLookup.
10060223017Sdim        R.clear();
10061223017Sdim        return false;
10062223017Sdim      }
10063223017Sdim
10064223017Sdim      OverloadCandidateSet Candidates(FnLoc);
10065223017Sdim      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10066223017Sdim        AddOverloadedCallCandidate(SemaRef, I.getPair(),
10067235633Sdim                                   ExplicitTemplateArgs, Args,
10068224145Sdim                                   Candidates, false, /*KnownValid*/ false);
10069223017Sdim
10070223017Sdim      OverloadCandidateSet::iterator Best;
10071224145Sdim      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10072223017Sdim        // No viable functions. Don't bother the user with notes for functions
10073223017Sdim        // which don't work and shouldn't be found anyway.
10074224145Sdim        R.clear();
10075223017Sdim        return false;
10076224145Sdim      }
10077223017Sdim
10078223017Sdim      // Find the namespaces where ADL would have looked, and suggest
10079223017Sdim      // declaring the function there instead.
10080223017Sdim      Sema::AssociatedNamespaceSet AssociatedNamespaces;
10081223017Sdim      Sema::AssociatedClassSet AssociatedClasses;
10082245431Sdim      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10083223017Sdim                                                 AssociatedNamespaces,
10084223017Sdim                                                 AssociatedClasses);
10085223017Sdim      Sema::AssociatedNamespaceSet SuggestedNamespaces;
10086263509Sdim      if (canBeDeclaredInNamespace(R.getLookupName())) {
10087263509Sdim        DeclContext *Std = SemaRef.getStdNamespace();
10088263509Sdim        for (Sema::AssociatedNamespaceSet::iterator
10089263509Sdim               it = AssociatedNamespaces.begin(),
10090263509Sdim               end = AssociatedNamespaces.end(); it != end; ++it) {
10091263509Sdim          // Never suggest declaring a function within namespace 'std'.
10092263509Sdim          if (Std && Std->Encloses(*it))
10093263509Sdim            continue;
10094252723Sdim
10095263509Sdim          // Never suggest declaring a function within a namespace with a
10096263509Sdim          // reserved name, like __gnu_cxx.
10097263509Sdim          NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10098263509Sdim          if (NS &&
10099263509Sdim              NS->getQualifiedNameAsString().find("__") != std::string::npos)
10100263509Sdim            continue;
10101263509Sdim
10102263509Sdim          SuggestedNamespaces.insert(*it);
10103263509Sdim        }
10104223017Sdim      }
10105223017Sdim
10106223017Sdim      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10107223017Sdim        << R.getLookupName();
10108223017Sdim      if (SuggestedNamespaces.empty()) {
10109223017Sdim        SemaRef.Diag(Best->Function->getLocation(),
10110223017Sdim                     diag::note_not_found_by_two_phase_lookup)
10111223017Sdim          << R.getLookupName() << 0;
10112223017Sdim      } else if (SuggestedNamespaces.size() == 1) {
10113223017Sdim        SemaRef.Diag(Best->Function->getLocation(),
10114223017Sdim                     diag::note_not_found_by_two_phase_lookup)
10115223017Sdim          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10116223017Sdim      } else {
10117223017Sdim        // FIXME: It would be useful to list the associated namespaces here,
10118223017Sdim        // but the diagnostics infrastructure doesn't provide a way to produce
10119223017Sdim        // a localized representation of a list of items.
10120223017Sdim        SemaRef.Diag(Best->Function->getLocation(),
10121223017Sdim                     diag::note_not_found_by_two_phase_lookup)
10122223017Sdim          << R.getLookupName() << 2;
10123223017Sdim      }
10124223017Sdim
10125223017Sdim      // Try to recover by calling this function.
10126223017Sdim      return true;
10127223017Sdim    }
10128223017Sdim
10129223017Sdim    R.clear();
10130223017Sdim  }
10131223017Sdim
10132223017Sdim  return false;
10133223017Sdim}
10134223017Sdim
10135223017Sdim/// Attempt to recover from ill-formed use of a non-dependent operator in a
10136223017Sdim/// template, where the non-dependent operator was declared after the template
10137223017Sdim/// was defined.
10138223017Sdim///
10139223017Sdim/// Returns true if a viable candidate was found and a diagnostic was issued.
10140223017Sdimstatic bool
10141223017SdimDiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10142223017Sdim                               SourceLocation OpLoc,
10143252723Sdim                               ArrayRef<Expr *> Args) {
10144223017Sdim  DeclarationName OpName =
10145223017Sdim    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10146223017Sdim  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10147223017Sdim  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10148235633Sdim                                /*ExplicitTemplateArgs=*/0, Args);
10149223017Sdim}
10150223017Sdim
10151235633Sdimnamespace {
10152245431Sdimclass BuildRecoveryCallExprRAII {
10153245431Sdim  Sema &SemaRef;
10154245431Sdimpublic:
10155245431Sdim  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10156245431Sdim    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10157245431Sdim    SemaRef.IsBuildingRecoveryCallExpr = true;
10158245431Sdim  }
10159245431Sdim
10160245431Sdim  ~BuildRecoveryCallExprRAII() {
10161245431Sdim    SemaRef.IsBuildingRecoveryCallExpr = false;
10162245431Sdim  }
10163245431Sdim};
10164245431Sdim
10165235633Sdim}
10166235633Sdim
10167201361Srdivacky/// Attempts to recover from a call where no functions were found.
10168201361Srdivacky///
10169201361Srdivacky/// Returns true if new candidates were found.
10170212904Sdimstatic ExprResult
10171207619SrdivackyBuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10172201361Srdivacky                      UnresolvedLookupExpr *ULE,
10173201361Srdivacky                      SourceLocation LParenLoc,
10174235633Sdim                      llvm::MutableArrayRef<Expr *> Args,
10175223017Sdim                      SourceLocation RParenLoc,
10176235633Sdim                      bool EmptyLookup, bool AllowTypoCorrection) {
10177245431Sdim  // Do not try to recover if it is already building a recovery call.
10178245431Sdim  // This stops infinite loops for template instantiations like
10179245431Sdim  //
10180245431Sdim  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10181245431Sdim  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10182245431Sdim  //
10183245431Sdim  if (SemaRef.IsBuildingRecoveryCallExpr)
10184245431Sdim    return ExprError();
10185245431Sdim  BuildRecoveryCallExprRAII RCE(SemaRef);
10186201361Srdivacky
10187201361Srdivacky  CXXScopeSpec SS;
10188221345Sdim  SS.Adopt(ULE->getQualifierLoc());
10189235633Sdim  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10190201361Srdivacky
10191201361Srdivacky  TemplateArgumentListInfo TABuffer;
10192223017Sdim  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
10193201361Srdivacky  if (ULE->hasExplicitTemplateArgs()) {
10194201361Srdivacky    ULE->copyTemplateArgumentsInto(TABuffer);
10195201361Srdivacky    ExplicitTemplateArgs = &TABuffer;
10196201361Srdivacky  }
10197201361Srdivacky
10198201361Srdivacky  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10199201361Srdivacky                 Sema::LookupOrdinaryName);
10200263509Sdim  FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10201263509Sdim                                  ExplicitTemplateArgs != 0);
10202235633Sdim  NoTypoCorrectionCCC RejectAll;
10203235633Sdim  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10204235633Sdim      (CorrectionCandidateCallback*)&Validator :
10205235633Sdim      (CorrectionCandidateCallback*)&RejectAll;
10206223017Sdim  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10207235633Sdim                              ExplicitTemplateArgs, Args) &&
10208223017Sdim      (!EmptyLookup ||
10209235633Sdim       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10210235633Sdim                                   ExplicitTemplateArgs, Args)))
10211212904Sdim    return ExprError();
10212201361Srdivacky
10213201361Srdivacky  assert(!R.empty() && "lookup results empty despite recovery");
10214201361Srdivacky
10215201361Srdivacky  // Build an implicit member call if appropriate.  Just drop the
10216201361Srdivacky  // casts and such from the call, we don't really care.
10217212904Sdim  ExprResult NewFn = ExprError();
10218201361Srdivacky  if ((*R.begin())->isCXXClassMember())
10219235633Sdim    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10220235633Sdim                                                    R, ExplicitTemplateArgs);
10221235633Sdim  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10222235633Sdim    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10223235633Sdim                                        ExplicitTemplateArgs);
10224201361Srdivacky  else
10225201361Srdivacky    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10226201361Srdivacky
10227201361Srdivacky  if (NewFn.isInvalid())
10228212904Sdim    return ExprError();
10229201361Srdivacky
10230201361Srdivacky  // This shouldn't cause an infinite loop because we're giving it
10231223017Sdim  // an expression with viable lookup results, which should never
10232201361Srdivacky  // end up here.
10233212904Sdim  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
10234235633Sdim                               MultiExprArg(Args.data(), Args.size()),
10235235633Sdim                               RParenLoc);
10236201361Srdivacky}
10237210299Sed
10238245431Sdim/// \brief Constructs and populates an OverloadedCandidateSet from
10239245431Sdim/// the given function.
10240245431Sdim/// \returns true when an the ExprResult output parameter has been set.
10241245431Sdimbool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10242245431Sdim                                  UnresolvedLookupExpr *ULE,
10243263509Sdim                                  MultiExprArg Args,
10244245431Sdim                                  SourceLocation RParenLoc,
10245245431Sdim                                  OverloadCandidateSet *CandidateSet,
10246245431Sdim                                  ExprResult *Result) {
10247201361Srdivacky#ifndef NDEBUG
10248201361Srdivacky  if (ULE->requiresADL()) {
10249201361Srdivacky    // To do ADL, we must have found an unqualified name.
10250201361Srdivacky    assert(!ULE->getQualifier() && "qualified name with ADL");
10251201361Srdivacky
10252201361Srdivacky    // We don't perform ADL for implicit declarations of builtins.
10253201361Srdivacky    // Verify that this was correctly set up.
10254201361Srdivacky    FunctionDecl *F;
10255201361Srdivacky    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10256201361Srdivacky        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10257201361Srdivacky        F->getBuiltinID() && F->isImplicit())
10258226890Sdim      llvm_unreachable("performing ADL for builtin");
10259218893Sdim
10260201361Srdivacky    // We don't perform ADL in C.
10261235633Sdim    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10262245431Sdim  }
10263201361Srdivacky#endif
10264201361Srdivacky
10265235633Sdim  UnbridgedCastsSet UnbridgedCasts;
10266263509Sdim  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10267245431Sdim    *Result = ExprError();
10268245431Sdim    return true;
10269245431Sdim  }
10270235633Sdim
10271201361Srdivacky  // Add the functions denoted by the callee to the set of candidate
10272201361Srdivacky  // functions, including those from argument-dependent lookup.
10273263509Sdim  AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10274201361Srdivacky
10275201361Srdivacky  // If we found nothing, try to recover.
10276223017Sdim  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10277223017Sdim  // out if it fails.
10278245431Sdim  if (CandidateSet->empty()) {
10279226890Sdim    // In Microsoft mode, if we are inside a template class member function then
10280226890Sdim    // create a type dependent CallExpr. The goal is to postpone name lookup
10281226890Sdim    // to instantiation time to be able to search into type dependent base
10282226890Sdim    // classes.
10283235633Sdim    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
10284235633Sdim        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10285263509Sdim      CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10286245431Sdim                                            Context.DependentTy, VK_RValue,
10287245431Sdim                                            RParenLoc);
10288226890Sdim      CE->setTypeDependent(true);
10289245431Sdim      *Result = Owned(CE);
10290245431Sdim      return true;
10291226890Sdim    }
10292245431Sdim    return false;
10293245431Sdim  }
10294245431Sdim
10295245431Sdim  UnbridgedCasts.restore();
10296245431Sdim  return false;
10297245431Sdim}
10298245431Sdim
10299245431Sdim/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10300245431Sdim/// the completed call expression. If overload resolution fails, emits
10301245431Sdim/// diagnostics and returns ExprError()
10302245431Sdimstatic ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10303245431Sdim                                           UnresolvedLookupExpr *ULE,
10304245431Sdim                                           SourceLocation LParenLoc,
10305263509Sdim                                           MultiExprArg Args,
10306245431Sdim                                           SourceLocation RParenLoc,
10307245431Sdim                                           Expr *ExecConfig,
10308245431Sdim                                           OverloadCandidateSet *CandidateSet,
10309245431Sdim                                           OverloadCandidateSet::iterator *Best,
10310245431Sdim                                           OverloadingResult OverloadResult,
10311245431Sdim                                           bool AllowTypoCorrection) {
10312245431Sdim  if (CandidateSet->empty())
10313263509Sdim    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10314235633Sdim                                 RParenLoc, /*EmptyLookup=*/true,
10315235633Sdim                                 AllowTypoCorrection);
10316201361Srdivacky
10317245431Sdim  switch (OverloadResult) {
10318201361Srdivacky  case OR_Success: {
10319245431Sdim    FunctionDecl *FDecl = (*Best)->Function;
10320245431Sdim    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10321252723Sdim    if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10322252723Sdim      return ExprError();
10323245431Sdim    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10324263509Sdim    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10325263509Sdim                                         ExecConfig);
10326201361Srdivacky  }
10327193326Sed
10328223017Sdim  case OR_No_Viable_Function: {
10329223017Sdim    // Try to recover by looking for viable functions which the user might
10330223017Sdim    // have meant to call.
10331245431Sdim    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10332263509Sdim                                                Args, RParenLoc,
10333235633Sdim                                                /*EmptyLookup=*/false,
10334235633Sdim                                                AllowTypoCorrection);
10335223017Sdim    if (!Recovery.isInvalid())
10336223017Sdim      return Recovery;
10337223017Sdim
10338245431Sdim    SemaRef.Diag(Fn->getLocStart(),
10339193326Sed         diag::err_ovl_no_viable_function_in_call)
10340201361Srdivacky      << ULE->getName() << Fn->getSourceRange();
10341263509Sdim    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10342193326Sed    break;
10343223017Sdim  }
10344193326Sed
10345193326Sed  case OR_Ambiguous:
10346245431Sdim    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10347201361Srdivacky      << ULE->getName() << Fn->getSourceRange();
10348263509Sdim    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10349193326Sed    break;
10350193326Sed
10351245431Sdim  case OR_Deleted: {
10352245431Sdim    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10353245431Sdim      << (*Best)->Function->isDeleted()
10354245431Sdim      << ULE->getName()
10355245431Sdim      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10356245431Sdim      << Fn->getSourceRange();
10357263509Sdim    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10358235633Sdim
10359245431Sdim    // We emitted an error for the unvailable/deleted function call but keep
10360245431Sdim    // the call in the AST.
10361245431Sdim    FunctionDecl *FDecl = (*Best)->Function;
10362245431Sdim    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10363263509Sdim    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10364263509Sdim                                         ExecConfig);
10365193326Sed  }
10366245431Sdim  }
10367193326Sed
10368212904Sdim  // Overload resolution failed.
10369201361Srdivacky  return ExprError();
10370193326Sed}
10371193326Sed
10372245431Sdim/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10373245431Sdim/// (which eventually refers to the declaration Func) and the call
10374245431Sdim/// arguments Args/NumArgs, attempt to resolve the function call down
10375245431Sdim/// to a specific function. If overload resolution succeeds, returns
10376245431Sdim/// the call expression produced by overload resolution.
10377245431Sdim/// Otherwise, emits diagnostics and returns ExprError.
10378245431SdimExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10379245431Sdim                                         UnresolvedLookupExpr *ULE,
10380245431Sdim                                         SourceLocation LParenLoc,
10381263509Sdim                                         MultiExprArg Args,
10382245431Sdim                                         SourceLocation RParenLoc,
10383245431Sdim                                         Expr *ExecConfig,
10384245431Sdim                                         bool AllowTypoCorrection) {
10385245431Sdim  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10386245431Sdim  ExprResult result;
10387245431Sdim
10388263509Sdim  if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10389263509Sdim                             &result))
10390245431Sdim    return result;
10391245431Sdim
10392245431Sdim  OverloadCandidateSet::iterator Best;
10393245431Sdim  OverloadingResult OverloadResult =
10394245431Sdim      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10395245431Sdim
10396263509Sdim  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10397245431Sdim                                  RParenLoc, ExecConfig, &CandidateSet,
10398245431Sdim                                  &Best, OverloadResult,
10399245431Sdim                                  AllowTypoCorrection);
10400245431Sdim}
10401245431Sdim
10402203955Srdivackystatic bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10403199990Srdivacky  return Functions.size() > 1 ||
10404199990Srdivacky    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10405199990Srdivacky}
10406199990Srdivacky
10407193326Sed/// \brief Create a unary operation that may resolve to an overloaded
10408193326Sed/// operator.
10409193326Sed///
10410193326Sed/// \param OpLoc The location of the operator itself (e.g., '*').
10411193326Sed///
10412193326Sed/// \param OpcIn The UnaryOperator::Opcode that describes this
10413193326Sed/// operator.
10414193326Sed///
10415245431Sdim/// \param Fns The set of non-member functions that will be
10416193326Sed/// considered by overload resolution. The caller needs to build this
10417193326Sed/// set based on the context using, e.g.,
10418193326Sed/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10419193326Sed/// set should not contain any member functions; those will be added
10420193326Sed/// by CreateOverloadedUnaryOp().
10421193326Sed///
10422245431Sdim/// \param Input The input argument.
10423212904SdimExprResult
10424203955SrdivackySema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10425203955Srdivacky                              const UnresolvedSetImpl &Fns,
10426212904Sdim                              Expr *Input) {
10427193326Sed  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10428193326Sed
10429193326Sed  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10430193326Sed  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10431193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10432212904Sdim  // TODO: provide better source location info.
10433212904Sdim  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10434193326Sed
10435235633Sdim  if (checkPlaceholderForOverload(*this, Input))
10436235633Sdim    return ExprError();
10437218893Sdim
10438193326Sed  Expr *Args[2] = { Input, 0 };
10439193326Sed  unsigned NumArgs = 1;
10440198092Srdivacky
10441193326Sed  // For post-increment and post-decrement, add the implicit '0' as
10442193326Sed  // the second argument, so that we know this is a post-increment or
10443193326Sed  // post-decrement.
10444212904Sdim  if (Opc == UO_PostInc || Opc == UO_PostDec) {
10445193326Sed    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10446212904Sdim    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10447212904Sdim                                     SourceLocation());
10448193326Sed    NumArgs = 2;
10449193326Sed  }
10450193326Sed
10451252723Sdim  ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10452252723Sdim
10453193326Sed  if (Input->isTypeDependent()) {
10454210299Sed    if (Fns.empty())
10455212904Sdim      return Owned(new (Context) UnaryOperator(Input,
10456218893Sdim                                               Opc,
10457210299Sed                                               Context.DependentTy,
10458218893Sdim                                               VK_RValue, OK_Ordinary,
10459210299Sed                                               OpLoc));
10460218893Sdim
10461203955Srdivacky    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10462199990Srdivacky    UnresolvedLookupExpr *Fn
10463218893Sdim      = UnresolvedLookupExpr::Create(Context, NamingClass,
10464221345Sdim                                     NestedNameSpecifierLoc(), OpNameInfo,
10465208600Srdivacky                                     /*ADL*/ true, IsOverloaded(Fns),
10466208600Srdivacky                                     Fns.begin(), Fns.end());
10467252723Sdim    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
10468193326Sed                                                   Context.DependentTy,
10469218893Sdim                                                   VK_RValue,
10470245431Sdim                                                   OpLoc, false));
10471193326Sed  }
10472193326Sed
10473193326Sed  // Build an empty overload set.
10474203955Srdivacky  OverloadCandidateSet CandidateSet(OpLoc);
10475193326Sed
10476193326Sed  // Add the candidates from the given function set.
10477252723Sdim  AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10478193326Sed
10479193326Sed  // Add operator candidates that are member functions.
10480252723Sdim  AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10481193326Sed
10482203955Srdivacky  // Add candidates from ADL.
10483252723Sdim  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10484252723Sdim                                       ArgsArray, /*ExplicitTemplateArgs*/ 0,
10485203955Srdivacky                                       CandidateSet);
10486203955Srdivacky
10487193326Sed  // Add builtin operator candidates.
10488252723Sdim  AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10489193326Sed
10490226890Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10491226890Sdim
10492193326Sed  // Perform overload resolution.
10493193326Sed  OverloadCandidateSet::iterator Best;
10494212904Sdim  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10495193326Sed  case OR_Success: {
10496193326Sed    // We found a built-in operator or an overloaded operator.
10497193326Sed    FunctionDecl *FnDecl = Best->Function;
10498198092Srdivacky
10499193326Sed    if (FnDecl) {
10500193326Sed      // We matched an overloaded operator. Build a call to that
10501193326Sed      // operator.
10502198092Srdivacky
10503193326Sed      // Convert the arguments.
10504193326Sed      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10505205408Srdivacky        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10506203955Srdivacky
10507221345Sdim        ExprResult InputRes =
10508221345Sdim          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10509221345Sdim                                              Best->FoundDecl, Method);
10510221345Sdim        if (InputRes.isInvalid())
10511193326Sed          return ExprError();
10512221345Sdim        Input = InputRes.take();
10513193326Sed      } else {
10514193326Sed        // Convert the arguments.
10515212904Sdim        ExprResult InputInit
10516201361Srdivacky          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10517218893Sdim                                                      Context,
10518201361Srdivacky                                                      FnDecl->getParamDecl(0)),
10519218893Sdim                                      SourceLocation(),
10520212904Sdim                                      Input);
10521201361Srdivacky        if (InputInit.isInvalid())
10522193326Sed          return ExprError();
10523212904Sdim        Input = InputInit.take();
10524193326Sed      }
10525193326Sed
10526193326Sed      // Build the actual expression node.
10527252723Sdim      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10528235633Sdim                                                HadMultipleCandidates, OpLoc);
10529221345Sdim      if (FnExpr.isInvalid())
10530221345Sdim        return ExprError();
10531198092Srdivacky
10532263509Sdim      // Determine the result type.
10533263509Sdim      QualType ResultTy = FnDecl->getResultType();
10534263509Sdim      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10535263509Sdim      ResultTy = ResultTy.getNonLValueExprType(Context);
10536263509Sdim
10537199482Srdivacky      Args[0] = Input;
10538212904Sdim      CallExpr *TheCall =
10539252723Sdim        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
10540245431Sdim                                          ResultTy, VK, OpLoc, false);
10541208600Srdivacky
10542218893Sdim      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10543198092Srdivacky                              FnDecl))
10544198092Srdivacky        return ExprError();
10545198092Srdivacky
10546212904Sdim      return MaybeBindToTemporary(TheCall);
10547193326Sed    } else {
10548193326Sed      // We matched a built-in operator. Convert the arguments, then
10549193326Sed      // break out so that we will build the appropriate built-in
10550193326Sed      // operator node.
10551221345Sdim      ExprResult InputRes =
10552221345Sdim        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10553221345Sdim                                  Best->Conversions[0], AA_Passing);
10554221345Sdim      if (InputRes.isInvalid())
10555221345Sdim        return ExprError();
10556221345Sdim      Input = InputRes.take();
10557221345Sdim      break;
10558193326Sed    }
10559221345Sdim  }
10560193326Sed
10561221345Sdim  case OR_No_Viable_Function:
10562223017Sdim    // This is an erroneous use of an operator which can be overloaded by
10563223017Sdim    // a non-member function. Check for non-member operators which were
10564223017Sdim    // defined too late to be candidates.
10565252723Sdim    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10566223017Sdim      // FIXME: Recover by calling the found function.
10567223017Sdim      return ExprError();
10568223017Sdim
10569221345Sdim    // No viable function; fall through to handling this as a
10570221345Sdim    // built-in operator, which will produce an error message for us.
10571221345Sdim    break;
10572193326Sed
10573221345Sdim  case OR_Ambiguous:
10574221345Sdim    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10575193326Sed        << UnaryOperator::getOpcodeStr(Opc)
10576221345Sdim        << Input->getType()
10577193326Sed        << Input->getSourceRange();
10578252723Sdim    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10579221345Sdim                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10580221345Sdim    return ExprError();
10581193326Sed
10582221345Sdim  case OR_Deleted:
10583221345Sdim    Diag(OpLoc, diag::err_ovl_deleted_oper)
10584221345Sdim      << Best->Function->isDeleted()
10585221345Sdim      << UnaryOperator::getOpcodeStr(Opc)
10586221345Sdim      << getDeletedOrUnavailableSuffix(Best->Function)
10587221345Sdim      << Input->getSourceRange();
10588252723Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10589226890Sdim                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10590221345Sdim    return ExprError();
10591221345Sdim  }
10592221345Sdim
10593193326Sed  // Either we found no viable overloaded operator or we matched a
10594193326Sed  // built-in operator. In either case, fall through to trying to
10595193326Sed  // build a built-in operation.
10596212904Sdim  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10597193326Sed}
10598193326Sed
10599193326Sed/// \brief Create a binary operation that may resolve to an overloaded
10600193326Sed/// operator.
10601193326Sed///
10602193326Sed/// \param OpLoc The location of the operator itself (e.g., '+').
10603193326Sed///
10604193326Sed/// \param OpcIn The BinaryOperator::Opcode that describes this
10605193326Sed/// operator.
10606193326Sed///
10607245431Sdim/// \param Fns The set of non-member functions that will be
10608193326Sed/// considered by overload resolution. The caller needs to build this
10609193326Sed/// set based on the context using, e.g.,
10610193326Sed/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10611193326Sed/// set should not contain any member functions; those will be added
10612193326Sed/// by CreateOverloadedBinOp().
10613193326Sed///
10614193326Sed/// \param LHS Left-hand argument.
10615193326Sed/// \param RHS Right-hand argument.
10616212904SdimExprResult
10617193326SedSema::CreateOverloadedBinOp(SourceLocation OpLoc,
10618198092Srdivacky                            unsigned OpcIn,
10619203955Srdivacky                            const UnresolvedSetImpl &Fns,
10620193326Sed                            Expr *LHS, Expr *RHS) {
10621193326Sed  Expr *Args[2] = { LHS, RHS };
10622198092Srdivacky  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10623193326Sed
10624193326Sed  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10625193326Sed  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10626193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10627193326Sed
10628193326Sed  // If either side is type-dependent, create an appropriate dependent
10629193326Sed  // expression.
10630198092Srdivacky  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10631203955Srdivacky    if (Fns.empty()) {
10632218893Sdim      // If there are no functions to store, just build a dependent
10633198954Srdivacky      // BinaryOperator or CompoundAssignment.
10634212904Sdim      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10635198954Srdivacky        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10636218893Sdim                                                  Context.DependentTy,
10637218893Sdim                                                  VK_RValue, OK_Ordinary,
10638245431Sdim                                                  OpLoc,
10639245431Sdim                                                  FPFeatures.fp_contract));
10640218893Sdim
10641198954Srdivacky      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10642198954Srdivacky                                                        Context.DependentTy,
10643218893Sdim                                                        VK_LValue,
10644218893Sdim                                                        OK_Ordinary,
10645198954Srdivacky                                                        Context.DependentTy,
10646198954Srdivacky                                                        Context.DependentTy,
10647245431Sdim                                                        OpLoc,
10648245431Sdim                                                        FPFeatures.fp_contract));
10649198954Srdivacky    }
10650203955Srdivacky
10651203955Srdivacky    // FIXME: save results of ADL from here?
10652203955Srdivacky    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10653212904Sdim    // TODO: provide better source location info in DNLoc component.
10654212904Sdim    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10655199990Srdivacky    UnresolvedLookupExpr *Fn
10656221345Sdim      = UnresolvedLookupExpr::Create(Context, NamingClass,
10657221345Sdim                                     NestedNameSpecifierLoc(), OpNameInfo,
10658221345Sdim                                     /*ADL*/ true, IsOverloaded(Fns),
10659208600Srdivacky                                     Fns.begin(), Fns.end());
10660245431Sdim    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10661245431Sdim                                                Context.DependentTy, VK_RValue,
10662245431Sdim                                                OpLoc, FPFeatures.fp_contract));
10663193326Sed  }
10664193326Sed
10665235633Sdim  // Always do placeholder-like conversions on the RHS.
10666235633Sdim  if (checkPlaceholderForOverload(*this, Args[1]))
10667235633Sdim    return ExprError();
10668193326Sed
10669235633Sdim  // Do placeholder-like conversion on the LHS; note that we should
10670235633Sdim  // not get here with a PseudoObject LHS.
10671235633Sdim  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10672235633Sdim  if (checkPlaceholderForOverload(*this, Args[0]))
10673235633Sdim    return ExprError();
10674218893Sdim
10675199512Srdivacky  // If this is the assignment operator, we only perform overload resolution
10676199512Srdivacky  // if the left-hand side is a class or enumeration type. This is actually
10677199512Srdivacky  // a hack. The standard requires that we do overload resolution between the
10678199512Srdivacky  // various built-in candidates, but as DR507 points out, this can lead to
10679199512Srdivacky  // problems. So we do it this way, which pretty much follows what GCC does.
10680199512Srdivacky  // Note that we go the traditional code path for compound assignment forms.
10681212904Sdim  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10682198092Srdivacky    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10683193326Sed
10684218893Sdim  // If this is the .* operator, which is not overloadable, just
10685218893Sdim  // create a built-in binary operator.
10686218893Sdim  if (Opc == BO_PtrMemD)
10687218893Sdim    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10688218893Sdim
10689193326Sed  // Build an empty overload set.
10690203955Srdivacky  OverloadCandidateSet CandidateSet(OpLoc);
10691193326Sed
10692193326Sed  // Add the candidates from the given function set.
10693235633Sdim  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10694193326Sed
10695193326Sed  // Add operator candidates that are member functions.
10696252723Sdim  AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10697193326Sed
10698203955Srdivacky  // Add candidates from ADL.
10699203955Srdivacky  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10700235633Sdim                                       OpLoc, Args,
10701203955Srdivacky                                       /*ExplicitTemplateArgs*/ 0,
10702203955Srdivacky                                       CandidateSet);
10703203955Srdivacky
10704193326Sed  // Add builtin operator candidates.
10705252723Sdim  AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10706193326Sed
10707226890Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10708226890Sdim
10709193326Sed  // Perform overload resolution.
10710193326Sed  OverloadCandidateSet::iterator Best;
10711212904Sdim  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10712193326Sed    case OR_Success: {
10713193326Sed      // We found a built-in operator or an overloaded operator.
10714193326Sed      FunctionDecl *FnDecl = Best->Function;
10715193326Sed
10716193326Sed      if (FnDecl) {
10717193326Sed        // We matched an overloaded operator. Build a call to that
10718193326Sed        // operator.
10719193326Sed
10720193326Sed        // Convert the arguments.
10721193326Sed        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10722203955Srdivacky          // Best->Access is only meaningful for class members.
10723205408Srdivacky          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10724203955Srdivacky
10725218893Sdim          ExprResult Arg1 =
10726218893Sdim            PerformCopyInitialization(
10727218893Sdim              InitializedEntity::InitializeParameter(Context,
10728218893Sdim                                                     FnDecl->getParamDecl(0)),
10729218893Sdim              SourceLocation(), Owned(Args[1]));
10730201361Srdivacky          if (Arg1.isInvalid())
10731193326Sed            return ExprError();
10732201361Srdivacky
10733221345Sdim          ExprResult Arg0 =
10734221345Sdim            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10735221345Sdim                                                Best->FoundDecl, Method);
10736221345Sdim          if (Arg0.isInvalid())
10737201361Srdivacky            return ExprError();
10738221345Sdim          Args[0] = Arg0.takeAs<Expr>();
10739201361Srdivacky          Args[1] = RHS = Arg1.takeAs<Expr>();
10740193326Sed        } else {
10741193326Sed          // Convert the arguments.
10742218893Sdim          ExprResult Arg0 = PerformCopyInitialization(
10743218893Sdim            InitializedEntity::InitializeParameter(Context,
10744218893Sdim                                                   FnDecl->getParamDecl(0)),
10745218893Sdim            SourceLocation(), Owned(Args[0]));
10746201361Srdivacky          if (Arg0.isInvalid())
10747193326Sed            return ExprError();
10748201361Srdivacky
10749218893Sdim          ExprResult Arg1 =
10750218893Sdim            PerformCopyInitialization(
10751218893Sdim              InitializedEntity::InitializeParameter(Context,
10752218893Sdim                                                     FnDecl->getParamDecl(1)),
10753218893Sdim              SourceLocation(), Owned(Args[1]));
10754201361Srdivacky          if (Arg1.isInvalid())
10755201361Srdivacky            return ExprError();
10756201361Srdivacky          Args[0] = LHS = Arg0.takeAs<Expr>();
10757201361Srdivacky          Args[1] = RHS = Arg1.takeAs<Expr>();
10758193326Sed        }
10759193326Sed
10760193326Sed        // Build the actual expression node.
10761226890Sdim        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10762252723Sdim                                                  Best->FoundDecl,
10763226890Sdim                                                  HadMultipleCandidates, OpLoc);
10764221345Sdim        if (FnExpr.isInvalid())
10765221345Sdim          return ExprError();
10766193326Sed
10767263509Sdim        // Determine the result type.
10768263509Sdim        QualType ResultTy = FnDecl->getResultType();
10769263509Sdim        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10770263509Sdim        ResultTy = ResultTy.getNonLValueExprType(Context);
10771263509Sdim
10772212904Sdim        CXXOperatorCallExpr *TheCall =
10773221345Sdim          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10774245431Sdim                                            Args, ResultTy, VK, OpLoc,
10775245431Sdim                                            FPFeatures.fp_contract);
10776218893Sdim
10777218893Sdim        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10778198092Srdivacky                                FnDecl))
10779198092Srdivacky          return ExprError();
10780198092Srdivacky
10781252723Sdim        ArrayRef<const Expr *> ArgsArray(Args, 2);
10782252723Sdim        // Cut off the implicit 'this'.
10783252723Sdim        if (isa<CXXMethodDecl>(FnDecl))
10784252723Sdim          ArgsArray = ArgsArray.slice(1);
10785252723Sdim        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10786252723Sdim                  TheCall->getSourceRange(), VariadicDoesNotApply);
10787252723Sdim
10788212904Sdim        return MaybeBindToTemporary(TheCall);
10789193326Sed      } else {
10790193326Sed        // We matched a built-in operator. Convert the arguments, then
10791193326Sed        // break out so that we will build the appropriate built-in
10792193326Sed        // operator node.
10793221345Sdim        ExprResult ArgsRes0 =
10794221345Sdim          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10795221345Sdim                                    Best->Conversions[0], AA_Passing);
10796221345Sdim        if (ArgsRes0.isInvalid())
10797193326Sed          return ExprError();
10798221345Sdim        Args[0] = ArgsRes0.take();
10799193326Sed
10800221345Sdim        ExprResult ArgsRes1 =
10801221345Sdim          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10802221345Sdim                                    Best->Conversions[1], AA_Passing);
10803221345Sdim        if (ArgsRes1.isInvalid())
10804221345Sdim          return ExprError();
10805221345Sdim        Args[1] = ArgsRes1.take();
10806193326Sed        break;
10807193326Sed      }
10808193326Sed    }
10809193326Sed
10810198092Srdivacky    case OR_No_Viable_Function: {
10811198092Srdivacky      // C++ [over.match.oper]p9:
10812198092Srdivacky      //   If the operator is the operator , [...] and there are no
10813198092Srdivacky      //   viable functions, then the operator is assumed to be the
10814198092Srdivacky      //   built-in operator and interpreted according to clause 5.
10815212904Sdim      if (Opc == BO_Comma)
10816198092Srdivacky        break;
10817198092Srdivacky
10818218893Sdim      // For class as left operand for assignment or compound assigment
10819218893Sdim      // operator do not fall through to handling in built-in, but report that
10820218893Sdim      // no overloaded assignment operator found
10821212904Sdim      ExprResult Result = ExprError();
10822218893Sdim      if (Args[0]->getType()->isRecordType() &&
10823212904Sdim          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10824193326Sed        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10825193326Sed             << BinaryOperator::getOpcodeStr(Opc)
10826198092Srdivacky             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10827263509Sdim        if (Args[0]->getType()->isIncompleteType()) {
10828263509Sdim          Diag(OpLoc, diag::note_assign_lhs_incomplete)
10829263509Sdim            << Args[0]->getType()
10830263509Sdim            << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10831263509Sdim        }
10832198092Srdivacky      } else {
10833223017Sdim        // This is an erroneous use of an operator which can be overloaded by
10834223017Sdim        // a non-member function. Check for non-member operators which were
10835223017Sdim        // defined too late to be candidates.
10836235633Sdim        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10837223017Sdim          // FIXME: Recover by calling the found function.
10838223017Sdim          return ExprError();
10839223017Sdim
10840198092Srdivacky        // No viable function; try to create a built-in operation, which will
10841198092Srdivacky        // produce an error. Then, show the non-viable candidates.
10842198092Srdivacky        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10843193326Sed      }
10844218893Sdim      assert(Result.isInvalid() &&
10845198092Srdivacky             "C++ binary operator overloading is missing candidates!");
10846198092Srdivacky      if (Result.isInvalid())
10847235633Sdim        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10848212904Sdim                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10849245431Sdim      return Result;
10850198092Srdivacky    }
10851193326Sed
10852193326Sed    case OR_Ambiguous:
10853218893Sdim      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10854193326Sed          << BinaryOperator::getOpcodeStr(Opc)
10855218893Sdim          << Args[0]->getType() << Args[1]->getType()
10856198092Srdivacky          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10857235633Sdim      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10858212904Sdim                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10859193326Sed      return ExprError();
10860193326Sed
10861193326Sed    case OR_Deleted:
10862235633Sdim      if (isImplicitlyDeleted(Best->Function)) {
10863235633Sdim        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10864235633Sdim        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10865252723Sdim          << Context.getRecordType(Method->getParent())
10866252723Sdim          << getSpecialMember(Method);
10867235633Sdim
10868252723Sdim        // The user probably meant to call this special member. Just
10869252723Sdim        // explain why it's deleted.
10870252723Sdim        NoteDeletedFunction(Method);
10871252723Sdim        return ExprError();
10872235633Sdim      } else {
10873235633Sdim        Diag(OpLoc, diag::err_ovl_deleted_oper)
10874235633Sdim          << Best->Function->isDeleted()
10875235633Sdim          << BinaryOperator::getOpcodeStr(Opc)
10876235633Sdim          << getDeletedOrUnavailableSuffix(Best->Function)
10877235633Sdim          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10878235633Sdim      }
10879235633Sdim      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10880226890Sdim                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10881193326Sed      return ExprError();
10882202379Srdivacky  }
10883193326Sed
10884198092Srdivacky  // We matched a built-in operator; build it.
10885198092Srdivacky  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10886193326Sed}
10887193326Sed
10888212904SdimExprResult
10889198893SrdivackySema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10890198893Srdivacky                                         SourceLocation RLoc,
10891212904Sdim                                         Expr *Base, Expr *Idx) {
10892212904Sdim  Expr *Args[2] = { Base, Idx };
10893198893Srdivacky  DeclarationName OpName =
10894198893Srdivacky      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10895198893Srdivacky
10896198893Srdivacky  // If either side is type-dependent, create an appropriate dependent
10897198893Srdivacky  // expression.
10898198893Srdivacky  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10899198893Srdivacky
10900203955Srdivacky    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10901212904Sdim    // CHECKME: no 'operator' keyword?
10902212904Sdim    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10903212904Sdim    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10904199990Srdivacky    UnresolvedLookupExpr *Fn
10905218893Sdim      = UnresolvedLookupExpr::Create(Context, NamingClass,
10906221345Sdim                                     NestedNameSpecifierLoc(), OpNameInfo,
10907208600Srdivacky                                     /*ADL*/ true, /*Overloaded*/ false,
10908208600Srdivacky                                     UnresolvedSetIterator(),
10909208600Srdivacky                                     UnresolvedSetIterator());
10910199990Srdivacky    // Can't add any actual overloads yet
10911198893Srdivacky
10912198893Srdivacky    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10913245431Sdim                                                   Args,
10914198893Srdivacky                                                   Context.DependentTy,
10915218893Sdim                                                   VK_RValue,
10916245431Sdim                                                   RLoc, false));
10917198893Srdivacky  }
10918198893Srdivacky
10919235633Sdim  // Handle placeholders on both operands.
10920235633Sdim  if (checkPlaceholderForOverload(*this, Args[0]))
10921235633Sdim    return ExprError();
10922235633Sdim  if (checkPlaceholderForOverload(*this, Args[1]))
10923235633Sdim    return ExprError();
10924218893Sdim
10925198893Srdivacky  // Build an empty overload set.
10926203955Srdivacky  OverloadCandidateSet CandidateSet(LLoc);
10927198893Srdivacky
10928198893Srdivacky  // Subscript can only be overloaded as a member function.
10929198893Srdivacky
10930198893Srdivacky  // Add operator candidates that are member functions.
10931252723Sdim  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10932198893Srdivacky
10933198893Srdivacky  // Add builtin operator candidates.
10934252723Sdim  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10935198893Srdivacky
10936226890Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10937226890Sdim
10938198893Srdivacky  // Perform overload resolution.
10939198893Srdivacky  OverloadCandidateSet::iterator Best;
10940212904Sdim  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10941198893Srdivacky    case OR_Success: {
10942198893Srdivacky      // We found a built-in operator or an overloaded operator.
10943198893Srdivacky      FunctionDecl *FnDecl = Best->Function;
10944198893Srdivacky
10945198893Srdivacky      if (FnDecl) {
10946198893Srdivacky        // We matched an overloaded operator. Build a call to that
10947198893Srdivacky        // operator.
10948198893Srdivacky
10949205408Srdivacky        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10950203955Srdivacky
10951198893Srdivacky        // Convert the arguments.
10952198893Srdivacky        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10953221345Sdim        ExprResult Arg0 =
10954221345Sdim          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10955221345Sdim                                              Best->FoundDecl, Method);
10956221345Sdim        if (Arg0.isInvalid())
10957198893Srdivacky          return ExprError();
10958221345Sdim        Args[0] = Arg0.take();
10959198893Srdivacky
10960203955Srdivacky        // Convert the arguments.
10961212904Sdim        ExprResult InputInit
10962203955Srdivacky          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10963218893Sdim                                                      Context,
10964203955Srdivacky                                                      FnDecl->getParamDecl(0)),
10965218893Sdim                                      SourceLocation(),
10966203955Srdivacky                                      Owned(Args[1]));
10967203955Srdivacky        if (InputInit.isInvalid())
10968203955Srdivacky          return ExprError();
10969203955Srdivacky
10970203955Srdivacky        Args[1] = InputInit.takeAs<Expr>();
10971203955Srdivacky
10972198893Srdivacky        // Build the actual expression node.
10973235633Sdim        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10974235633Sdim        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10975226890Sdim        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10976252723Sdim                                                  Best->FoundDecl,
10977226890Sdim                                                  HadMultipleCandidates,
10978235633Sdim                                                  OpLocInfo.getLoc(),
10979235633Sdim                                                  OpLocInfo.getInfo());
10980221345Sdim        if (FnExpr.isInvalid())
10981221345Sdim          return ExprError();
10982198893Srdivacky
10983263509Sdim        // Determine the result type
10984263509Sdim        QualType ResultTy = FnDecl->getResultType();
10985263509Sdim        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10986263509Sdim        ResultTy = ResultTy.getNonLValueExprType(Context);
10987263509Sdim
10988212904Sdim        CXXOperatorCallExpr *TheCall =
10989212904Sdim          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10990245431Sdim                                            FnExpr.take(), Args,
10991245431Sdim                                            ResultTy, VK, RLoc,
10992245431Sdim                                            false);
10993198893Srdivacky
10994212904Sdim        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10995198893Srdivacky                                FnDecl))
10996198893Srdivacky          return ExprError();
10997198893Srdivacky
10998212904Sdim        return MaybeBindToTemporary(TheCall);
10999198893Srdivacky      } else {
11000198893Srdivacky        // We matched a built-in operator. Convert the arguments, then
11001198893Srdivacky        // break out so that we will build the appropriate built-in
11002198893Srdivacky        // operator node.
11003221345Sdim        ExprResult ArgsRes0 =
11004221345Sdim          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11005221345Sdim                                    Best->Conversions[0], AA_Passing);
11006221345Sdim        if (ArgsRes0.isInvalid())
11007198893Srdivacky          return ExprError();
11008221345Sdim        Args[0] = ArgsRes0.take();
11009198893Srdivacky
11010221345Sdim        ExprResult ArgsRes1 =
11011221345Sdim          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11012221345Sdim                                    Best->Conversions[1], AA_Passing);
11013221345Sdim        if (ArgsRes1.isInvalid())
11014221345Sdim          return ExprError();
11015221345Sdim        Args[1] = ArgsRes1.take();
11016221345Sdim
11017198893Srdivacky        break;
11018198893Srdivacky      }
11019198893Srdivacky    }
11020198893Srdivacky
11021198893Srdivacky    case OR_No_Viable_Function: {
11022202379Srdivacky      if (CandidateSet.empty())
11023202379Srdivacky        Diag(LLoc, diag::err_ovl_no_oper)
11024202379Srdivacky          << Args[0]->getType() << /*subscript*/ 0
11025202379Srdivacky          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11026202379Srdivacky      else
11027202379Srdivacky        Diag(LLoc, diag::err_ovl_no_viable_subscript)
11028202379Srdivacky          << Args[0]->getType()
11029202379Srdivacky          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11030235633Sdim      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11031212904Sdim                                  "[]", LLoc);
11032202379Srdivacky      return ExprError();
11033198893Srdivacky    }
11034198893Srdivacky
11035198893Srdivacky    case OR_Ambiguous:
11036218893Sdim      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11037218893Sdim          << "[]"
11038218893Sdim          << Args[0]->getType() << Args[1]->getType()
11039218893Sdim          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11040235633Sdim      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11041212904Sdim                                  "[]", LLoc);
11042198893Srdivacky      return ExprError();
11043198893Srdivacky
11044198893Srdivacky    case OR_Deleted:
11045198893Srdivacky      Diag(LLoc, diag::err_ovl_deleted_oper)
11046198893Srdivacky        << Best->Function->isDeleted() << "[]"
11047221345Sdim        << getDeletedOrUnavailableSuffix(Best->Function)
11048198893Srdivacky        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11049235633Sdim      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11050212904Sdim                                  "[]", LLoc);
11051198893Srdivacky      return ExprError();
11052198893Srdivacky    }
11053198893Srdivacky
11054198893Srdivacky  // We matched a built-in operator; build it.
11055212904Sdim  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11056198893Srdivacky}
11057198893Srdivacky
11058193326Sed/// BuildCallToMemberFunction - Build a call to a member
11059193326Sed/// function. MemExpr is the expression that refers to the member
11060193326Sed/// function (and includes the object parameter), Args/NumArgs are the
11061193326Sed/// arguments to the function call (not including the object
11062193326Sed/// parameter). The caller needs to validate that the member
11063221345Sdim/// expression refers to a non-static member function or an overloaded
11064221345Sdim/// member function.
11065212904SdimExprResult
11066198092SrdivackySema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11067263509Sdim                                SourceLocation LParenLoc,
11068263509Sdim                                MultiExprArg Args,
11069263509Sdim                                SourceLocation RParenLoc) {
11070221345Sdim  assert(MemExprE->getType() == Context.BoundMemberTy ||
11071221345Sdim         MemExprE->getType() == Context.OverloadTy);
11072221345Sdim
11073193326Sed  // Dig out the member expression. This holds both the object
11074193326Sed  // argument and the member function we're referring to.
11075199990Srdivacky  Expr *NakedMemExpr = MemExprE->IgnoreParens();
11076218893Sdim
11077221345Sdim  // Determine whether this is a call to a pointer-to-member function.
11078221345Sdim  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11079221345Sdim    assert(op->getType() == Context.BoundMemberTy);
11080221345Sdim    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11081221345Sdim
11082221345Sdim    QualType fnType =
11083221345Sdim      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11084221345Sdim
11085221345Sdim    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11086221345Sdim    QualType resultType = proto->getCallResultType(Context);
11087221345Sdim    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
11088221345Sdim
11089221345Sdim    // Check that the object type isn't more qualified than the
11090221345Sdim    // member function we're calling.
11091221345Sdim    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11092221345Sdim
11093221345Sdim    QualType objectType = op->getLHS()->getType();
11094221345Sdim    if (op->getOpcode() == BO_PtrMemI)
11095221345Sdim      objectType = objectType->castAs<PointerType>()->getPointeeType();
11096221345Sdim    Qualifiers objectQuals = objectType.getQualifiers();
11097221345Sdim
11098221345Sdim    Qualifiers difference = objectQuals - funcQuals;
11099221345Sdim    difference.removeObjCGCAttr();
11100221345Sdim    difference.removeAddressSpace();
11101221345Sdim    if (difference) {
11102221345Sdim      std::string qualsString = difference.getAsString();
11103221345Sdim      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11104221345Sdim        << fnType.getUnqualifiedType()
11105221345Sdim        << qualsString
11106221345Sdim        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11107221345Sdim    }
11108221345Sdim
11109221345Sdim    CXXMemberCallExpr *call
11110263509Sdim      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11111221345Sdim                                        resultType, valueKind, RParenLoc);
11112221345Sdim
11113221345Sdim    if (CheckCallReturnType(proto->getResultType(),
11114235633Sdim                            op->getRHS()->getLocStart(),
11115221345Sdim                            call, 0))
11116221345Sdim      return ExprError();
11117221345Sdim
11118263509Sdim    if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
11119221345Sdim      return ExprError();
11120221345Sdim
11121263509Sdim    if (CheckOtherCall(call, proto))
11122263509Sdim      return ExprError();
11123263509Sdim
11124221345Sdim    return MaybeBindToTemporary(call);
11125221345Sdim  }
11126221345Sdim
11127235633Sdim  UnbridgedCastsSet UnbridgedCasts;
11128263509Sdim  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11129235633Sdim    return ExprError();
11130235633Sdim
11131199990Srdivacky  MemberExpr *MemExpr;
11132193326Sed  CXXMethodDecl *Method = 0;
11133207619Srdivacky  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
11134204793Srdivacky  NestedNameSpecifier *Qualifier = 0;
11135199990Srdivacky  if (isa<MemberExpr>(NakedMemExpr)) {
11136199990Srdivacky    MemExpr = cast<MemberExpr>(NakedMemExpr);
11137199990Srdivacky    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11138206084Srdivacky    FoundDecl = MemExpr->getFoundDecl();
11139204793Srdivacky    Qualifier = MemExpr->getQualifier();
11140235633Sdim    UnbridgedCasts.restore();
11141199990Srdivacky  } else {
11142199990Srdivacky    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11143204793Srdivacky    Qualifier = UnresExpr->getQualifier();
11144218893Sdim
11145200583Srdivacky    QualType ObjectType = UnresExpr->getBaseType();
11146218893Sdim    Expr::Classification ObjectClassification
11147218893Sdim      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11148218893Sdim                            : UnresExpr->getBase()->Classify(Context);
11149200583Srdivacky
11150193326Sed    // Add overload candidates
11151203955Srdivacky    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
11152198092Srdivacky
11153200583Srdivacky    // FIXME: avoid copy.
11154200583Srdivacky    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11155200583Srdivacky    if (UnresExpr->hasExplicitTemplateArgs()) {
11156200583Srdivacky      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11157200583Srdivacky      TemplateArgs = &TemplateArgsBuffer;
11158200583Srdivacky    }
11159200583Srdivacky
11160199990Srdivacky    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11161199990Srdivacky           E = UnresExpr->decls_end(); I != E; ++I) {
11162199990Srdivacky
11163200583Srdivacky      NamedDecl *Func = *I;
11164200583Srdivacky      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11165200583Srdivacky      if (isa<UsingShadowDecl>(Func))
11166200583Srdivacky        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11167200583Srdivacky
11168218893Sdim
11169218893Sdim      // Microsoft supports direct constructor calls.
11170235633Sdim      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11171235633Sdim        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11172263509Sdim                             Args, CandidateSet);
11173218893Sdim      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11174198893Srdivacky        // If explicit template arguments were provided, we can't call a
11175198893Srdivacky        // non-template member function.
11176200583Srdivacky        if (TemplateArgs)
11177198893Srdivacky          continue;
11178218893Sdim
11179205408Srdivacky        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11180263509Sdim                           ObjectClassification, Args, CandidateSet,
11181218893Sdim                           /*SuppressUserConversions=*/false);
11182199990Srdivacky      } else {
11183199990Srdivacky        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11184205408Srdivacky                                   I.getPair(), ActingDC, TemplateArgs,
11185218893Sdim                                   ObjectType,  ObjectClassification,
11186263509Sdim                                   Args, CandidateSet,
11187198092Srdivacky                                   /*SuppressUsedConversions=*/false);
11188199990Srdivacky      }
11189193326Sed    }
11190193326Sed
11191199990Srdivacky    DeclarationName DeclName = UnresExpr->getMemberName();
11192199990Srdivacky
11193235633Sdim    UnbridgedCasts.restore();
11194235633Sdim
11195193326Sed    OverloadCandidateSet::iterator Best;
11196212904Sdim    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11197218893Sdim                                            Best)) {
11198193326Sed    case OR_Success:
11199193326Sed      Method = cast<CXXMethodDecl>(Best->Function);
11200206084Srdivacky      FoundDecl = Best->FoundDecl;
11201205408Srdivacky      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11202252723Sdim      if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11203252723Sdim        return ExprError();
11204263509Sdim      // If FoundDecl is different from Method (such as if one is a template
11205263509Sdim      // and the other a specialization), make sure DiagnoseUseOfDecl is
11206263509Sdim      // called on both.
11207263509Sdim      // FIXME: This would be more comprehensively addressed by modifying
11208263509Sdim      // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11209263509Sdim      // being used.
11210263509Sdim      if (Method != FoundDecl.getDecl() &&
11211263509Sdim                      DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11212263509Sdim        return ExprError();
11213193326Sed      break;
11214193326Sed
11215193326Sed    case OR_No_Viable_Function:
11216199990Srdivacky      Diag(UnresExpr->getMemberLoc(),
11217193326Sed           diag::err_ovl_no_viable_member_function_in_call)
11218198092Srdivacky        << DeclName << MemExprE->getSourceRange();
11219263509Sdim      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11220193326Sed      // FIXME: Leaking incoming expressions!
11221200583Srdivacky      return ExprError();
11222193326Sed
11223193326Sed    case OR_Ambiguous:
11224199990Srdivacky      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11225198092Srdivacky        << DeclName << MemExprE->getSourceRange();
11226263509Sdim      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11227193326Sed      // FIXME: Leaking incoming expressions!
11228200583Srdivacky      return ExprError();
11229193326Sed
11230193326Sed    case OR_Deleted:
11231199990Srdivacky      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11232193326Sed        << Best->Function->isDeleted()
11233219077Sdim        << DeclName
11234221345Sdim        << getDeletedOrUnavailableSuffix(Best->Function)
11235219077Sdim        << MemExprE->getSourceRange();
11236263509Sdim      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11237193326Sed      // FIXME: Leaking incoming expressions!
11238200583Srdivacky      return ExprError();
11239193326Sed    }
11240193326Sed
11241206084Srdivacky    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11242200583Srdivacky
11243200583Srdivacky    // If overload resolution picked a static member, build a
11244200583Srdivacky    // non-member call based on that function.
11245200583Srdivacky    if (Method->isStatic()) {
11246263509Sdim      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11247263509Sdim                                   RParenLoc);
11248200583Srdivacky    }
11249200583Srdivacky
11250199990Srdivacky    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11251193326Sed  }
11252193326Sed
11253218893Sdim  QualType ResultType = Method->getResultType();
11254218893Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultType);
11255218893Sdim  ResultType = ResultType.getNonLValueExprType(Context);
11256218893Sdim
11257193326Sed  assert(Method && "Member call to something that isn't a method?");
11258218893Sdim  CXXMemberCallExpr *TheCall =
11259263509Sdim    new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11260218893Sdim                                    ResultType, VK, RParenLoc);
11261193326Sed
11262198092Srdivacky  // Check for a valid return type.
11263218893Sdim  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
11264212904Sdim                          TheCall, Method))
11265200583Srdivacky    return ExprError();
11266218893Sdim
11267193326Sed  // Convert the object argument (for a non-static member function call).
11268206084Srdivacky  // We only need to do this if there was actually an overload; otherwise
11269206084Srdivacky  // it was done at lookup.
11270221345Sdim  if (!Method->isStatic()) {
11271221345Sdim    ExprResult ObjectArg =
11272221345Sdim      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11273221345Sdim                                          FoundDecl, Method);
11274221345Sdim    if (ObjectArg.isInvalid())
11275221345Sdim      return ExprError();
11276221345Sdim    MemExpr->setBase(ObjectArg.take());
11277221345Sdim  }
11278193326Sed
11279193326Sed  // Convert the rest of the arguments
11280218893Sdim  const FunctionProtoType *Proto =
11281218893Sdim    Method->getType()->getAs<FunctionProtoType>();
11282263509Sdim  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11283193326Sed                              RParenLoc))
11284200583Srdivacky    return ExprError();
11285193326Sed
11286263509Sdim  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11287235633Sdim
11288245431Sdim  if (CheckFunctionCall(Method, TheCall, Proto))
11289200583Srdivacky    return ExprError();
11290198092Srdivacky
11291223017Sdim  if ((isa<CXXConstructorDecl>(CurContext) ||
11292223017Sdim       isa<CXXDestructorDecl>(CurContext)) &&
11293223017Sdim      TheCall->getMethodDecl()->isPure()) {
11294223017Sdim    const CXXMethodDecl *MD = TheCall->getMethodDecl();
11295223017Sdim
11296224145Sdim    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11297223017Sdim      Diag(MemExpr->getLocStart(),
11298223017Sdim           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11299223017Sdim        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11300223017Sdim        << MD->getParent()->getDeclName();
11301223017Sdim
11302223017Sdim      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11303224145Sdim    }
11304223017Sdim  }
11305212904Sdim  return MaybeBindToTemporary(TheCall);
11306193326Sed}
11307193326Sed
11308193326Sed/// BuildCallToObjectOfClassType - Build a call to an object of class
11309193326Sed/// type (C++ [over.call.object]), which can end up invoking an
11310193326Sed/// overloaded function call operator (@c operator()) or performing a
11311193326Sed/// user-defined conversion on the object argument.
11312212904SdimExprResult
11313221345SdimSema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11314193326Sed                                   SourceLocation LParenLoc,
11315263509Sdim                                   MultiExprArg Args,
11316193326Sed                                   SourceLocation RParenLoc) {
11317235633Sdim  if (checkPlaceholderForOverload(*this, Obj))
11318235633Sdim    return ExprError();
11319221345Sdim  ExprResult Object = Owned(Obj);
11320218893Sdim
11321235633Sdim  UnbridgedCastsSet UnbridgedCasts;
11322263509Sdim  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11323235633Sdim    return ExprError();
11324235633Sdim
11325221345Sdim  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11326221345Sdim  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11327198092Srdivacky
11328193326Sed  // C++ [over.call.object]p1:
11329193326Sed  //  If the primary-expression E in the function call syntax
11330198092Srdivacky  //  evaluates to a class object of type "cv T", then the set of
11331193326Sed  //  candidate functions includes at least the function call
11332193326Sed  //  operators of T. The function call operators of T are obtained by
11333193326Sed  //  ordinary lookup of the name operator() in the context of
11334193326Sed  //  (E).operator().
11335203955Srdivacky  OverloadCandidateSet CandidateSet(LParenLoc);
11336193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11337193326Sed
11338221345Sdim  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11339245431Sdim                          diag::err_incomplete_object_call, Object.get()))
11340198398Srdivacky    return true;
11341218893Sdim
11342199482Srdivacky  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11343199482Srdivacky  LookupQualifiedName(R, Record->getDecl());
11344199482Srdivacky  R.suppressDiagnostics();
11345199482Srdivacky
11346199482Srdivacky  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11347199482Srdivacky       Oper != OperEnd; ++Oper) {
11348221345Sdim    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11349263509Sdim                       Object.get()->Classify(Context),
11350263509Sdim                       Args, CandidateSet,
11351199482Srdivacky                       /*SuppressUserConversions=*/ false);
11352199482Srdivacky  }
11353218893Sdim
11354193326Sed  // C++ [over.call.object]p2:
11355226890Sdim  //   In addition, for each (non-explicit in C++0x) conversion function
11356226890Sdim  //   declared in T of the form
11357193326Sed  //
11358193326Sed  //        operator conversion-type-id () cv-qualifier;
11359193326Sed  //
11360193326Sed  //   where cv-qualifier is the same cv-qualification as, or a
11361193326Sed  //   greater cv-qualification than, cv, and where conversion-type-id
11362193326Sed  //   denotes the type "pointer to function of (P1,...,Pn) returning
11363193326Sed  //   R", or the type "reference to pointer to function of
11364193326Sed  //   (P1,...,Pn) returning R", or the type "reference to function
11365193326Sed  //   of (P1,...,Pn) returning R", a surrogate call function [...]
11366193326Sed  //   is also considered as a candidate function. Similarly,
11367193326Sed  //   surrogate call functions are added to the set of candidate
11368193326Sed  //   functions for each conversion function declared in an
11369193326Sed  //   accessible base class provided the function is not hidden
11370193326Sed  //   within T by another intervening declaration.
11371252723Sdim  std::pair<CXXRecordDecl::conversion_iterator,
11372252723Sdim            CXXRecordDecl::conversion_iterator> Conversions
11373202379Srdivacky    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11374252723Sdim  for (CXXRecordDecl::conversion_iterator
11375252723Sdim         I = Conversions.first, E = Conversions.second; I != E; ++I) {
11376200583Srdivacky    NamedDecl *D = *I;
11377200583Srdivacky    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11378200583Srdivacky    if (isa<UsingShadowDecl>(D))
11379200583Srdivacky      D = cast<UsingShadowDecl>(D)->getTargetDecl();
11380218893Sdim
11381198398Srdivacky    // Skip over templated conversion functions; they aren't
11382198398Srdivacky    // surrogates.
11383200583Srdivacky    if (isa<FunctionTemplateDecl>(D))
11384198398Srdivacky      continue;
11385193326Sed
11386200583Srdivacky    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11387226890Sdim    if (!Conv->isExplicit()) {
11388226890Sdim      // Strip the reference type (if any) and then the pointer type (if
11389226890Sdim      // any) to get down to what might be a function type.
11390226890Sdim      QualType ConvType = Conv->getConversionType().getNonReferenceType();
11391226890Sdim      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11392226890Sdim        ConvType = ConvPtrType->getPointeeType();
11393199990Srdivacky
11394226890Sdim      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11395226890Sdim      {
11396226890Sdim        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11397263509Sdim                              Object.get(), Args, CandidateSet);
11398226890Sdim      }
11399226890Sdim    }
11400193326Sed  }
11401193326Sed
11402226890Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11403226890Sdim
11404193326Sed  // Perform overload resolution.
11405193326Sed  OverloadCandidateSet::iterator Best;
11406221345Sdim  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11407212904Sdim                             Best)) {
11408193326Sed  case OR_Success:
11409193326Sed    // Overload resolution succeeded; we'll build the appropriate call
11410193326Sed    // below.
11411193326Sed    break;
11412193326Sed
11413193326Sed  case OR_No_Viable_Function:
11414202379Srdivacky    if (CandidateSet.empty())
11415235633Sdim      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11416221345Sdim        << Object.get()->getType() << /*call*/ 1
11417221345Sdim        << Object.get()->getSourceRange();
11418202379Srdivacky    else
11419235633Sdim      Diag(Object.get()->getLocStart(),
11420202379Srdivacky           diag::err_ovl_no_viable_object_call)
11421221345Sdim        << Object.get()->getType() << Object.get()->getSourceRange();
11422263509Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11423193326Sed    break;
11424193326Sed
11425193326Sed  case OR_Ambiguous:
11426235633Sdim    Diag(Object.get()->getLocStart(),
11427193326Sed         diag::err_ovl_ambiguous_object_call)
11428221345Sdim      << Object.get()->getType() << Object.get()->getSourceRange();
11429263509Sdim    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11430193326Sed    break;
11431193326Sed
11432193326Sed  case OR_Deleted:
11433235633Sdim    Diag(Object.get()->getLocStart(),
11434193326Sed         diag::err_ovl_deleted_object_call)
11435193326Sed      << Best->Function->isDeleted()
11436221345Sdim      << Object.get()->getType()
11437221345Sdim      << getDeletedOrUnavailableSuffix(Best->Function)
11438221345Sdim      << Object.get()->getSourceRange();
11439263509Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11440193326Sed    break;
11441198092Srdivacky  }
11442193326Sed
11443212904Sdim  if (Best == CandidateSet.end())
11444193326Sed    return true;
11445193326Sed
11446235633Sdim  UnbridgedCasts.restore();
11447235633Sdim
11448193326Sed  if (Best->Function == 0) {
11449193326Sed    // Since there is no function declaration, this is one of the
11450193326Sed    // surrogate candidates. Dig out the conversion function.
11451198092Srdivacky    CXXConversionDecl *Conv
11452193326Sed      = cast<CXXConversionDecl>(
11453193326Sed                         Best->Conversions[0].UserDefined.ConversionFunction);
11454193326Sed
11455221345Sdim    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11456252723Sdim    if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11457252723Sdim      return ExprError();
11458263509Sdim    assert(Conv == Best->FoundDecl.getDecl() &&
11459263509Sdim             "Found Decl & conversion-to-functionptr should be same, right?!");
11460193326Sed    // We selected one of the surrogate functions that converts the
11461193326Sed    // object parameter to a function pointer. Perform the conversion
11462193326Sed    // on the object argument, then let ActOnCallExpr finish the job.
11463218893Sdim
11464198092Srdivacky    // Create an implicit member expr to refer to the conversion operator.
11465198092Srdivacky    // and then call it.
11466226890Sdim    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11467226890Sdim                                             Conv, HadMultipleCandidates);
11468218893Sdim    if (Call.isInvalid())
11469218893Sdim      return ExprError();
11470235633Sdim    // Record usage of conversion in an implicit cast.
11471235633Sdim    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11472235633Sdim                                          CK_UserDefinedConversion,
11473235633Sdim                                          Call.get(), 0, VK_RValue));
11474218893Sdim
11475263509Sdim    return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11476193326Sed  }
11477193326Sed
11478221345Sdim  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11479203955Srdivacky
11480193326Sed  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11481193326Sed  // that calls this method, using Object for the implicit object
11482193326Sed  // parameter and passing along the remaining arguments.
11483193326Sed  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11484245431Sdim
11485245431Sdim  // An error diagnostic has already been printed when parsing the declaration.
11486245431Sdim  if (Method->isInvalidDecl())
11487245431Sdim    return ExprError();
11488245431Sdim
11489218893Sdim  const FunctionProtoType *Proto =
11490218893Sdim    Method->getType()->getAs<FunctionProtoType>();
11491193326Sed
11492193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
11493193326Sed
11494235633Sdim  DeclarationNameInfo OpLocInfo(
11495235633Sdim               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11496235633Sdim  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11497252723Sdim  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11498235633Sdim                                           HadMultipleCandidates,
11499235633Sdim                                           OpLocInfo.getLoc(),
11500235633Sdim                                           OpLocInfo.getInfo());
11501221345Sdim  if (NewFn.isInvalid())
11502221345Sdim    return true;
11503193326Sed
11504263509Sdim  // Build the full argument list for the method call (the implicit object
11505263509Sdim  // parameter is placed at the beginning of the list).
11506263509Sdim  llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11507263509Sdim  MethodArgs[0] = Object.get();
11508263509Sdim  std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11509263509Sdim
11510193326Sed  // Once we've built TheCall, all of the expressions are properly
11511193326Sed  // owned.
11512218893Sdim  QualType ResultTy = Method->getResultType();
11513218893Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11514218893Sdim  ResultTy = ResultTy.getNonLValueExprType(Context);
11515218893Sdim
11516263509Sdim  CXXOperatorCallExpr *TheCall = new (Context)
11517263509Sdim      CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11518263509Sdim                          llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11519263509Sdim                          ResultTy, VK, RParenLoc, false);
11520263509Sdim  MethodArgs.reset();
11521193326Sed
11522218893Sdim  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11523198092Srdivacky                          Method))
11524198092Srdivacky    return true;
11525218893Sdim
11526193326Sed  // We may have default arguments. If so, we need to allocate more
11527193326Sed  // slots in the call for them.
11528263509Sdim  if (Args.size() < NumArgsInProto)
11529193326Sed    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11530193326Sed
11531193326Sed  bool IsError = false;
11532193326Sed
11533193326Sed  // Initialize the implicit object parameter.
11534221345Sdim  ExprResult ObjRes =
11535221345Sdim    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11536221345Sdim                                        Best->FoundDecl, Method);
11537221345Sdim  if (ObjRes.isInvalid())
11538221345Sdim    IsError = true;
11539221345Sdim  else
11540245431Sdim    Object = ObjRes;
11541221345Sdim  TheCall->setArg(0, Object.take());
11542193326Sed
11543193326Sed  // Check the argument types.
11544263509Sdim  for (unsigned i = 0; i != NumArgsInProto; i++) {
11545193326Sed    Expr *Arg;
11546263509Sdim    if (i < Args.size()) {
11547193326Sed      Arg = Args[i];
11548198092Srdivacky
11549193326Sed      // Pass the argument.
11550203955Srdivacky
11551212904Sdim      ExprResult InputInit
11552203955Srdivacky        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11553218893Sdim                                                    Context,
11554203955Srdivacky                                                    Method->getParamDecl(i)),
11555212904Sdim                                    SourceLocation(), Arg);
11556218893Sdim
11557203955Srdivacky      IsError |= InputInit.isInvalid();
11558203955Srdivacky      Arg = InputInit.takeAs<Expr>();
11559193326Sed    } else {
11560212904Sdim      ExprResult DefArg
11561199482Srdivacky        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11562199482Srdivacky      if (DefArg.isInvalid()) {
11563199482Srdivacky        IsError = true;
11564199482Srdivacky        break;
11565199482Srdivacky      }
11566218893Sdim
11567199482Srdivacky      Arg = DefArg.takeAs<Expr>();
11568193326Sed    }
11569193326Sed
11570193326Sed    TheCall->setArg(i + 1, Arg);
11571193326Sed  }
11572193326Sed
11573193326Sed  // If this is a variadic call, handle args passed through "...".
11574193326Sed  if (Proto->isVariadic()) {
11575193326Sed    // Promote the arguments (C99 6.5.2.2p7).
11576263509Sdim    for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
11577221345Sdim      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11578221345Sdim      IsError |= Arg.isInvalid();
11579221345Sdim      TheCall->setArg(i + 1, Arg.take());
11580193326Sed    }
11581193326Sed  }
11582193326Sed
11583193326Sed  if (IsError) return true;
11584193326Sed
11585263509Sdim  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11586235633Sdim
11587245431Sdim  if (CheckFunctionCall(Method, TheCall, Proto))
11588198092Srdivacky    return true;
11589198092Srdivacky
11590212904Sdim  return MaybeBindToTemporary(TheCall);
11591193326Sed}
11592193326Sed
11593193326Sed/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11594198092Srdivacky///  (if one exists), where @c Base is an expression of class type and
11595193326Sed/// @c Member is the name of the member we're trying to find.
11596212904SdimExprResult
11597263509SdimSema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11598263509Sdim                               bool *NoArrowOperatorFound) {
11599218893Sdim  assert(Base->getType()->isRecordType() &&
11600218893Sdim         "left-hand side must have class type");
11601198092Srdivacky
11602235633Sdim  if (checkPlaceholderForOverload(*this, Base))
11603235633Sdim    return ExprError();
11604218893Sdim
11605203955Srdivacky  SourceLocation Loc = Base->getExprLoc();
11606203955Srdivacky
11607193326Sed  // C++ [over.ref]p1:
11608193326Sed  //
11609193326Sed  //   [...] An expression x->m is interpreted as (x.operator->())->m
11610193326Sed  //   for a class object x of type T if T::operator->() exists and if
11611193326Sed  //   the operator is selected as the best match function by the
11612193326Sed  //   overload resolution mechanism (13.3).
11613218893Sdim  DeclarationName OpName =
11614218893Sdim    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11615203955Srdivacky  OverloadCandidateSet CandidateSet(Loc);
11616198092Srdivacky  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11617198092Srdivacky
11618203955Srdivacky  if (RequireCompleteType(Loc, Base->getType(),
11619245431Sdim                          diag::err_typecheck_incomplete_tag, Base))
11620199482Srdivacky    return ExprError();
11621198092Srdivacky
11622199482Srdivacky  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11623199482Srdivacky  LookupQualifiedName(R, BaseRecord->getDecl());
11624199482Srdivacky  R.suppressDiagnostics();
11625199482Srdivacky
11626198092Srdivacky  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11627200583Srdivacky       Oper != OperEnd; ++Oper) {
11628218893Sdim    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11629252723Sdim                       None, CandidateSet, /*SuppressUserConversions=*/false);
11630200583Srdivacky  }
11631193326Sed
11632226890Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11633226890Sdim
11634193326Sed  // Perform overload resolution.
11635193326Sed  OverloadCandidateSet::iterator Best;
11636212904Sdim  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11637193326Sed  case OR_Success:
11638193326Sed    // Overload resolution succeeded; we'll build the call below.
11639193326Sed    break;
11640193326Sed
11641193326Sed  case OR_No_Viable_Function:
11642263509Sdim    if (CandidateSet.empty()) {
11643263509Sdim      QualType BaseType = Base->getType();
11644263509Sdim      if (NoArrowOperatorFound) {
11645263509Sdim        // Report this specific error to the caller instead of emitting a
11646263509Sdim        // diagnostic, as requested.
11647263509Sdim        *NoArrowOperatorFound = true;
11648263509Sdim        return ExprError();
11649263509Sdim      }
11650193326Sed      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11651263509Sdim        << BaseType << Base->getSourceRange();
11652263509Sdim      if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11653263509Sdim        Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11654263509Sdim          << FixItHint::CreateReplacement(OpLoc, ".");
11655263509Sdim      }
11656263509Sdim    } else
11657193326Sed      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11658198092Srdivacky        << "operator->" << Base->getSourceRange();
11659235633Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11660198092Srdivacky    return ExprError();
11661193326Sed
11662193326Sed  case OR_Ambiguous:
11663218893Sdim    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11664218893Sdim      << "->" << Base->getType() << Base->getSourceRange();
11665235633Sdim    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11666198092Srdivacky    return ExprError();
11667193326Sed
11668193326Sed  case OR_Deleted:
11669193326Sed    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11670193326Sed      << Best->Function->isDeleted()
11671219077Sdim      << "->"
11672221345Sdim      << getDeletedOrUnavailableSuffix(Best->Function)
11673219077Sdim      << Base->getSourceRange();
11674235633Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11675198092Srdivacky    return ExprError();
11676193326Sed  }
11677193326Sed
11678205408Srdivacky  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11679205408Srdivacky
11680193326Sed  // Convert the object parameter.
11681193326Sed  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11682221345Sdim  ExprResult BaseResult =
11683221345Sdim    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11684221345Sdim                                        Best->FoundDecl, Method);
11685221345Sdim  if (BaseResult.isInvalid())
11686198092Srdivacky    return ExprError();
11687221345Sdim  Base = BaseResult.take();
11688193326Sed
11689193326Sed  // Build the operator call.
11690252723Sdim  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11691235633Sdim                                            HadMultipleCandidates, OpLoc);
11692221345Sdim  if (FnExpr.isInvalid())
11693221345Sdim    return ExprError();
11694218893Sdim
11695218893Sdim  QualType ResultTy = Method->getResultType();
11696218893Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11697218893Sdim  ResultTy = ResultTy.getNonLValueExprType(Context);
11698212904Sdim  CXXOperatorCallExpr *TheCall =
11699221345Sdim    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11700245431Sdim                                      Base, ResultTy, VK, OpLoc, false);
11701198092Srdivacky
11702218893Sdim  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11703198092Srdivacky                          Method))
11704198092Srdivacky          return ExprError();
11705221345Sdim
11706221345Sdim  return MaybeBindToTemporary(TheCall);
11707193326Sed}
11708193326Sed
11709235633Sdim/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11710235633Sdim/// a literal operator described by the provided lookup results.
11711235633SdimExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11712235633Sdim                                          DeclarationNameInfo &SuffixInfo,
11713235633Sdim                                          ArrayRef<Expr*> Args,
11714235633Sdim                                          SourceLocation LitEndLoc,
11715235633Sdim                                       TemplateArgumentListInfo *TemplateArgs) {
11716235633Sdim  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11717235633Sdim
11718235633Sdim  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11719235633Sdim  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11720235633Sdim                        TemplateArgs);
11721235633Sdim
11722235633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11723235633Sdim
11724235633Sdim  // Perform overload resolution. This will usually be trivial, but might need
11725235633Sdim  // to perform substitutions for a literal operator template.
11726235633Sdim  OverloadCandidateSet::iterator Best;
11727235633Sdim  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11728235633Sdim  case OR_Success:
11729235633Sdim  case OR_Deleted:
11730235633Sdim    break;
11731235633Sdim
11732235633Sdim  case OR_No_Viable_Function:
11733235633Sdim    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11734235633Sdim      << R.getLookupName();
11735235633Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11736235633Sdim    return ExprError();
11737235633Sdim
11738235633Sdim  case OR_Ambiguous:
11739235633Sdim    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11740235633Sdim    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11741235633Sdim    return ExprError();
11742235633Sdim  }
11743235633Sdim
11744235633Sdim  FunctionDecl *FD = Best->Function;
11745252723Sdim  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11746252723Sdim                                        HadMultipleCandidates,
11747235633Sdim                                        SuffixInfo.getLoc(),
11748235633Sdim                                        SuffixInfo.getInfo());
11749235633Sdim  if (Fn.isInvalid())
11750235633Sdim    return true;
11751235633Sdim
11752235633Sdim  // Check the argument types. This should almost always be a no-op, except
11753235633Sdim  // that array-to-pointer decay is applied to string literals.
11754235633Sdim  Expr *ConvArgs[2];
11755252723Sdim  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
11756235633Sdim    ExprResult InputInit = PerformCopyInitialization(
11757235633Sdim      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11758235633Sdim      SourceLocation(), Args[ArgIdx]);
11759235633Sdim    if (InputInit.isInvalid())
11760235633Sdim      return true;
11761235633Sdim    ConvArgs[ArgIdx] = InputInit.take();
11762235633Sdim  }
11763235633Sdim
11764235633Sdim  QualType ResultTy = FD->getResultType();
11765235633Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11766235633Sdim  ResultTy = ResultTy.getNonLValueExprType(Context);
11767235633Sdim
11768235633Sdim  UserDefinedLiteral *UDL =
11769245431Sdim    new (Context) UserDefinedLiteral(Context, Fn.take(),
11770245431Sdim                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11771235633Sdim                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11772235633Sdim
11773235633Sdim  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11774235633Sdim    return ExprError();
11775235633Sdim
11776245431Sdim  if (CheckFunctionCall(FD, UDL, NULL))
11777235633Sdim    return ExprError();
11778235633Sdim
11779235633Sdim  return MaybeBindToTemporary(UDL);
11780235633Sdim}
11781235633Sdim
11782245431Sdim/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11783245431Sdim/// given LookupResult is non-empty, it is assumed to describe a member which
11784245431Sdim/// will be invoked. Otherwise, the function will be found via argument
11785245431Sdim/// dependent lookup.
11786245431Sdim/// CallExpr is set to a valid expression and FRS_Success returned on success,
11787245431Sdim/// otherwise CallExpr is set to ExprError() and some non-success value
11788245431Sdim/// is returned.
11789245431SdimSema::ForRangeStatus
11790245431SdimSema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11791245431Sdim                                SourceLocation RangeLoc, VarDecl *Decl,
11792245431Sdim                                BeginEndFunction BEF,
11793245431Sdim                                const DeclarationNameInfo &NameInfo,
11794245431Sdim                                LookupResult &MemberLookup,
11795245431Sdim                                OverloadCandidateSet *CandidateSet,
11796245431Sdim                                Expr *Range, ExprResult *CallExpr) {
11797245431Sdim  CandidateSet->clear();
11798245431Sdim  if (!MemberLookup.empty()) {
11799245431Sdim    ExprResult MemberRef =
11800245431Sdim        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11801245431Sdim                                 /*IsPtr=*/false, CXXScopeSpec(),
11802245431Sdim                                 /*TemplateKWLoc=*/SourceLocation(),
11803245431Sdim                                 /*FirstQualifierInScope=*/0,
11804245431Sdim                                 MemberLookup,
11805245431Sdim                                 /*TemplateArgs=*/0);
11806245431Sdim    if (MemberRef.isInvalid()) {
11807245431Sdim      *CallExpr = ExprError();
11808245431Sdim      Diag(Range->getLocStart(), diag::note_in_for_range)
11809245431Sdim          << RangeLoc << BEF << Range->getType();
11810245431Sdim      return FRS_DiagnosticIssued;
11811245431Sdim    }
11812252723Sdim    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
11813245431Sdim    if (CallExpr->isInvalid()) {
11814245431Sdim      *CallExpr = ExprError();
11815245431Sdim      Diag(Range->getLocStart(), diag::note_in_for_range)
11816245431Sdim          << RangeLoc << BEF << Range->getType();
11817245431Sdim      return FRS_DiagnosticIssued;
11818245431Sdim    }
11819245431Sdim  } else {
11820245431Sdim    UnresolvedSet<0> FoundNames;
11821245431Sdim    UnresolvedLookupExpr *Fn =
11822245431Sdim      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11823245431Sdim                                   NestedNameSpecifierLoc(), NameInfo,
11824245431Sdim                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11825245431Sdim                                   FoundNames.begin(), FoundNames.end());
11826245431Sdim
11827263509Sdim    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
11828245431Sdim                                                    CandidateSet, CallExpr);
11829245431Sdim    if (CandidateSet->empty() || CandidateSetError) {
11830245431Sdim      *CallExpr = ExprError();
11831245431Sdim      return FRS_NoViableFunction;
11832245431Sdim    }
11833245431Sdim    OverloadCandidateSet::iterator Best;
11834245431Sdim    OverloadingResult OverloadResult =
11835245431Sdim        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11836245431Sdim
11837245431Sdim    if (OverloadResult == OR_No_Viable_Function) {
11838245431Sdim      *CallExpr = ExprError();
11839245431Sdim      return FRS_NoViableFunction;
11840245431Sdim    }
11841263509Sdim    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
11842245431Sdim                                         Loc, 0, CandidateSet, &Best,
11843245431Sdim                                         OverloadResult,
11844245431Sdim                                         /*AllowTypoCorrection=*/false);
11845245431Sdim    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11846245431Sdim      *CallExpr = ExprError();
11847245431Sdim      Diag(Range->getLocStart(), diag::note_in_for_range)
11848245431Sdim          << RangeLoc << BEF << Range->getType();
11849245431Sdim      return FRS_DiagnosticIssued;
11850245431Sdim    }
11851245431Sdim  }
11852245431Sdim  return FRS_Success;
11853245431Sdim}
11854245431Sdim
11855245431Sdim
11856193326Sed/// FixOverloadedFunctionReference - E is an expression that refers to
11857193326Sed/// a C++ overloaded function (possibly with some parentheses and
11858193326Sed/// perhaps a '&' around it). We have resolved the overloaded function
11859193326Sed/// to the function declaration Fn, so patch up the expression E to
11860198398Srdivacky/// refer (possibly indirectly) to Fn. Returns the new expr.
11861207619SrdivackyExpr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11862206084Srdivacky                                           FunctionDecl *Fn) {
11863193326Sed  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11864206084Srdivacky    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11865206084Srdivacky                                                   Found, Fn);
11866199990Srdivacky    if (SubExpr == PE->getSubExpr())
11867218893Sdim      return PE;
11868218893Sdim
11869199990Srdivacky    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11870218893Sdim  }
11871218893Sdim
11872199990Srdivacky  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11873206084Srdivacky    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11874206084Srdivacky                                                   Found, Fn);
11875218893Sdim    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11876199990Srdivacky                               SubExpr->getType()) &&
11877198893Srdivacky           "Implicit cast type cannot be determined from overload");
11878212904Sdim    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11879199990Srdivacky    if (SubExpr == ICE->getSubExpr())
11880218893Sdim      return ICE;
11881218893Sdim
11882218893Sdim    return ImplicitCastExpr::Create(Context, ICE->getType(),
11883212904Sdim                                    ICE->getCastKind(),
11884212904Sdim                                    SubExpr, 0,
11885212904Sdim                                    ICE->getValueKind());
11886218893Sdim  }
11887218893Sdim
11888199990Srdivacky  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11889212904Sdim    assert(UnOp->getOpcode() == UO_AddrOf &&
11890193326Sed           "Can only take the address of an overloaded function");
11891193326Sed    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11892193326Sed      if (Method->isStatic()) {
11893193326Sed        // Do nothing: static member functions aren't any different
11894193326Sed        // from non-member functions.
11895199990Srdivacky      } else {
11896199990Srdivacky        // Fix the sub expression, which really has to be an
11897199990Srdivacky        // UnresolvedLookupExpr holding an overloaded member function
11898199990Srdivacky        // or template.
11899206084Srdivacky        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11900206084Srdivacky                                                       Found, Fn);
11901199990Srdivacky        if (SubExpr == UnOp->getSubExpr())
11902218893Sdim          return UnOp;
11903199990Srdivacky
11904199990Srdivacky        assert(isa<DeclRefExpr>(SubExpr)
11905199990Srdivacky               && "fixed to something other than a decl ref");
11906199990Srdivacky        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11907199990Srdivacky               && "fixed to a member ref with no nested name qualifier");
11908199990Srdivacky
11909199990Srdivacky        // We have taken the address of a pointer to member
11910199990Srdivacky        // function. Perform the computation here so that we get the
11911199990Srdivacky        // appropriate pointer to member type.
11912199990Srdivacky        QualType ClassType
11913199990Srdivacky          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11914199990Srdivacky        QualType MemPtrType
11915199990Srdivacky          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11916199990Srdivacky
11917218893Sdim        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11918218893Sdim                                           VK_RValue, OK_Ordinary,
11919218893Sdim                                           UnOp->getOperatorLoc());
11920193326Sed      }
11921193326Sed    }
11922206084Srdivacky    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11923206084Srdivacky                                                   Found, Fn);
11924199990Srdivacky    if (SubExpr == UnOp->getSubExpr())
11925218893Sdim      return UnOp;
11926218893Sdim
11927212904Sdim    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11928199990Srdivacky                                     Context.getPointerType(SubExpr->getType()),
11929218893Sdim                                       VK_RValue, OK_Ordinary,
11930199990Srdivacky                                       UnOp->getOperatorLoc());
11931218893Sdim  }
11932199990Srdivacky
11933199990Srdivacky  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11934200583Srdivacky    // FIXME: avoid copy.
11935200583Srdivacky    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11936199990Srdivacky    if (ULE->hasExplicitTemplateArgs()) {
11937200583Srdivacky      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11938200583Srdivacky      TemplateArgs = &TemplateArgsBuffer;
11939199990Srdivacky    }
11940199990Srdivacky
11941226890Sdim    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11942226890Sdim                                           ULE->getQualifierLoc(),
11943235633Sdim                                           ULE->getTemplateKeywordLoc(),
11944226890Sdim                                           Fn,
11945235633Sdim                                           /*enclosing*/ false, // FIXME?
11946226890Sdim                                           ULE->getNameLoc(),
11947226890Sdim                                           Fn->getType(),
11948226890Sdim                                           VK_LValue,
11949226890Sdim                                           Found.getDecl(),
11950226890Sdim                                           TemplateArgs);
11951235633Sdim    MarkDeclRefReferenced(DRE);
11952226890Sdim    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11953226890Sdim    return DRE;
11954193326Sed  }
11955199990Srdivacky
11956199990Srdivacky  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11957199990Srdivacky    // FIXME: avoid copy.
11958200583Srdivacky    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11959200583Srdivacky    if (MemExpr->hasExplicitTemplateArgs()) {
11960200583Srdivacky      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11961200583Srdivacky      TemplateArgs = &TemplateArgsBuffer;
11962200583Srdivacky    }
11963199990Srdivacky
11964200583Srdivacky    Expr *Base;
11965200583Srdivacky
11966218893Sdim    // If we're filling in a static method where we used to have an
11967218893Sdim    // implicit member access, rewrite to a simple decl ref.
11968200583Srdivacky    if (MemExpr->isImplicitAccess()) {
11969200583Srdivacky      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11970226890Sdim        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11971226890Sdim                                               MemExpr->getQualifierLoc(),
11972235633Sdim                                               MemExpr->getTemplateKeywordLoc(),
11973226890Sdim                                               Fn,
11974235633Sdim                                               /*enclosing*/ false,
11975226890Sdim                                               MemExpr->getMemberLoc(),
11976226890Sdim                                               Fn->getType(),
11977226890Sdim                                               VK_LValue,
11978226890Sdim                                               Found.getDecl(),
11979226890Sdim                                               TemplateArgs);
11980235633Sdim        MarkDeclRefReferenced(DRE);
11981226890Sdim        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11982226890Sdim        return DRE;
11983202379Srdivacky      } else {
11984202379Srdivacky        SourceLocation Loc = MemExpr->getMemberLoc();
11985202379Srdivacky        if (MemExpr->getQualifier())
11986221345Sdim          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11987235633Sdim        CheckCXXThisCapture(Loc);
11988202379Srdivacky        Base = new (Context) CXXThisExpr(Loc,
11989202379Srdivacky                                         MemExpr->getBaseType(),
11990202379Srdivacky                                         /*isImplicit=*/true);
11991202379Srdivacky      }
11992200583Srdivacky    } else
11993218893Sdim      Base = MemExpr->getBase();
11994200583Srdivacky
11995221345Sdim    ExprValueKind valueKind;
11996221345Sdim    QualType type;
11997221345Sdim    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11998221345Sdim      valueKind = VK_LValue;
11999221345Sdim      type = Fn->getType();
12000221345Sdim    } else {
12001221345Sdim      valueKind = VK_RValue;
12002221345Sdim      type = Context.BoundMemberTy;
12003221345Sdim    }
12004221345Sdim
12005226890Sdim    MemberExpr *ME = MemberExpr::Create(Context, Base,
12006226890Sdim                                        MemExpr->isArrow(),
12007226890Sdim                                        MemExpr->getQualifierLoc(),
12008235633Sdim                                        MemExpr->getTemplateKeywordLoc(),
12009226890Sdim                                        Fn,
12010226890Sdim                                        Found,
12011226890Sdim                                        MemExpr->getMemberNameInfo(),
12012226890Sdim                                        TemplateArgs,
12013226890Sdim                                        type, valueKind, OK_Ordinary);
12014226890Sdim    ME->setHadMultipleCandidates(true);
12015245431Sdim    MarkMemberReferenced(ME);
12016226890Sdim    return ME;
12017199990Srdivacky  }
12018218893Sdim
12019218893Sdim  llvm_unreachable("Invalid reference to overloaded function");
12020193326Sed}
12021193326Sed
12022218893SdimExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12023212904Sdim                                                DeclAccessPair Found,
12024212904Sdim                                                FunctionDecl *Fn) {
12025206084Srdivacky  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
12026200583Srdivacky}
12027200583Srdivacky
12028193326Sed} // end namespace clang
12029