1249423Sdim//===--- 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
14249423Sdim#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"
22249423Sdim#include "clang/Basic/Diagnostic.h"
23198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
24263508Sdim#include "clang/Basic/TargetInfo.h"
25249423Sdim#include "clang/Lex/Preprocessor.h"
26249423Sdim#include "clang/Sema/Initialization.h"
27249423Sdim#include "clang/Sema/Lookup.h"
28249423Sdim#include "clang/Sema/SemaInternal.h"
29249423Sdim#include "clang/Sema/Template.h"
30249423Sdim#include "clang/Sema/TemplateDeduction.h"
31218893Sdim#include "llvm/ADT/DenseSet.h"
32249423Sdim#include "llvm/ADT/STLExtras.h"
33193326Sed#include "llvm/ADT/SmallPtrSet.h"
34239462Sdim#include "llvm/ADT/SmallString.h"
35193326Sed#include <algorithm>
36193326Sed
37193326Sednamespace clang {
38212904Sdimusing namespace sema;
39193326Sed
40249423Sdim/// A convenience routine for creating a decayed reference to a function.
41221345Sdimstatic ExprResult
42249423SdimCreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43249423Sdim                      bool HadMultipleCandidates,
44224145Sdim                      SourceLocation Loc = SourceLocation(),
45224145Sdim                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
46251662Sdim  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
47263508Sdim    return ExprError();
48263508Sdim  // If FoundDecl is different from Fn (such as if one is a template
49263508Sdim  // and the other a specialization), make sure DiagnoseUseOfDecl is
50263508Sdim  // called on both.
51263508Sdim  // FIXME: This would be more comprehensively addressed by modifying
52263508Sdim  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53263508Sdim  // being used.
54263508Sdim  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
55251662Sdim    return ExprError();
56234353Sdim  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
57226633Sdim                                                 VK_LValue, Loc, LocInfo);
58226633Sdim  if (HadMultipleCandidates)
59226633Sdim    DRE->setHadMultipleCandidates(true);
60249423Sdim
61249423Sdim  S.MarkDeclRefReferenced(DRE);
62249423Sdim
63226633Sdim  ExprResult E = S.Owned(DRE);
64221345Sdim  E = S.DefaultFunctionArrayConversion(E.take());
65221345Sdim  if (E.isInvalid())
66221345Sdim    return ExprError();
67243830Sdim  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);
75239462Sdim
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,
85263508Sdim                        bool AllowExplicit,
86263508Sdim                        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
278234353Sdim/// Skip any implicit casts which could be either part of a narrowing conversion
279234353Sdim/// or after one in an implicit conversion.
280234353Sdimstatic const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
281234353Sdim  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
282234353Sdim    switch (ICE->getCastKind()) {
283234353Sdim    case CK_NoOp:
284234353Sdim    case CK_IntegralCast:
285234353Sdim    case CK_IntegralToBoolean:
286234353Sdim    case CK_IntegralToFloating:
287234353Sdim    case CK_FloatingToIntegral:
288234353Sdim    case CK_FloatingToBoolean:
289234353Sdim    case CK_FloatingCast:
290234353Sdim      Converted = ICE->getSubExpr();
291234353Sdim      continue;
292234353Sdim
293234353Sdim    default:
294234353Sdim      return Converted;
295234353Sdim    }
296234353Sdim  }
297234353Sdim
298234353Sdim  return Converted;
299234353Sdim}
300234353Sdim
301234353Sdim/// Check if this standard conversion sequence represents a narrowing
302234353Sdim/// conversion, according to C++11 [dcl.init.list]p7.
303234353Sdim///
304234353Sdim/// \param Ctx  The AST context.
305234353Sdim/// \param Converted  The result of applying this standard conversion sequence.
306234353Sdim/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
307234353Sdim///        value of the expression prior to the narrowing conversion.
308234353Sdim/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
309234353Sdim///        type of the expression prior to the narrowing conversion.
310234353SdimNarrowingKind
311234353SdimStandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
312234353Sdim                                             const Expr *Converted,
313234353Sdim                                             APValue &ConstantValue,
314234353Sdim                                             QualType &ConstantType) const {
315234353Sdim  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
316234353Sdim
317234353Sdim  // C++11 [dcl.init.list]p7:
318234353Sdim  //   A narrowing conversion is an implicit conversion ...
319234353Sdim  QualType FromType = getToType(0);
320234353Sdim  QualType ToType = getToType(1);
321234353Sdim  switch (Second) {
322234353Sdim  // -- from a floating-point type to an integer type, or
323234353Sdim  //
324234353Sdim  // -- from an integer type or unscoped enumeration type to a floating-point
325234353Sdim  //    type, except where the source is a constant expression and the actual
326234353Sdim  //    value after conversion will fit into the target type and will produce
327234353Sdim  //    the original value when converted back to the original type, or
328234353Sdim  case ICK_Floating_Integral:
329234353Sdim    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330234353Sdim      return NK_Type_Narrowing;
331234353Sdim    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
332234353Sdim      llvm::APSInt IntConstantValue;
333234353Sdim      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334234353Sdim      if (Initializer &&
335234353Sdim          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
336234353Sdim        // Convert the integer to the floating type.
337234353Sdim        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
338234353Sdim        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
339234353Sdim                                llvm::APFloat::rmNearestTiesToEven);
340234353Sdim        // And back.
341234353Sdim        llvm::APSInt ConvertedValue = IntConstantValue;
342234353Sdim        bool ignored;
343234353Sdim        Result.convertToInteger(ConvertedValue,
344234353Sdim                                llvm::APFloat::rmTowardZero, &ignored);
345234353Sdim        // If the resulting value is different, this was a narrowing conversion.
346234353Sdim        if (IntConstantValue != ConvertedValue) {
347234353Sdim          ConstantValue = APValue(IntConstantValue);
348234353Sdim          ConstantType = Initializer->getType();
349234353Sdim          return NK_Constant_Narrowing;
350234353Sdim        }
351234353Sdim      } else {
352234353Sdim        // Variables are always narrowings.
353234353Sdim        return NK_Variable_Narrowing;
354234353Sdim      }
355234353Sdim    }
356234353Sdim    return NK_Not_Narrowing;
357234353Sdim
358234353Sdim  // -- from long double to double or float, or from double to float, except
359234353Sdim  //    where the source is a constant expression and the actual value after
360234353Sdim  //    conversion is within the range of values that can be represented (even
361234353Sdim  //    if it cannot be represented exactly), or
362234353Sdim  case ICK_Floating_Conversion:
363234353Sdim    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
364234353Sdim        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
365234353Sdim      // FromType is larger than ToType.
366234353Sdim      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
367234353Sdim      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
368234353Sdim        // Constant!
369234353Sdim        assert(ConstantValue.isFloat());
370234353Sdim        llvm::APFloat FloatVal = ConstantValue.getFloat();
371234353Sdim        // Convert the source value into the target type.
372234353Sdim        bool ignored;
373234353Sdim        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
374234353Sdim          Ctx.getFloatTypeSemantics(ToType),
375234353Sdim          llvm::APFloat::rmNearestTiesToEven, &ignored);
376234353Sdim        // If there was no overflow, the source value is within the range of
377234353Sdim        // values that can be represented.
378234353Sdim        if (ConvertStatus & llvm::APFloat::opOverflow) {
379234353Sdim          ConstantType = Initializer->getType();
380234353Sdim          return NK_Constant_Narrowing;
381234353Sdim        }
382234353Sdim      } else {
383234353Sdim        return NK_Variable_Narrowing;
384234353Sdim      }
385234353Sdim    }
386234353Sdim    return NK_Not_Narrowing;
387234353Sdim
388234353Sdim  // -- from an integer type or unscoped enumeration type to an integer type
389234353Sdim  //    that cannot represent all the values of the original type, except where
390234353Sdim  //    the source is a constant expression and the actual value after
391234353Sdim  //    conversion will fit into the target type and will produce the original
392234353Sdim  //    value when converted back to the original type.
393234353Sdim  case ICK_Boolean_Conversion:  // Bools are integers too.
394234353Sdim    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
395234353Sdim      // Boolean conversions can be from pointers and pointers to members
396234353Sdim      // [conv.bool], and those aren't considered narrowing conversions.
397234353Sdim      return NK_Not_Narrowing;
398234353Sdim    }  // Otherwise, fall through to the integral case.
399234353Sdim  case ICK_Integral_Conversion: {
400234353Sdim    assert(FromType->isIntegralOrUnscopedEnumerationType());
401234353Sdim    assert(ToType->isIntegralOrUnscopedEnumerationType());
402234353Sdim    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
403234353Sdim    const unsigned FromWidth = Ctx.getIntWidth(FromType);
404234353Sdim    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
405234353Sdim    const unsigned ToWidth = Ctx.getIntWidth(ToType);
406234353Sdim
407234353Sdim    if (FromWidth > ToWidth ||
408239462Sdim        (FromWidth == ToWidth && FromSigned != ToSigned) ||
409239462Sdim        (FromSigned && !ToSigned)) {
410234353Sdim      // Not all values of FromType can be represented in ToType.
411234353Sdim      llvm::APSInt InitializerValue;
412234353Sdim      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
413239462Sdim      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
414239462Sdim        // Such conversions on variables are always narrowing.
415239462Sdim        return NK_Variable_Narrowing;
416239462Sdim      }
417239462Sdim      bool Narrowing = false;
418239462Sdim      if (FromWidth < ToWidth) {
419239462Sdim        // Negative -> unsigned is narrowing. Otherwise, more bits is never
420239462Sdim        // narrowing.
421239462Sdim        if (InitializerValue.isSigned() && InitializerValue.isNegative())
422239462Sdim          Narrowing = true;
423239462Sdim      } else {
424234353Sdim        // Add a bit to the InitializerValue so we don't have to worry about
425234353Sdim        // signed vs. unsigned comparisons.
426234353Sdim        InitializerValue = InitializerValue.extend(
427234353Sdim          InitializerValue.getBitWidth() + 1);
428234353Sdim        // Convert the initializer to and from the target width and signed-ness.
429234353Sdim        llvm::APSInt ConvertedValue = InitializerValue;
430234353Sdim        ConvertedValue = ConvertedValue.trunc(ToWidth);
431234353Sdim        ConvertedValue.setIsSigned(ToSigned);
432234353Sdim        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
433234353Sdim        ConvertedValue.setIsSigned(InitializerValue.isSigned());
434234353Sdim        // If the result is different, this was a narrowing conversion.
435239462Sdim        if (ConvertedValue != InitializerValue)
436239462Sdim          Narrowing = true;
437234353Sdim      }
438239462Sdim      if (Narrowing) {
439239462Sdim        ConstantType = Initializer->getType();
440239462Sdim        ConstantValue = APValue(InitializerValue);
441239462Sdim        return NK_Constant_Narrowing;
442239462Sdim      }
443234353Sdim    }
444234353Sdim    return NK_Not_Narrowing;
445234353Sdim  }
446234353Sdim
447234353Sdim  default:
448234353Sdim    // Other kinds of conversions are not narrowings.
449234353Sdim    return NK_Not_Narrowing;
450234353Sdim  }
451234353Sdim}
452234353Sdim
453263508Sdim/// dump - Print this standard conversion sequence to standard
454193326Sed/// error. Useful for debugging overloading issues.
455263508Sdimvoid StandardConversionSequence::dump() const {
456226633Sdim  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
492263508Sdim/// dump - Print this user-defined conversion sequence to standard
493193326Sed/// error. Useful for debugging overloading issues.
494263508Sdimvoid UserDefinedConversionSequence::dump() const {
495226633Sdim  raw_ostream &OS = llvm::errs();
496193326Sed  if (Before.First || Before.Second || Before.Third) {
497263508Sdim    Before.dump();
498202879Srdivacky    OS << " -> ";
499193326Sed  }
500234353Sdim  if (ConversionFunction)
501234353Sdim    OS << '\'' << *ConversionFunction << '\'';
502234353Sdim  else
503234353Sdim    OS << "aggregate initialization";
504193326Sed  if (After.First || After.Second || After.Third) {
505202879Srdivacky    OS << " -> ";
506263508Sdim    After.dump();
507193326Sed  }
508193326Sed}
509193326Sed
510263508Sdim/// dump - Print this implicit conversion sequence to standard
511193326Sed/// error. Useful for debugging overloading issues.
512263508Sdimvoid ImplicitConversionSequence::dump() const {
513226633Sdim  raw_ostream &OS = llvm::errs();
514263508Sdim  if (isStdInitializerListElement())
515263508Sdim    OS << "Worst std::initializer_list element conversion: ";
516193326Sed  switch (ConversionKind) {
517193326Sed  case StandardConversion:
518202879Srdivacky    OS << "Standard conversion: ";
519263508Sdim    Standard.dump();
520193326Sed    break;
521193326Sed  case UserDefinedConversion:
522202879Srdivacky    OS << "User-defined conversion: ";
523263508Sdim    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 {
555263508Sdim  // Structure used by DeductionFailureInfo to store
556249423Sdim  // template argument information.
557249423Sdim  struct DFIArguments {
558208600Srdivacky    TemplateArgument FirstArg;
559208600Srdivacky    TemplateArgument SecondArg;
560208600Srdivacky  };
561263508Sdim  // Structure used by DeductionFailureInfo to store
562249423Sdim  // template parameter and template argument information.
563249423Sdim  struct DFIParamWithArguments : DFIArguments {
564249423Sdim    TemplateParameter Param;
565249423Sdim  };
566208600Srdivacky}
567218893Sdim
568208600Srdivacky/// \brief Convert from Sema's representation of template deduction information
569208600Srdivacky/// to the form used in overload-candidate information.
570263508SdimDeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
571263508Sdim                                              Sema::TemplateDeductionResult TDK,
572263508Sdim                                              TemplateDeductionInfo &Info) {
573263508Sdim  DeductionFailureInfo Result;
574208600Srdivacky  Result.Result = static_cast<unsigned>(TDK);
575239462Sdim  Result.HasDiagnostic = false;
576208600Srdivacky  Result.Data = 0;
577208600Srdivacky  switch (TDK) {
578208600Srdivacky  case Sema::TDK_Success:
579243830Sdim  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
590249423Sdim  case Sema::TDK_NonDeducedMismatch: {
591249423Sdim    // FIXME: Should allocate from normal heap so that we can free this later.
592249423Sdim    DFIArguments *Saved = new (Context) DFIArguments;
593249423Sdim    Saved->FirstArg = Info.FirstArg;
594249423Sdim    Saved->SecondArg = Info.SecondArg;
595249423Sdim    Result.Data = Saved;
596249423Sdim    break;
597249423Sdim  }
598249423Sdim
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();
612239462Sdim    if (Info.hasSFINAEDiagnostic()) {
613239462Sdim      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614239462Sdim          SourceLocation(), PartialDiagnostic::NullDiagnostic());
615239462Sdim      Info.takeSFINAEDiagnostic(*Diag);
616239462Sdim      Result.HasDiagnostic = true;
617239462Sdim    }
618208600Srdivacky    break;
619218893Sdim
620208600Srdivacky  case Sema::TDK_FailedOverloadResolution:
621249423Sdim    Result.Data = Info.Expression;
622218893Sdim    break;
623249423Sdim
624249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
625249423Sdim    break;
626208600Srdivacky  }
627218893Sdim
628208600Srdivacky  return Result;
629208600Srdivacky}
630202379Srdivacky
631263508Sdimvoid DeductionFailureInfo::Destroy() {
632208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
633208600Srdivacky  case Sema::TDK_Success:
634243830Sdim  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:
640249423Sdim  case Sema::TDK_FailedOverloadResolution:
641208600Srdivacky    break;
642218893Sdim
643208600Srdivacky  case Sema::TDK_Inconsistent:
644212904Sdim  case Sema::TDK_Underqualified:
645249423Sdim  case Sema::TDK_NonDeducedMismatch:
646208600Srdivacky    // FIXME: Destroy the data?
647208600Srdivacky    Data = 0;
648208600Srdivacky    break;
649208600Srdivacky
650208600Srdivacky  case Sema::TDK_SubstitutionFailure:
651239462Sdim    // FIXME: Destroy the template argument list?
652208600Srdivacky    Data = 0;
653239462Sdim    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
654239462Sdim      Diag->~PartialDiagnosticAt();
655239462Sdim      HasDiagnostic = false;
656239462Sdim    }
657208600Srdivacky    break;
658218893Sdim
659208600Srdivacky  // Unhandled
660249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
661208600Srdivacky    break;
662208600Srdivacky  }
663208600Srdivacky}
664218893Sdim
665263508SdimPartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
666239462Sdim  if (HasDiagnostic)
667239462Sdim    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
668239462Sdim  return 0;
669239462Sdim}
670239462Sdim
671263508SdimTemplateParameter DeductionFailureInfo::getTemplateParameter() {
672208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
673208600Srdivacky  case Sema::TDK_Success:
674243830Sdim  case Sema::TDK_Invalid:
675208600Srdivacky  case Sema::TDK_InstantiationDepth:
676208600Srdivacky  case Sema::TDK_TooManyArguments:
677208600Srdivacky  case Sema::TDK_TooFewArguments:
678208600Srdivacky  case Sema::TDK_SubstitutionFailure:
679249423Sdim  case Sema::TDK_NonDeducedMismatch:
680249423Sdim  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
692249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
693208600Srdivacky    break;
694208600Srdivacky  }
695218893Sdim
696208600Srdivacky  return TemplateParameter();
697208600Srdivacky}
698218893Sdim
699263508SdimTemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
700208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701249423Sdim  case Sema::TDK_Success:
702249423Sdim  case Sema::TDK_Invalid:
703249423Sdim  case Sema::TDK_InstantiationDepth:
704249423Sdim  case Sema::TDK_TooManyArguments:
705249423Sdim  case Sema::TDK_TooFewArguments:
706249423Sdim  case Sema::TDK_Incomplete:
707249423Sdim  case Sema::TDK_InvalidExplicitArguments:
708249423Sdim  case Sema::TDK_Inconsistent:
709249423Sdim  case Sema::TDK_Underqualified:
710249423Sdim  case Sema::TDK_NonDeducedMismatch:
711249423Sdim  case Sema::TDK_FailedOverloadResolution:
712249423Sdim    return 0;
713208600Srdivacky
714249423Sdim  case Sema::TDK_SubstitutionFailure:
715249423Sdim    return static_cast<TemplateArgumentList*>(Data);
716218893Sdim
717249423Sdim  // Unhandled
718249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
719249423Sdim    break;
720208600Srdivacky  }
721208600Srdivacky
722208600Srdivacky  return 0;
723208600Srdivacky}
724208600Srdivacky
725263508Sdimconst TemplateArgument *DeductionFailureInfo::getFirstArg() {
726208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727208600Srdivacky  case Sema::TDK_Success:
728243830Sdim  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:
735249423Sdim  case Sema::TDK_FailedOverloadResolution:
736208600Srdivacky    return 0;
737208600Srdivacky
738208600Srdivacky  case Sema::TDK_Inconsistent:
739212904Sdim  case Sema::TDK_Underqualified:
740249423Sdim  case Sema::TDK_NonDeducedMismatch:
741249423Sdim    return &static_cast<DFIArguments*>(Data)->FirstArg;
742208600Srdivacky
743208600Srdivacky  // Unhandled
744249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
745208600Srdivacky    break;
746208600Srdivacky  }
747218893Sdim
748208600Srdivacky  return 0;
749218893Sdim}
750208600Srdivacky
751263508Sdimconst TemplateArgument *DeductionFailureInfo::getSecondArg() {
752208600Srdivacky  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
753208600Srdivacky  case Sema::TDK_Success:
754243830Sdim  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:
761249423Sdim  case Sema::TDK_FailedOverloadResolution:
762208600Srdivacky    return 0;
763208600Srdivacky
764208600Srdivacky  case Sema::TDK_Inconsistent:
765212904Sdim  case Sema::TDK_Underqualified:
766249423Sdim  case Sema::TDK_NonDeducedMismatch:
767249423Sdim    return &static_cast<DFIArguments*>(Data)->SecondArg;
768208600Srdivacky
769208600Srdivacky  // Unhandled
770249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
771208600Srdivacky    break;
772208600Srdivacky  }
773218893Sdim
774208600Srdivacky  return 0;
775208600Srdivacky}
776208600Srdivacky
777263508SdimExpr *DeductionFailureInfo::getExpr() {
778249423Sdim  if (static_cast<Sema::TemplateDeductionResult>(Result) ==
779249423Sdim        Sema::TDK_FailedOverloadResolution)
780249423Sdim    return static_cast<Expr*>(Data);
781249423Sdim
782249423Sdim  return 0;
783249423Sdim}
784249423Sdim
785243830Sdimvoid OverloadCandidateSet::destroyCandidates() {
786239462Sdim  for (iterator i = begin(), e = end(); i != e; ++i) {
787234353Sdim    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
788234353Sdim      i->Conversions[ii].~ImplicitConversionSequence();
789239462Sdim    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
790239462Sdim      i->DeductionFailure.Destroy();
791239462Sdim  }
792243830Sdim}
793243830Sdim
794243830Sdimvoid OverloadCandidateSet::clear() {
795243830Sdim  destroyCandidates();
796234353Sdim  NumInlineSequences = 0;
797234353Sdim  Candidates.clear();
798208600Srdivacky  Functions.clear();
799208600Srdivacky}
800218893Sdim
801234353Sdimnamespace {
802234353Sdim  class UnbridgedCastsSet {
803234353Sdim    struct Entry {
804234353Sdim      Expr **Addr;
805234353Sdim      Expr *Saved;
806234353Sdim    };
807234353Sdim    SmallVector<Entry, 2> Entries;
808234353Sdim
809234353Sdim  public:
810234353Sdim    void save(Sema &S, Expr *&E) {
811234353Sdim      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
812234353Sdim      Entry entry = { &E, E };
813234353Sdim      Entries.push_back(entry);
814234353Sdim      E = S.stripARCUnbridgedCast(E);
815234353Sdim    }
816234353Sdim
817234353Sdim    void restore() {
818234353Sdim      for (SmallVectorImpl<Entry>::iterator
819234353Sdim             i = Entries.begin(), e = Entries.end(); i != e; ++i)
820234353Sdim        *i->Addr = i->Saved;
821234353Sdim    }
822234353Sdim  };
823234353Sdim}
824234353Sdim
825234353Sdim/// checkPlaceholderForOverload - Do any interesting placeholder-like
826234353Sdim/// preprocessing on the given expression.
827234353Sdim///
828234353Sdim/// \param unbridgedCasts a collection to which to add unbridged casts;
829234353Sdim///   without this, they will be immediately diagnosed as errors
830234353Sdim///
831234353Sdim/// Return true on unrecoverable error.
832234353Sdimstatic bool checkPlaceholderForOverload(Sema &S, Expr *&E,
833234353Sdim                                        UnbridgedCastsSet *unbridgedCasts = 0) {
834234353Sdim  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
835234353Sdim    // We can't handle overloaded expressions here because overload
836234353Sdim    // resolution might reasonably tweak them.
837234353Sdim    if (placeholder->getKind() == BuiltinType::Overload) return false;
838234353Sdim
839234353Sdim    // If the context potentially accepts unbridged ARC casts, strip
840234353Sdim    // the unbridged cast and add it to the collection for later restoration.
841234353Sdim    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
842234353Sdim        unbridgedCasts) {
843234353Sdim      unbridgedCasts->save(S, E);
844234353Sdim      return false;
845234353Sdim    }
846234353Sdim
847234353Sdim    // Go ahead and check everything else.
848234353Sdim    ExprResult result = S.CheckPlaceholderExpr(E);
849234353Sdim    if (result.isInvalid())
850234353Sdim      return true;
851234353Sdim
852234353Sdim    E = result.take();
853234353Sdim    return false;
854234353Sdim  }
855234353Sdim
856234353Sdim  // Nothing to do.
857234353Sdim  return false;
858234353Sdim}
859234353Sdim
860234353Sdim/// checkArgPlaceholdersForOverload - Check a set of call operands for
861234353Sdim/// placeholders.
862263508Sdimstatic bool checkArgPlaceholdersForOverload(Sema &S,
863263508Sdim                                            MultiExprArg Args,
864234353Sdim                                            UnbridgedCastsSet &unbridged) {
865263508Sdim  for (unsigned i = 0, e = Args.size(); i != e; ++i)
866263508Sdim    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
867234353Sdim      return true;
868234353Sdim
869234353Sdim  return false;
870234353Sdim}
871234353Sdim
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 =
930249423Sdim      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
931249423Sdim      !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
950251662Sdim        if (!shouldLinkPossiblyHiddenDecl(*I, New))
951251662Sdim          continue;
952251662Sdim
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
978263508Sdimbool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
979263508Sdim                      bool UseUsingDeclRules) {
980263508Sdim  // C++ [basic.start.main]p2: This function shall not be overloaded.
981263508Sdim  if (New->isMain())
982212904Sdim    return false;
983212904Sdim
984263508Sdim  // MSVCRT user defined entry points cannot be overloaded.
985263508Sdim  if (New->isMSVCRTEntryPoint())
986249423Sdim    return false;
987249423Sdim
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?
998263508Sdim  QualType OldQType = Context.getCanonicalType(Old->getType());
999263508Sdim  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() ||
1020263508Sdim       !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 &&
1036263508Sdim      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037263508Sdim                                       OldTemplate->getTemplateParameters(),
1038263508Sdim                                       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.
1050249423Sdim  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051249423Sdim  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1052199512Srdivacky  if (OldMethod && NewMethod &&
1053249423Sdim      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054249423Sdim    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055249423Sdim      if (!UseUsingDeclRules &&
1056249423Sdim          (OldMethod->getRefQualifier() == RQ_None ||
1057249423Sdim           NewMethod->getRefQualifier() == RQ_None)) {
1058249423Sdim        // C++0x [over.load]p2:
1059249423Sdim        //   - Member function declarations with the same name and the same
1060249423Sdim        //     parameter-type-list as well as member function template
1061249423Sdim        //     declarations with the same name, the same parameter-type-list, and
1062249423Sdim        //     the same template parameter lists cannot be overloaded if any of
1063249423Sdim        //     them, but not all, have a ref-qualifier (8.3.5).
1064263508Sdim        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1065249423Sdim          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1066263508Sdim        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1067249423Sdim      }
1068249423Sdim      return true;
1069218893Sdim    }
1070218893Sdim
1071249423Sdim    // We may not have applied the implicit const for a constexpr member
1072249423Sdim    // function yet (because we haven't yet resolved whether this is a static
1073249423Sdim    // or non-static member function). Add it now, on the assumption that this
1074249423Sdim    // is a redeclaration of OldMethod.
1075263508Sdim    unsigned OldQuals = OldMethod->getTypeQualifiers();
1076249423Sdim    unsigned NewQuals = NewMethod->getTypeQualifiers();
1077263508Sdim    if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1078263508Sdim        !isa<CXXConstructorDecl>(NewMethod))
1079249423Sdim      NewQuals |= Qualifiers::Const;
1080263508Sdim
1081263508Sdim    // We do not allow overloading based off of '__restrict'.
1082263508Sdim    OldQuals &= ~Qualifiers::Restrict;
1083263508Sdim    NewQuals &= ~Qualifiers::Restrict;
1084263508Sdim    if (OldQuals != NewQuals)
1085249423Sdim      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
1101234353Sdim/// \brief Tries a user-defined conversion from From to ToType.
1102234353Sdim///
1103234353Sdim/// Produces an implicit conversion sequence for when a standard conversion
1104234353Sdim/// is not an option. See TryImplicitConversion for more information.
1105234353Sdimstatic ImplicitConversionSequence
1106234353SdimTryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1107234353Sdim                         bool SuppressUserConversions,
1108234353Sdim                         bool AllowExplicit,
1109234353Sdim                         bool InOverloadResolution,
1110234353Sdim                         bool CStyle,
1111263508Sdim                         bool AllowObjCWritebackConversion,
1112263508Sdim                         bool AllowObjCConversionOnExplicit) {
1113234353Sdim  ImplicitConversionSequence ICS;
1114234353Sdim
1115234353Sdim  if (SuppressUserConversions) {
1116234353Sdim    // We're not in the case above, so there is no conversion that
1117234353Sdim    // we can perform.
1118234353Sdim    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1119234353Sdim    return ICS;
1120234353Sdim  }
1121234353Sdim
1122234353Sdim  // Attempt user-defined conversion.
1123234353Sdim  OverloadCandidateSet Conversions(From->getExprLoc());
1124234353Sdim  OverloadingResult UserDefResult
1125234353Sdim    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1126263508Sdim                              AllowExplicit, AllowObjCConversionOnExplicit);
1127234353Sdim
1128234353Sdim  if (UserDefResult == OR_Success) {
1129234353Sdim    ICS.setUserDefined();
1130234353Sdim    // C++ [over.ics.user]p4:
1131234353Sdim    //   A conversion of an expression of class type to the same class
1132234353Sdim    //   type is given Exact Match rank, and a conversion of an
1133234353Sdim    //   expression of class type to a base class of that type is
1134234353Sdim    //   given Conversion rank, in spite of the fact that a copy
1135234353Sdim    //   constructor (i.e., a user-defined conversion function) is
1136234353Sdim    //   called for those cases.
1137234353Sdim    if (CXXConstructorDecl *Constructor
1138234353Sdim          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1139234353Sdim      QualType FromCanon
1140234353Sdim        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1141234353Sdim      QualType ToCanon
1142234353Sdim        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1143234353Sdim      if (Constructor->isCopyConstructor() &&
1144234353Sdim          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1145234353Sdim        // Turn this into a "standard" conversion sequence, so that it
1146234353Sdim        // gets ranked with standard conversion sequences.
1147234353Sdim        ICS.setStandard();
1148234353Sdim        ICS.Standard.setAsIdentityConversion();
1149234353Sdim        ICS.Standard.setFromType(From->getType());
1150234353Sdim        ICS.Standard.setAllToTypes(ToType);
1151234353Sdim        ICS.Standard.CopyConstructor = Constructor;
1152234353Sdim        if (ToCanon != FromCanon)
1153234353Sdim          ICS.Standard.Second = ICK_Derived_To_Base;
1154234353Sdim      }
1155234353Sdim    }
1156234353Sdim
1157234353Sdim    // C++ [over.best.ics]p4:
1158234353Sdim    //   However, when considering the argument of a user-defined
1159234353Sdim    //   conversion function that is a candidate by 13.3.1.3 when
1160234353Sdim    //   invoked for the copying of the temporary in the second step
1161234353Sdim    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1162234353Sdim    //   13.3.1.6 in all cases, only standard conversion sequences and
1163234353Sdim    //   ellipsis conversion sequences are allowed.
1164234353Sdim    if (SuppressUserConversions && ICS.isUserDefined()) {
1165234353Sdim      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1166234353Sdim    }
1167234353Sdim  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1168234353Sdim    ICS.setAmbiguous();
1169234353Sdim    ICS.Ambiguous.setFromType(From->getType());
1170234353Sdim    ICS.Ambiguous.setToType(ToType);
1171234353Sdim    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172234353Sdim         Cand != Conversions.end(); ++Cand)
1173234353Sdim      if (Cand->Viable)
1174234353Sdim        ICS.Ambiguous.addConversion(Cand->Function);
1175234353Sdim  } else {
1176234353Sdim    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1177234353Sdim  }
1178234353Sdim
1179234353Sdim  return ICS;
1180234353Sdim}
1181234353Sdim
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,
1215263508Sdim                      bool AllowObjCWritebackConversion,
1216263508Sdim                      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
1224234353Sdim  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
1258234353Sdim  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1259234353Sdim                                  AllowExplicit, InOverloadResolution, CStyle,
1260263508Sdim                                  AllowObjCWritebackConversion,
1261263508Sdim                                  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,
1274263508Sdim                                      AllowObjCWritebackConversion,
1275263508Sdim                                      /*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,
1285234353Sdim                                AssignmentAction Action, bool AllowExplicit) {
1286207619Srdivacky  ImplicitConversionSequence ICS;
1287234353Sdim  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1288207619Srdivacky}
1289207619Srdivacky
1290221345SdimExprResult
1291221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType,
1292207619Srdivacky                                AssignmentAction Action, bool AllowExplicit,
1293234353Sdim                                ImplicitConversionSequence& ICS) {
1294234353Sdim  if (checkPlaceholderForOverload(*this, From))
1295234353Sdim    return ExprError();
1296234353Sdim
1297224145Sdim  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1298224145Sdim  bool AllowObjCWritebackConversion
1299234353Sdim    = 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,
1307263508Sdim                                     AllowObjCWritebackConversion,
1308263508Sdim                                     /*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) ||
1396234353Sdim        (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
1406234353Sdimstatic bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1407234353Sdim                                bool InOverloadResolution,
1408234353Sdim                                StandardConversionSequence &SCS,
1409234353Sdim                                bool CStyle);
1410234353Sdim
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()) {
1436234353Sdim    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  }
1497226633Sdim  // Lvalue-to-rvalue conversion (C++11 4.1):
1498226633Sdim  //   A glvalue (3.10) of a non-function, non-array type T can
1499226633Sdim  //   be converted to a prvalue.
1500226633Sdim  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
1506234353Sdim    // C11 6.3.2.1p2:
1507234353Sdim    //   ... if the lvalue has atomic type, the value has the non-atomic version
1508234353Sdim    //   of the type of the lvalue ...
1509234353Sdim    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1510234353Sdim      FromType = Atomic->getValueType();
1511234353Sdim
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();
1592263508Sdim  } 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();
1630234353Sdim  } 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;
1643234353Sdim  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1644234353Sdim                                 CStyle)) {
1645234353Sdim    // tryAtomicConversion has updated the standard conversion sequence
1646234353Sdim    // appropriately.
1647234353Sdim    return true;
1648249423Sdim  } else if (ToType->isEventT() &&
1649249423Sdim             From->isIntegerConstantExpr(S.getASTContext()) &&
1650249423Sdim             (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1651249423Sdim    SCS.Second = ICK_Zero_Event_Conversion;
1652249423Sdim    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() &&
1682249423Sdim        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
1752243830Sdim  // 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.
1764243830Sdim  // C++11 [conv.prom]p4:
1765243830Sdim  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1766243830Sdim  //   can be converted to a prvalue of its underlying type. Moreover, if
1767243830Sdim  //   integral promotion can be applied to its underlying type, a prvalue of an
1768243830Sdim  //   unscoped enumeration type whose underlying type is fixed can also be
1769243830Sdim  //   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
1776243830Sdim    // We can perform an integral promotion to the underlying type of the enum,
1777243830Sdim    // even if that's not the promoted type.
1778243830Sdim    if (FromEnumType->getDecl()->isFixed()) {
1779243830Sdim      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1780243830Sdim      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1781243830Sdim             IsIntegralPromotion(From, Underlying, ToType);
1782243830Sdim    }
1783243830Sdim
1784218893Sdim    // We have already pre-calculated the promotion type, so this is trivial.
1785218893Sdim    if (ToType->isIntegerType() &&
1786239462Sdim        !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.
1804226633Sdim    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)
1838251662Sdim    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>()) {
1876226633Sdim      /// An rvalue of type float can be converted to an rvalue of type
1877226633Sdim      /// 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 [...].
1885234353Sdim      if (!getLangOpts().CPlusPlus &&
1886193326Sed          (FromBuiltin->getKind() == BuiltinType::Float ||
1887193326Sed           FromBuiltin->getKind() == BuiltinType::Double) &&
1888193326Sed          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1889193326Sed        return true;
1890226633Sdim
1891226633Sdim      // Half can be promoted to float.
1892249423Sdim      if (!getLangOpts().NativeHalfType &&
1893249423Sdim           FromBuiltin->getKind() == BuiltinType::Half &&
1894226633Sdim          ToBuiltin->getKind() == BuiltinType::Float)
1895226633Sdim        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() &&
2052234353Sdim      !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.
2083234353Sdim  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.
2093234353Sdim  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.
2114234353Sdim  if (getLangOpts().CPlusPlus &&
2115193326Sed      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2116204643Srdivacky      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2117239462Sdim      !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) {
2156234353Sdim  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();
2195234353Sdim      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) {
2351234353Sdim  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 ||
2365234353Sdim      !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();
2455234353Sdim    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   }
2488226633Sdim   if (LangOpts.ObjCAutoRefCount &&
2489226633Sdim       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2490226633Sdim                                                    ToFunctionType))
2491226633Sdim     return false;
2492226633Sdim
2493218893Sdim   ConvertedType = ToType;
2494218893Sdim   return true;
2495218893Sdim}
2496218893Sdim
2497234353Sdimenum {
2498234353Sdim  ft_default,
2499234353Sdim  ft_different_class,
2500234353Sdim  ft_parameter_arity,
2501234353Sdim  ft_parameter_mismatch,
2502234353Sdim  ft_return_type,
2503234353Sdim  ft_qualifer_mismatch
2504234353Sdim};
2505234353Sdim
2506234353Sdim/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2507234353Sdim/// function types.  Catches different number of parameter, mismatch in
2508234353Sdim/// parameter types, and different return types.
2509234353Sdimvoid Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2510234353Sdim                                      QualType FromType, QualType ToType) {
2511234353Sdim  // If either type is not valid, include no extra info.
2512234353Sdim  if (FromType.isNull() || ToType.isNull()) {
2513234353Sdim    PDiag << ft_default;
2514234353Sdim    return;
2515234353Sdim  }
2516234353Sdim
2517234353Sdim  // Get the function type from the pointers.
2518234353Sdim  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2519234353Sdim    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2520234353Sdim                            *ToMember = ToType->getAs<MemberPointerType>();
2521234353Sdim    if (FromMember->getClass() != ToMember->getClass()) {
2522234353Sdim      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2523234353Sdim            << QualType(FromMember->getClass(), 0);
2524234353Sdim      return;
2525234353Sdim    }
2526234353Sdim    FromType = FromMember->getPointeeType();
2527234353Sdim    ToType = ToMember->getPointeeType();
2528234353Sdim  }
2529234353Sdim
2530234353Sdim  if (FromType->isPointerType())
2531234353Sdim    FromType = FromType->getPointeeType();
2532234353Sdim  if (ToType->isPointerType())
2533234353Sdim    ToType = ToType->getPointeeType();
2534234353Sdim
2535234353Sdim  // Remove references.
2536234353Sdim  FromType = FromType.getNonReferenceType();
2537234353Sdim  ToType = ToType.getNonReferenceType();
2538234353Sdim
2539234353Sdim  // Don't print extra info for non-specialized template functions.
2540234353Sdim  if (FromType->isInstantiationDependentType() &&
2541234353Sdim      !FromType->getAs<TemplateSpecializationType>()) {
2542234353Sdim    PDiag << ft_default;
2543234353Sdim    return;
2544234353Sdim  }
2545234353Sdim
2546234353Sdim  // No extra info for same types.
2547234353Sdim  if (Context.hasSameType(FromType, ToType)) {
2548234353Sdim    PDiag << ft_default;
2549234353Sdim    return;
2550234353Sdim  }
2551234353Sdim
2552234353Sdim  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2553234353Sdim                          *ToFunction = ToType->getAs<FunctionProtoType>();
2554234353Sdim
2555234353Sdim  // Both types need to be function types.
2556234353Sdim  if (!FromFunction || !ToFunction) {
2557234353Sdim    PDiag << ft_default;
2558234353Sdim    return;
2559234353Sdim  }
2560234353Sdim
2561234353Sdim  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2562234353Sdim    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2563234353Sdim          << FromFunction->getNumArgs();
2564234353Sdim    return;
2565234353Sdim  }
2566234353Sdim
2567234353Sdim  // Handle different parameter types.
2568234353Sdim  unsigned ArgPos;
2569234353Sdim  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2570234353Sdim    PDiag << ft_parameter_mismatch << ArgPos + 1
2571234353Sdim          << ToFunction->getArgType(ArgPos)
2572234353Sdim          << FromFunction->getArgType(ArgPos);
2573234353Sdim    return;
2574234353Sdim  }
2575234353Sdim
2576234353Sdim  // Handle different return type.
2577234353Sdim  if (!Context.hasSameType(FromFunction->getResultType(),
2578234353Sdim                           ToFunction->getResultType())) {
2579234353Sdim    PDiag << ft_return_type << ToFunction->getResultType()
2580234353Sdim          << FromFunction->getResultType();
2581234353Sdim    return;
2582234353Sdim  }
2583234353Sdim
2584234353Sdim  unsigned FromQuals = FromFunction->getTypeQuals(),
2585234353Sdim           ToQuals = ToFunction->getTypeQuals();
2586234353Sdim  if (FromQuals != ToQuals) {
2587234353Sdim    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2588234353Sdim    return;
2589234353Sdim  }
2590234353Sdim
2591234353Sdim  // Unable to find a difference, so add no extra info.
2592234353Sdim  PDiag << ft_default;
2593234353Sdim}
2594234353Sdim
2595207619Srdivacky/// FunctionArgTypesAreEqual - This routine checks two function proto types
2596234353Sdim/// for equality of their argument types. Caller has already checked that
2597263508Sdim/// they have same number of arguments.  If the parameters are different,
2598263508Sdim/// ArgPos will have the parameter index of the first different parameter.
2599218893Sdimbool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2600234353Sdim                                    const FunctionProtoType *NewType,
2601234353Sdim                                    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) {
2605263508Sdim    if (!Context.hasSameType(O->getUnqualifiedType(),
2606263508Sdim                             N->getUnqualifiedType())) {
2607234353Sdim      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
2629239462Sdim  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2630239462Sdim      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2631239462Sdim      Expr::NPCK_ZeroExpression) {
2632239462Sdim    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2633239462Sdim      DiagRuntimeBehavior(From->getExprLoc(), From,
2634239462Sdim                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2635239462Sdim                            << ToType << From->getSourceRange());
2636239462Sdim    else if (!isUnevaluatedContext())
2637239462Sdim      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2638239462Sdim        << ToType << From->getSourceRange();
2639239462Sdim  }
2640226633Sdim  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2641226633Sdim    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    }
2659226633Sdim  } else if (const ObjCObjectPointerType *ToPtrType =
2660226633Sdim               ToType->getAs<ObjCObjectPointerType>()) {
2661226633Sdim    if (const ObjCObjectPointerType *FromPtrType =
2662226633Sdim          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;
2668226633Sdim    } else if (FromType->isBlockPointerType()) {
2669226633Sdim      Kind = CK_BlockPointerToObjCPointerCast;
2670226633Sdim    } else {
2671226633Sdim      Kind = CK_CPointerToObjCPointerCast;
2672218893Sdim    }
2673226633Sdim  } else if (ToType->isBlockPointerType()) {
2674226633Sdim    if (!FromType->isBlockPointerType())
2675226633Sdim      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) &&
2718239462Sdim      !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
2793263508Sdim/// Determine whether the lifetime conversion between the two given
2794263508Sdim/// qualifiers sets is nontrivial.
2795263508Sdimstatic bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2796263508Sdim                                               Qualifiers ToQuals) {
2797263508Sdim  // Converting anything to const __unsafe_unretained is trivial.
2798263508Sdim  if (ToQuals.hasConst() &&
2799263508Sdim      ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2800263508Sdim    return false;
2801263508Sdim
2802263508Sdim  return true;
2803263508Sdim}
2804263508Sdim
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)) {
2846263508Sdim        if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2847263508Sdim          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
2889234353Sdim/// \brief - Determine whether this is a conversion from a scalar type to an
2890234353Sdim/// atomic type.
2891234353Sdim///
2892234353Sdim/// If successful, updates \c SCS's second and third steps in the conversion
2893234353Sdim/// sequence to finish the conversion.
2894234353Sdimstatic bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2895234353Sdim                                bool InOverloadResolution,
2896234353Sdim                                StandardConversionSequence &SCS,
2897234353Sdim                                bool CStyle) {
2898234353Sdim  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2899234353Sdim  if (!ToAtomic)
2900234353Sdim    return false;
2901234353Sdim
2902234353Sdim  StandardConversionSequence InnerSCS;
2903234353Sdim  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2904234353Sdim                            InOverloadResolution, InnerSCS,
2905234353Sdim                            CStyle, /*AllowObjCWritebackConversion=*/false))
2906234353Sdim    return false;
2907234353Sdim
2908234353Sdim  SCS.Second = InnerSCS.Second;
2909234353Sdim  SCS.setToType(1, InnerSCS.getToType(1));
2910234353Sdim  SCS.Third = InnerSCS.Third;
2911234353Sdim  SCS.QualificationIncludesObjCLifetime
2912234353Sdim    = InnerSCS.QualificationIncludesObjCLifetime;
2913234353Sdim  SCS.setToType(2, InnerSCS.getToType(2));
2914234353Sdim  return true;
2915234353Sdim}
2916234353Sdim
2917234353Sdimstatic bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2918234353Sdim                                              CXXConstructorDecl *Constructor,
2919234353Sdim                                              QualType Type) {
2920234353Sdim  const FunctionProtoType *CtorType =
2921234353Sdim      Constructor->getType()->getAs<FunctionProtoType>();
2922234353Sdim  if (CtorType->getNumArgs() > 0) {
2923234353Sdim    QualType FirstArg = CtorType->getArgType(0);
2924234353Sdim    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2925234353Sdim      return true;
2926234353Sdim  }
2927234353Sdim  return false;
2928234353Sdim}
2929234353Sdim
2930234353Sdimstatic OverloadingResult
2931234353SdimIsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2932234353Sdim                                       CXXRecordDecl *To,
2933234353Sdim                                       UserDefinedConversionSequence &User,
2934234353Sdim                                       OverloadCandidateSet &CandidateSet,
2935234353Sdim                                       bool AllowExplicit) {
2936249423Sdim  DeclContext::lookup_result R = S.LookupConstructors(To);
2937249423Sdim  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2938234353Sdim       Con != ConEnd; ++Con) {
2939234353Sdim    NamedDecl *D = *Con;
2940234353Sdim    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2941234353Sdim
2942234353Sdim    // Find the constructor (which may be a template).
2943234353Sdim    CXXConstructorDecl *Constructor = 0;
2944234353Sdim    FunctionTemplateDecl *ConstructorTmpl
2945234353Sdim      = dyn_cast<FunctionTemplateDecl>(D);
2946234353Sdim    if (ConstructorTmpl)
2947234353Sdim      Constructor
2948234353Sdim        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2949234353Sdim    else
2950234353Sdim      Constructor = cast<CXXConstructorDecl>(D);
2951234353Sdim
2952234353Sdim    bool Usable = !Constructor->isInvalidDecl() &&
2953234353Sdim                  S.isInitListConstructor(Constructor) &&
2954234353Sdim                  (AllowExplicit || !Constructor->isExplicit());
2955234353Sdim    if (Usable) {
2956234353Sdim      // If the first argument is (a reference to) the target type,
2957234353Sdim      // suppress conversions.
2958234353Sdim      bool SuppressUserConversions =
2959234353Sdim          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2960234353Sdim      if (ConstructorTmpl)
2961234353Sdim        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2962234353Sdim                                       /*ExplicitArgs*/ 0,
2963234353Sdim                                       From, CandidateSet,
2964234353Sdim                                       SuppressUserConversions);
2965234353Sdim      else
2966234353Sdim        S.AddOverloadCandidate(Constructor, FoundDecl,
2967234353Sdim                               From, CandidateSet,
2968234353Sdim                               SuppressUserConversions);
2969234353Sdim    }
2970234353Sdim  }
2971234353Sdim
2972234353Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2973234353Sdim
2974234353Sdim  OverloadCandidateSet::iterator Best;
2975234353Sdim  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2976234353Sdim  case OR_Success: {
2977234353Sdim    // Record the standard conversion we used and the conversion function.
2978234353Sdim    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2979234353Sdim    QualType ThisType = Constructor->getThisType(S.Context);
2980234353Sdim    // Initializer lists don't have conversions as such.
2981234353Sdim    User.Before.setAsIdentityConversion();
2982234353Sdim    User.HadMultipleCandidates = HadMultipleCandidates;
2983234353Sdim    User.ConversionFunction = Constructor;
2984234353Sdim    User.FoundConversionFunction = Best->FoundDecl;
2985234353Sdim    User.After.setAsIdentityConversion();
2986234353Sdim    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2987234353Sdim    User.After.setAllToTypes(ToType);
2988234353Sdim    return OR_Success;
2989234353Sdim  }
2990234353Sdim
2991234353Sdim  case OR_No_Viable_Function:
2992234353Sdim    return OR_No_Viable_Function;
2993234353Sdim  case OR_Deleted:
2994234353Sdim    return OR_Deleted;
2995234353Sdim  case OR_Ambiguous:
2996234353Sdim    return OR_Ambiguous;
2997234353Sdim  }
2998234353Sdim
2999234353Sdim  llvm_unreachable("Invalid OverloadResult!");
3000234353Sdim}
3001234353Sdim
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).
3012263508Sdim///
3013263508Sdim/// \param AllowObjCConversionOnExplicit true if the conversion should
3014263508Sdim/// allow an extra Objective-C pointer conversion on uses of explicit
3015263508Sdim/// constructors. Requires \c AllowExplicit to also be set.
3016212904Sdimstatic OverloadingResult
3017212904SdimIsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3018234353Sdim                        UserDefinedConversionSequence &User,
3019234353Sdim                        OverloadCandidateSet &CandidateSet,
3020263508Sdim                        bool AllowExplicit,
3021263508Sdim                        bool AllowObjCConversionOnExplicit) {
3022263508Sdim  assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3023263508Sdim
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
3043249423Sdim    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())) {
3051234353Sdim
3052234353Sdim      Expr **Args = &From;
3053234353Sdim      unsigned NumArgs = 1;
3054234353Sdim      bool ListInitializing = false;
3055234353Sdim      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3056263508Sdim        // But first, see if there is an init-list-constructor that will work.
3057234353Sdim        OverloadingResult Result = IsInitializerListConstructorConversion(
3058234353Sdim            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3059234353Sdim        if (Result != OR_No_Viable_Function)
3060234353Sdim          return Result;
3061234353Sdim        // Never mind.
3062234353Sdim        CandidateSet.clear();
3063234353Sdim
3064234353Sdim        // If we're list-initializing, we pass the individual elements as
3065234353Sdim        // arguments, not the entire list.
3066234353Sdim        Args = InitList->getInits();
3067234353Sdim        NumArgs = InitList->getNumInits();
3068234353Sdim        ListInitializing = true;
3069234353Sdim      }
3070234353Sdim
3071249423Sdim      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3072249423Sdim      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
3087234353Sdim        bool Usable = !Constructor->isInvalidDecl();
3088234353Sdim        if (ListInitializing)
3089234353Sdim          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3090234353Sdim        else
3091234353Sdim          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3092234353Sdim        if (Usable) {
3093234353Sdim          bool SuppressUserConversions = !ConstructorsOnly;
3094234353Sdim          if (SuppressUserConversions && ListInitializing) {
3095234353Sdim            SuppressUserConversions = false;
3096234353Sdim            if (NumArgs == 1) {
3097234353Sdim              // If the first argument is (a reference to) the target type,
3098234353Sdim              // suppress conversions.
3099234353Sdim              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3100234353Sdim                                                S.Context, Constructor, ToType);
3101234353Sdim            }
3102234353Sdim          }
3103198092Srdivacky          if (ConstructorTmpl)
3104212904Sdim            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3105212904Sdim                                           /*ExplicitArgs*/ 0,
3106234353Sdim                                           llvm::makeArrayRef(Args, NumArgs),
3107234353Sdim                                           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,
3112234353Sdim                                   llvm::makeArrayRef(Args, NumArgs),
3113234353Sdim                                   CandidateSet, SuppressUserConversions);
3114198092Srdivacky        }
3115193326Sed      }
3116193326Sed    }
3117193326Sed  }
3118193326Sed
3119207619Srdivacky  // Enumerate conversion functions, if we're allowed to.
3120234353Sdim  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3121239462Sdim  } 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.
3128249423Sdim      std::pair<CXXRecordDecl::conversion_iterator,
3129249423Sdim                CXXRecordDecl::conversion_iterator>
3130249423Sdim        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3131249423Sdim      for (CXXRecordDecl::conversion_iterator
3132249423Sdim             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,
3150263508Sdim                                             CandidateSet,
3151263508Sdim                                             AllowObjCConversionOnExplicit);
3152198092Srdivacky          else
3153212904Sdim            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3154263508Sdim                                     From, ToType, CandidateSet,
3155263508Sdim                                     AllowObjCConversionOnExplicit);
3156198092Srdivacky        }
3157193326Sed      }
3158193326Sed    }
3159193326Sed  }
3160193326Sed
3161226633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3162226633Sdim
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);
3176234353Sdim      if (isa<InitListExpr>(From)) {
3177234353Sdim        // Initializer lists don't have conversions as such.
3178234353Sdim        User.Before.setAsIdentityConversion();
3179234353Sdim      } else {
3180234353Sdim        if (Best->Conversions[0].isEllipsis())
3181234353Sdim          User.EllipsisConversion = true;
3182234353Sdim        else {
3183234353Sdim          User.Before = Best->Conversions[0].Standard;
3184234353Sdim          User.EllipsisConversion = false;
3185234353Sdim        }
3186193326Sed      }
3187226633Sdim      User.HadMultipleCandidates = HadMultipleCandidates;
3188212904Sdim      User.ConversionFunction = Constructor;
3189226633Sdim      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;
3194234353Sdim    }
3195234353Sdim    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;
3204226633Sdim      User.HadMultipleCandidates = HadMultipleCandidates;
3205212904Sdim      User.ConversionFunction = Conversion;
3206226633Sdim      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    }
3221234353Sdim    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
3233234353Sdim  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,
3242263508Sdim                            CandidateSet, false, false);
3243199512Srdivacky  if (OvResult == OR_Ambiguous)
3244234353Sdim    Diag(From->getLocStart(),
3245199512Srdivacky         diag::err_typecheck_ambiguous_condition)
3246199512Srdivacky          << From->getType() << ToType << From->getSourceRange();
3247263508Sdim  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3248263508Sdim    if (!RequireCompleteType(From->getLocStart(), ToType,
3249263508Sdim                          diag::err_typecheck_nonviable_condition_incomplete,
3250263508Sdim                             From->getType(), From->getSourceRange()))
3251263508Sdim      Diag(From->getLocStart(),
3252263508Sdim           diag::err_typecheck_nonviable_condition)
3253263508Sdim           << From->getType() << From->getSourceRange() << ToType;
3254263508Sdim  }
3255199512Srdivacky  else
3256198092Srdivacky    return false;
3257234353Sdim  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3258218893Sdim  return true;
3259198092Srdivacky}
3260193326Sed
3261234353Sdim/// \brief Compare the user-defined conversion functions or constructors
3262234353Sdim/// of two user-defined conversion sequences to determine whether any ordering
3263234353Sdim/// is possible.
3264234353Sdimstatic ImplicitConversionSequence::CompareKind
3265234353SdimcompareConversionFunctions(Sema &S,
3266234353Sdim                           FunctionDecl *Function1,
3267234353Sdim                           FunctionDecl *Function2) {
3268249423Sdim  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3269234353Sdim    return ImplicitConversionSequence::Indistinguishable;
3270234353Sdim
3271234353Sdim  // Objective-C++:
3272234353Sdim  //   If both conversion functions are implicitly-declared conversions from
3273234353Sdim  //   a lambda closure type to a function pointer and a block pointer,
3274234353Sdim  //   respectively, always prefer the conversion to a function pointer,
3275234353Sdim  //   because the function pointer is more lightweight and is more likely
3276234353Sdim  //   to keep code working.
3277234353Sdim  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3278234353Sdim  if (!Conv1)
3279234353Sdim    return ImplicitConversionSequence::Indistinguishable;
3280234353Sdim
3281234353Sdim  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3282234353Sdim  if (!Conv2)
3283234353Sdim    return ImplicitConversionSequence::Indistinguishable;
3284234353Sdim
3285234353Sdim  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3286234353Sdim    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3287234353Sdim    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3288234353Sdim    if (Block1 != Block2)
3289234353Sdim      return Block1? ImplicitConversionSequence::Worse
3290234353Sdim                   : ImplicitConversionSequence::Better;
3291234353Sdim  }
3292234353Sdim
3293234353Sdim  return ImplicitConversionSequence::Indistinguishable;
3294234353Sdim}
3295234353Sdim
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;
3320234353Sdim  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
3328234353Sdim  ImplicitConversionSequence::CompareKind Result =
3329234353Sdim      ImplicitConversionSequence::Indistinguishable;
3330234353Sdim
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())
3335234353Sdim    Result = CompareStandardConversionSequences(S,
3336234353Sdim                                                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)
3346234353Sdim      Result = CompareStandardConversionSequences(S,
3347234353Sdim                                                  ICS1.UserDefined.After,
3348234353Sdim                                                  ICS2.UserDefined.After);
3349234353Sdim    else
3350234353Sdim      Result = compareConversionFunctions(S,
3351234353Sdim                                          ICS1.UserDefined.ConversionFunction,
3352234353Sdim                                          ICS2.UserDefined.ConversionFunction);
3353193326Sed  }
3354193326Sed
3355234353Sdim  // List-initialization sequence L1 is a better conversion sequence than
3356234353Sdim  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3357234353Sdim  // for some X and L2 does not.
3358234353Sdim  if (Result == ImplicitConversionSequence::Indistinguishable &&
3359263508Sdim      !ICS1.isBad()) {
3360234353Sdim    if (ICS1.isStdInitializerListElement() &&
3361234353Sdim        !ICS2.isStdInitializerListElement())
3362234353Sdim      return ImplicitConversionSequence::Better;
3363234353Sdim    if (!ICS1.isStdInitializerListElement() &&
3364234353Sdim        ICS2.isStdInitializerListElement())
3365234353Sdim      return ImplicitConversionSequence::Worse;
3366234353Sdim  }
3367234353Sdim
3368234353Sdim  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
3604226633Sdim  // In Microsoft mode, prefer an integral conversion to a
3605226633Sdim  // floating-to-integral conversion if the integral conversion
3606226633Sdim  // is between types of the same size.
3607226633Sdim  // For example:
3608226633Sdim  // void f(float);
3609226633Sdim  // void f(int);
3610226633Sdim  // int main {
3611226633Sdim  //    long a;
3612226633Sdim  //    f(a);
3613226633Sdim  // }
3614226633Sdim  // Here, MSVC will call f(int) instead of generating a compile error
3615226633Sdim  // as clang will do in standard mode.
3616234353Sdim  if (S.getLangOpts().MicrosoftMode &&
3617226633Sdim      SCS1.Second == ICK_Integral_Conversion &&
3618226633Sdim      SCS2.Second == ICK_Floating_Integral &&
3619226633Sdim      S.Context.getTypeSize(SCS1.getFromType()) ==
3620226633Sdim      S.Context.getTypeSize(SCS1.getToType(2)))
3621226633Sdim    return ImplicitConversionSequence::Better;
3622226633Sdim
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
3936249423Sdim/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3937249423Sdim/// C++ class.
3938249423Sdimstatic bool isTypeValid(QualType T) {
3939249423Sdim  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3940249423Sdim    return !Record->isInvalidDecl();
3941249423Sdim
3942249423Sdim  return true;
3943249423Sdim}
3944249423Sdim
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.
3977239462Sdim  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3978249423Sdim             isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3979249423Sdim             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)) {
4012263508Sdim    if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4013263508Sdim      ObjCLifetimeConversion = true;
4014263508Sdim
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);
4039249423Sdim  std::pair<CXXRecordDecl::conversion_iterator,
4040249423Sdim            CXXRecordDecl::conversion_iterator>
4041249423Sdim    Conversions = T2RecordDecl->getVisibleConversionFunctions();
4042249423Sdim  for (CXXRecordDecl::conversion_iterator
4043249423Sdim         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;
4066226633Sdim
4067226633Sdim      // If we are initializing an rvalue reference, don't permit conversion
4068226633Sdim      // functions that return lvalues.
4069226633Sdim      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4070226633Sdim        const ReferenceType *RefType
4071226633Sdim          = Conv->getConversionType()->getAs<LValueReferenceType>();
4072226633Sdim        if (RefType && !RefType->getPointeeType()->isFunctionType())
4073226633Sdim          continue;
4074226633Sdim      }
4075226633Sdim
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,
4100263508Sdim                                       Init, DeclType, CandidateSet,
4101263508Sdim                                       /*AllowObjCConversionOnExplicit=*/false);
4102212904Sdim    else
4103212904Sdim      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4104263508Sdim                               DeclType, CandidateSet,
4105263508Sdim                               /*AllowObjCConversionOnExplicit=*/false);
4106210299Sed  }
4107210299Sed
4108226633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4109226633Sdim
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;
4129226633Sdim    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4130210299Sed    ICS.UserDefined.ConversionFunction = Best->Function;
4131226633Sdim    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
4153234353Sdim  llvm_unreachable("Invalid OverloadResult!");
4154210299Sed}
4155210299Sed
4156207619Srdivacky/// \brief Compute an implicit conversion sequence for reference
4157207619Srdivacky/// initialization.
4158207619Srdivackystatic ImplicitConversionSequence
4159234353SdimTryReferenceInit(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.
4268239462Sdim  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 =
4296249423Sdim      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,
4387263508Sdim                              /*AllowObjCWritebackConversion=*/false,
4388263508Sdim                              /*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()) {
4399226633Sdim    // Don't allow rvalue references to bind to lvalues.
4400226633Sdim    if (DeclType->isRValueReferenceType()) {
4401226633Sdim      if (const ReferenceType *RefType
4402226633Sdim            = ICS.UserDefined.ConversionFunction->getResultType()
4403226633Sdim                ->getAs<LValueReferenceType>()) {
4404226633Sdim        if (!RefType->getPointeeType()->isFunctionType()) {
4405226633Sdim          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4406226633Sdim                     DeclType);
4407226633Sdim          return ICS;
4408226633Sdim        }
4409226633Sdim      }
4410226633Sdim    }
4411226633Sdim
4412207619Srdivacky    ICS.UserDefined.After.ReferenceBinding = true;
4413226633Sdim    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4414226633Sdim    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4415226633Sdim    ICS.UserDefined.After.BindsToRvalue = true;
4416226633Sdim    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4417226633Sdim    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4418207619Srdivacky  }
4419218893Sdim
4420207619Srdivacky  return ICS;
4421207619Srdivacky}
4422207619Srdivacky
4423234353Sdimstatic ImplicitConversionSequence
4424234353SdimTryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4425234353Sdim                      bool SuppressUserConversions,
4426234353Sdim                      bool InOverloadResolution,
4427234353Sdim                      bool AllowObjCWritebackConversion,
4428234353Sdim                      bool AllowExplicit = false);
4429234353Sdim
4430234353Sdim/// TryListConversion - Try to copy-initialize a value of type ToType from the
4431234353Sdim/// initializer list From.
4432234353Sdimstatic ImplicitConversionSequence
4433234353SdimTryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4434234353Sdim                  bool SuppressUserConversions,
4435234353Sdim                  bool InOverloadResolution,
4436234353Sdim                  bool AllowObjCWritebackConversion) {
4437234353Sdim  // C++11 [over.ics.list]p1:
4438234353Sdim  //   When an argument is an initializer list, it is not an expression and
4439234353Sdim  //   special rules apply for converting it to a parameter type.
4440234353Sdim
4441234353Sdim  ImplicitConversionSequence Result;
4442234353Sdim  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4443234353Sdim
4444234353Sdim  // We need a complete type for what follows. Incomplete types can never be
4445234353Sdim  // initialized from init lists.
4446239462Sdim  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4447234353Sdim    return Result;
4448234353Sdim
4449234353Sdim  // C++11 [over.ics.list]p2:
4450234353Sdim  //   If the parameter type is std::initializer_list<X> or "array of X" and
4451234353Sdim  //   all the elements can be implicitly converted to X, the implicit
4452234353Sdim  //   conversion sequence is the worst conversion necessary to convert an
4453234353Sdim  //   element of the list to X.
4454234353Sdim  bool toStdInitializerList = false;
4455234353Sdim  QualType X;
4456234353Sdim  if (ToType->isArrayType())
4457249423Sdim    X = S.Context.getAsArrayType(ToType)->getElementType();
4458234353Sdim  else
4459234353Sdim    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4460234353Sdim  if (!X.isNull()) {
4461234353Sdim    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4462234353Sdim      Expr *Init = From->getInit(i);
4463234353Sdim      ImplicitConversionSequence ICS =
4464234353Sdim          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4465234353Sdim                                InOverloadResolution,
4466234353Sdim                                AllowObjCWritebackConversion);
4467234353Sdim      // If a single element isn't convertible, fail.
4468234353Sdim      if (ICS.isBad()) {
4469234353Sdim        Result = ICS;
4470234353Sdim        break;
4471234353Sdim      }
4472234353Sdim      // Otherwise, look for the worst conversion.
4473234353Sdim      if (Result.isBad() ||
4474234353Sdim          CompareImplicitConversionSequences(S, ICS, Result) ==
4475234353Sdim              ImplicitConversionSequence::Worse)
4476234353Sdim        Result = ICS;
4477234353Sdim    }
4478234353Sdim
4479234353Sdim    // For an empty list, we won't have computed any conversion sequence.
4480234353Sdim    // Introduce the identity conversion sequence.
4481234353Sdim    if (From->getNumInits() == 0) {
4482234353Sdim      Result.setStandard();
4483234353Sdim      Result.Standard.setAsIdentityConversion();
4484234353Sdim      Result.Standard.setFromType(ToType);
4485234353Sdim      Result.Standard.setAllToTypes(ToType);
4486234353Sdim    }
4487234353Sdim
4488234353Sdim    Result.setStdInitializerListElement(toStdInitializerList);
4489234353Sdim    return Result;
4490234353Sdim  }
4491234353Sdim
4492234353Sdim  // C++11 [over.ics.list]p3:
4493234353Sdim  //   Otherwise, if the parameter is a non-aggregate class X and overload
4494234353Sdim  //   resolution chooses a single best constructor [...] the implicit
4495234353Sdim  //   conversion sequence is a user-defined conversion sequence. If multiple
4496234353Sdim  //   constructors are viable but none is better than the others, the
4497234353Sdim  //   implicit conversion sequence is a user-defined conversion sequence.
4498234353Sdim  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4499234353Sdim    // This function can deal with initializer lists.
4500263508Sdim    return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4501263508Sdim                                    /*AllowExplicit=*/false,
4502263508Sdim                                    InOverloadResolution, /*CStyle=*/false,
4503263508Sdim                                    AllowObjCWritebackConversion,
4504263508Sdim                                    /*AllowObjCConversionOnExplicit=*/false);
4505234353Sdim  }
4506234353Sdim
4507234353Sdim  // C++11 [over.ics.list]p4:
4508234353Sdim  //   Otherwise, if the parameter has an aggregate type which can be
4509234353Sdim  //   initialized from the initializer list [...] the implicit conversion
4510234353Sdim  //   sequence is a user-defined conversion sequence.
4511234353Sdim  if (ToType->isAggregateType()) {
4512234353Sdim    // Type is an aggregate, argument is an init list. At this point it comes
4513234353Sdim    // down to checking whether the initialization works.
4514234353Sdim    // FIXME: Find out whether this parameter is consumed or not.
4515234353Sdim    InitializedEntity Entity =
4516234353Sdim        InitializedEntity::InitializeParameter(S.Context, ToType,
4517234353Sdim                                               /*Consumed=*/false);
4518234353Sdim    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4519234353Sdim      Result.setUserDefined();
4520234353Sdim      Result.UserDefined.Before.setAsIdentityConversion();
4521234353Sdim      // Initializer lists don't have a type.
4522234353Sdim      Result.UserDefined.Before.setFromType(QualType());
4523234353Sdim      Result.UserDefined.Before.setAllToTypes(QualType());
4524234353Sdim
4525234353Sdim      Result.UserDefined.After.setAsIdentityConversion();
4526234353Sdim      Result.UserDefined.After.setFromType(ToType);
4527234353Sdim      Result.UserDefined.After.setAllToTypes(ToType);
4528234353Sdim      Result.UserDefined.ConversionFunction = 0;
4529234353Sdim    }
4530234353Sdim    return Result;
4531234353Sdim  }
4532234353Sdim
4533234353Sdim  // C++11 [over.ics.list]p5:
4534234353Sdim  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4535234353Sdim  if (ToType->isReferenceType()) {
4536234353Sdim    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4537234353Sdim    // mention initializer lists in any way. So we go by what list-
4538234353Sdim    // initialization would do and try to extrapolate from that.
4539234353Sdim
4540234353Sdim    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4541234353Sdim
4542234353Sdim    // If the initializer list has a single element that is reference-related
4543234353Sdim    // to the parameter type, we initialize the reference from that.
4544234353Sdim    if (From->getNumInits() == 1) {
4545234353Sdim      Expr *Init = From->getInit(0);
4546234353Sdim
4547234353Sdim      QualType T2 = Init->getType();
4548234353Sdim
4549234353Sdim      // If the initializer is the address of an overloaded function, try
4550234353Sdim      // to resolve the overloaded function. If all goes well, T2 is the
4551234353Sdim      // type of the resulting function.
4552234353Sdim      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4553234353Sdim        DeclAccessPair Found;
4554234353Sdim        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4555234353Sdim                                   Init, ToType, false, Found))
4556234353Sdim          T2 = Fn->getType();
4557234353Sdim      }
4558234353Sdim
4559234353Sdim      // Compute some basic properties of the types and the initializer.
4560234353Sdim      bool dummy1 = false;
4561234353Sdim      bool dummy2 = false;
4562234353Sdim      bool dummy3 = false;
4563234353Sdim      Sema::ReferenceCompareResult RefRelationship
4564234353Sdim        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4565234353Sdim                                         dummy2, dummy3);
4566234353Sdim
4567263508Sdim      if (RefRelationship >= Sema::Ref_Related) {
4568263508Sdim        return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4569234353Sdim                                SuppressUserConversions,
4570234353Sdim                                /*AllowExplicit=*/false);
4571263508Sdim      }
4572234353Sdim    }
4573234353Sdim
4574234353Sdim    // Otherwise, we bind the reference to a temporary created from the
4575234353Sdim    // initializer list.
4576234353Sdim    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4577234353Sdim                               InOverloadResolution,
4578234353Sdim                               AllowObjCWritebackConversion);
4579234353Sdim    if (Result.isFailure())
4580234353Sdim      return Result;
4581234353Sdim    assert(!Result.isEllipsis() &&
4582234353Sdim           "Sub-initialization cannot result in ellipsis conversion.");
4583234353Sdim
4584234353Sdim    // Can we even bind to a temporary?
4585234353Sdim    if (ToType->isRValueReferenceType() ||
4586234353Sdim        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4587234353Sdim      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4588234353Sdim                                            Result.UserDefined.After;
4589234353Sdim      SCS.ReferenceBinding = true;
4590234353Sdim      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4591234353Sdim      SCS.BindsToRvalue = true;
4592234353Sdim      SCS.BindsToFunctionLvalue = false;
4593234353Sdim      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4594234353Sdim      SCS.ObjCLifetimeConversionBinding = false;
4595234353Sdim    } else
4596234353Sdim      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4597234353Sdim                    From, ToType);
4598234353Sdim    return Result;
4599234353Sdim  }
4600234353Sdim
4601234353Sdim  // C++11 [over.ics.list]p6:
4602234353Sdim  //   Otherwise, if the parameter type is not a class:
4603234353Sdim  if (!ToType->isRecordType()) {
4604234353Sdim    //    - if the initializer list has one element, the implicit conversion
4605234353Sdim    //      sequence is the one required to convert the element to the
4606234353Sdim    //      parameter type.
4607234353Sdim    unsigned NumInits = From->getNumInits();
4608234353Sdim    if (NumInits == 1)
4609234353Sdim      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4610234353Sdim                                     SuppressUserConversions,
4611234353Sdim                                     InOverloadResolution,
4612234353Sdim                                     AllowObjCWritebackConversion);
4613234353Sdim    //    - if the initializer list has no elements, the implicit conversion
4614234353Sdim    //      sequence is the identity conversion.
4615234353Sdim    else if (NumInits == 0) {
4616234353Sdim      Result.setStandard();
4617234353Sdim      Result.Standard.setAsIdentityConversion();
4618234353Sdim      Result.Standard.setFromType(ToType);
4619234353Sdim      Result.Standard.setAllToTypes(ToType);
4620234353Sdim    }
4621234353Sdim    return Result;
4622234353Sdim  }
4623234353Sdim
4624234353Sdim  // C++11 [over.ics.list]p7:
4625234353Sdim  //   In all cases other than those enumerated above, no conversion is possible
4626234353Sdim  return Result;
4627234353Sdim}
4628234353Sdim
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,
4639234353Sdim                      bool AllowObjCWritebackConversion,
4640234353Sdim                      bool AllowExplicit) {
4641234353Sdim  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4642234353Sdim    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4643234353Sdim                             InOverloadResolution,AllowObjCWritebackConversion);
4644234353Sdim
4645207619Srdivacky  if (ToType->isReferenceType())
4646207619Srdivacky    return TryReferenceInit(S, From, ToType,
4647207619Srdivacky                            /*FIXME:*/From->getLocStart(),
4648207619Srdivacky                            SuppressUserConversions,
4649234353Sdim                            AllowExplicit);
4650207619Srdivacky
4651212904Sdim  return TryImplicitConversion(S, From, ToType,
4652212904Sdim                               SuppressUserConversions,
4653212904Sdim                               /*AllowExplicit=*/false,
4654218893Sdim                               InOverloadResolution,
4655224145Sdim                               /*CStyle=*/false,
4656263508Sdim                               AllowObjCWritebackConversion,
4657263508Sdim                               /*AllowObjCConversionOnExplicit=*/false);
4658193326Sed}
4659193326Sed
4660226633Sdimstatic bool TryCopyInitialization(const CanQualType FromQTy,
4661226633Sdim                                  const CanQualType ToQTy,
4662226633Sdim                                  Sema &S,
4663226633Sdim                                  SourceLocation Loc,
4664226633Sdim                                  ExprValueKind FromVK) {
4665226633Sdim  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4666226633Sdim  ImplicitConversionSequence ICS =
4667226633Sdim    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4668226633Sdim
4669226633Sdim  return !ICS.isBad();
4670226633Sdim}
4671226633Sdim
4672193326Sed/// TryObjectArgumentInitialization - Try to initialize the object
4673193326Sed/// parameter of the given member function (@c Method) from the
4674193326Sed/// expression @p From.
4675212904Sdimstatic ImplicitConversionSequence
4676249423SdimTryObjectArgumentInitialization(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,
4726249423Sdim               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) {
4819234353Sdim        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
4829234353Sdim    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,
4844234353Sdim                             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,
4857263508Sdim                               /*AllowObjCWritebackConversion=*/false,
4858263508Sdim                               /*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) {
4864234353Sdim  if (checkPlaceholderForOverload(*this, From))
4865234353Sdim    return ExprError();
4866234353Sdim
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))
4872234353Sdim    return Diag(From->getLocStart(),
4873221345Sdim                diag::err_typecheck_bool_condition)
4874198092Srdivacky                  << From->getType() << From->getSourceRange();
4875221345Sdim  return ExprError();
4876193326Sed}
4877218893Sdim
4878234353Sdim/// Check that the specified conversion is permitted in a converted constant
4879234353Sdim/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4880234353Sdim/// is acceptable.
4881234353Sdimstatic bool CheckConvertedConstantConversions(Sema &S,
4882234353Sdim                                              StandardConversionSequence &SCS) {
4883234353Sdim  // Since we know that the target type is an integral or unscoped enumeration
4884234353Sdim  // type, most conversion kinds are impossible. All possible First and Third
4885234353Sdim  // conversions are fine.
4886234353Sdim  switch (SCS.Second) {
4887234353Sdim  case ICK_Identity:
4888234353Sdim  case ICK_Integral_Promotion:
4889234353Sdim  case ICK_Integral_Conversion:
4890249423Sdim  case ICK_Zero_Event_Conversion:
4891234353Sdim    return true;
4892234353Sdim
4893234353Sdim  case ICK_Boolean_Conversion:
4894234353Sdim    // Conversion from an integral or unscoped enumeration type to bool is
4895234353Sdim    // classified as ICK_Boolean_Conversion, but it's also an integral
4896234353Sdim    // conversion, so it's permitted in a converted constant expression.
4897234353Sdim    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4898234353Sdim           SCS.getToType(2)->isBooleanType();
4899234353Sdim
4900234353Sdim  case ICK_Floating_Integral:
4901234353Sdim  case ICK_Complex_Real:
4902234353Sdim    return false;
4903234353Sdim
4904234353Sdim  case ICK_Lvalue_To_Rvalue:
4905234353Sdim  case ICK_Array_To_Pointer:
4906234353Sdim  case ICK_Function_To_Pointer:
4907234353Sdim  case ICK_NoReturn_Adjustment:
4908234353Sdim  case ICK_Qualification:
4909234353Sdim  case ICK_Compatible_Conversion:
4910234353Sdim  case ICK_Vector_Conversion:
4911234353Sdim  case ICK_Vector_Splat:
4912234353Sdim  case ICK_Derived_To_Base:
4913234353Sdim  case ICK_Pointer_Conversion:
4914234353Sdim  case ICK_Pointer_Member:
4915234353Sdim  case ICK_Block_Pointer_Conversion:
4916234353Sdim  case ICK_Writeback_Conversion:
4917234353Sdim  case ICK_Floating_Promotion:
4918234353Sdim  case ICK_Complex_Promotion:
4919234353Sdim  case ICK_Complex_Conversion:
4920234353Sdim  case ICK_Floating_Conversion:
4921234353Sdim  case ICK_TransparentUnionConversion:
4922234353Sdim    llvm_unreachable("unexpected second conversion kind");
4923234353Sdim
4924234353Sdim  case ICK_Num_Conversion_Kinds:
4925234353Sdim    break;
4926234353Sdim  }
4927234353Sdim
4928234353Sdim  llvm_unreachable("unknown conversion kind");
4929234353Sdim}
4930234353Sdim
4931234353Sdim/// CheckConvertedConstantExpression - Check that the expression From is a
4932234353Sdim/// converted constant expression of type T, perform the conversion and produce
4933234353Sdim/// the converted expression, per C++11 [expr.const]p3.
4934234353SdimExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4935234353Sdim                                                  llvm::APSInt &Value,
4936234353Sdim                                                  CCEKind CCE) {
4937249423Sdim  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4938234353Sdim  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4939234353Sdim
4940234353Sdim  if (checkPlaceholderForOverload(*this, From))
4941234353Sdim    return ExprError();
4942234353Sdim
4943234353Sdim  // C++11 [expr.const]p3 with proposed wording fixes:
4944234353Sdim  //  A converted constant expression of type T is a core constant expression,
4945234353Sdim  //  implicitly converted to a prvalue of type T, where the converted
4946234353Sdim  //  expression is a literal constant expression and the implicit conversion
4947234353Sdim  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4948234353Sdim  //  conversions, integral promotions, and integral conversions other than
4949234353Sdim  //  narrowing conversions.
4950234353Sdim  ImplicitConversionSequence ICS =
4951234353Sdim    TryImplicitConversion(From, T,
4952234353Sdim                          /*SuppressUserConversions=*/false,
4953234353Sdim                          /*AllowExplicit=*/false,
4954234353Sdim                          /*InOverloadResolution=*/false,
4955234353Sdim                          /*CStyle=*/false,
4956234353Sdim                          /*AllowObjcWritebackConversion=*/false);
4957234353Sdim  StandardConversionSequence *SCS = 0;
4958234353Sdim  switch (ICS.getKind()) {
4959234353Sdim  case ImplicitConversionSequence::StandardConversion:
4960234353Sdim    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4961234353Sdim      return Diag(From->getLocStart(),
4962234353Sdim                  diag::err_typecheck_converted_constant_expression_disallowed)
4963234353Sdim               << From->getType() << From->getSourceRange() << T;
4964234353Sdim    SCS = &ICS.Standard;
4965234353Sdim    break;
4966234353Sdim  case ImplicitConversionSequence::UserDefinedConversion:
4967234353Sdim    // We are converting from class type to an integral or enumeration type, so
4968234353Sdim    // the Before sequence must be trivial.
4969234353Sdim    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4970234353Sdim      return Diag(From->getLocStart(),
4971234353Sdim                  diag::err_typecheck_converted_constant_expression_disallowed)
4972234353Sdim               << From->getType() << From->getSourceRange() << T;
4973234353Sdim    SCS = &ICS.UserDefined.After;
4974234353Sdim    break;
4975234353Sdim  case ImplicitConversionSequence::AmbiguousConversion:
4976234353Sdim  case ImplicitConversionSequence::BadConversion:
4977234353Sdim    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4978234353Sdim      return Diag(From->getLocStart(),
4979234353Sdim                  diag::err_typecheck_converted_constant_expression)
4980234353Sdim                    << From->getType() << From->getSourceRange() << T;
4981234353Sdim    return ExprError();
4982234353Sdim
4983234353Sdim  case ImplicitConversionSequence::EllipsisConversion:
4984234353Sdim    llvm_unreachable("ellipsis conversion in converted constant expression");
4985234353Sdim  }
4986234353Sdim
4987234353Sdim  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4988234353Sdim  if (Result.isInvalid())
4989234353Sdim    return Result;
4990234353Sdim
4991234353Sdim  // Check for a narrowing implicit conversion.
4992234353Sdim  APValue PreNarrowingValue;
4993234353Sdim  QualType PreNarrowingType;
4994234353Sdim  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4995234353Sdim                                PreNarrowingType)) {
4996234353Sdim  case NK_Variable_Narrowing:
4997234353Sdim    // Implicit conversion to a narrower type, and the value is not a constant
4998234353Sdim    // expression. We'll diagnose this in a moment.
4999234353Sdim  case NK_Not_Narrowing:
5000234353Sdim    break;
5001234353Sdim
5002234353Sdim  case NK_Constant_Narrowing:
5003263508Sdim    Diag(From->getLocStart(), diag::ext_cce_narrowing)
5004234353Sdim      << CCE << /*Constant*/1
5005234353Sdim      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5006234353Sdim    break;
5007234353Sdim
5008234353Sdim  case NK_Type_Narrowing:
5009263508Sdim    Diag(From->getLocStart(), diag::ext_cce_narrowing)
5010234353Sdim      << CCE << /*Constant*/0 << From->getType() << T;
5011234353Sdim    break;
5012234353Sdim  }
5013234353Sdim
5014234353Sdim  // Check the expression is a constant expression.
5015249423Sdim  SmallVector<PartialDiagnosticAt, 8> Notes;
5016234353Sdim  Expr::EvalResult Eval;
5017234353Sdim  Eval.Diag = &Notes;
5018234353Sdim
5019251662Sdim  if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5020234353Sdim    // The expression can't be folded, so we can't keep it at this position in
5021234353Sdim    // the AST.
5022234353Sdim    Result = ExprError();
5023234353Sdim  } else {
5024234353Sdim    Value = Eval.Val.getInt();
5025234353Sdim
5026234353Sdim    if (Notes.empty()) {
5027234353Sdim      // It's a constant expression.
5028234353Sdim      return Result;
5029234353Sdim    }
5030234353Sdim  }
5031234353Sdim
5032234353Sdim  // It's not a constant expression. Produce an appropriate diagnostic.
5033234353Sdim  if (Notes.size() == 1 &&
5034234353Sdim      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5035234353Sdim    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5036234353Sdim  else {
5037234353Sdim    Diag(From->getLocStart(), diag::err_expr_not_cce)
5038234353Sdim      << CCE << From->getSourceRange();
5039234353Sdim    for (unsigned I = 0; I < Notes.size(); ++I)
5040234353Sdim      Diag(Notes[I].first, Notes[I].second);
5041234353Sdim  }
5042234353Sdim  return Result;
5043234353Sdim}
5044234353Sdim
5045226633Sdim/// dropPointerConversions - If the given standard conversion sequence
5046226633Sdim/// involves any pointer conversions, remove them.  This may change
5047226633Sdim/// the result type of the conversion sequence.
5048226633Sdimstatic void dropPointerConversion(StandardConversionSequence &SCS) {
5049226633Sdim  if (SCS.Second == ICK_Pointer_Conversion) {
5050226633Sdim    SCS.Second = ICK_Identity;
5051226633Sdim    SCS.Third = ICK_Identity;
5052226633Sdim    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5053226633Sdim  }
5054226633Sdim}
5055226633Sdim
5056226633Sdim/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5057226633Sdim/// convert the expression From to an Objective-C pointer type.
5058212904Sdimstatic ImplicitConversionSequence
5059226633SdimTryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5060226633Sdim  // Do an implicit conversion to 'id'.
5061212904Sdim  QualType Ty = S.Context.getObjCIdType();
5062226633Sdim  ImplicitConversionSequence ICS
5063226633Sdim    = TryImplicitConversion(S, From, Ty,
5064226633Sdim                            // FIXME: Are these flags correct?
5065226633Sdim                            /*SuppressUserConversions=*/false,
5066226633Sdim                            /*AllowExplicit=*/true,
5067226633Sdim                            /*InOverloadResolution=*/false,
5068226633Sdim                            /*CStyle=*/false,
5069263508Sdim                            /*AllowObjCWritebackConversion=*/false,
5070263508Sdim                            /*AllowObjCConversionOnExplicit=*/true);
5071226633Sdim
5072226633Sdim  // Strip off any final conversions to 'id'.
5073226633Sdim  switch (ICS.getKind()) {
5074226633Sdim  case ImplicitConversionSequence::BadConversion:
5075226633Sdim  case ImplicitConversionSequence::AmbiguousConversion:
5076226633Sdim  case ImplicitConversionSequence::EllipsisConversion:
5077226633Sdim    break;
5078226633Sdim
5079226633Sdim  case ImplicitConversionSequence::UserDefinedConversion:
5080226633Sdim    dropPointerConversion(ICS.UserDefined.After);
5081226633Sdim    break;
5082226633Sdim
5083226633Sdim  case ImplicitConversionSequence::StandardConversion:
5084226633Sdim    dropPointerConversion(ICS.Standard);
5085226633Sdim    break;
5086226633Sdim  }
5087226633Sdim
5088226633Sdim  return ICS;
5089208600Srdivacky}
5090212904Sdim
5091226633Sdim/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5092226633Sdim/// conversion of the expression From to an Objective-C pointer type.
5093226633SdimExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5094234353Sdim  if (checkPlaceholderForOverload(*this, From))
5095234353Sdim    return ExprError();
5096234353Sdim
5097208600Srdivacky  QualType Ty = Context.getObjCIdType();
5098226633Sdim  ImplicitConversionSequence ICS =
5099226633Sdim    TryContextuallyConvertToObjCPointer(*this, From);
5100208600Srdivacky  if (!ICS.isBad())
5101208600Srdivacky    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5102221345Sdim  return ExprError();
5103208600Srdivacky}
5104193326Sed
5105234353Sdim/// Determine whether the provided type is an integral type, or an enumeration
5106234353Sdim/// type of a permitted flavor.
5107263508Sdimbool Sema::ICEConvertDiagnoser::match(QualType T) {
5108263508Sdim  return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5109263508Sdim                                 : T->isIntegralOrUnscopedEnumerationType();
5110234353Sdim}
5111234353Sdim
5112263508Sdimstatic ExprResult
5113263508SdimdiagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5114263508Sdim                            Sema::ContextualImplicitConverter &Converter,
5115263508Sdim                            QualType T, UnresolvedSetImpl &ViableConversions) {
5116263508Sdim
5117263508Sdim  if (Converter.Suppress)
5118263508Sdim    return ExprError();
5119263508Sdim
5120263508Sdim  Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5121263508Sdim  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5122263508Sdim    CXXConversionDecl *Conv =
5123263508Sdim        cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5124263508Sdim    QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5125263508Sdim    Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5126263508Sdim  }
5127263508Sdim  return SemaRef.Owned(From);
5128263508Sdim}
5129263508Sdim
5130263508Sdimstatic bool
5131263508SdimdiagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5132263508Sdim                           Sema::ContextualImplicitConverter &Converter,
5133263508Sdim                           QualType T, bool HadMultipleCandidates,
5134263508Sdim                           UnresolvedSetImpl &ExplicitConversions) {
5135263508Sdim  if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5136263508Sdim    DeclAccessPair Found = ExplicitConversions[0];
5137263508Sdim    CXXConversionDecl *Conversion =
5138263508Sdim        cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5139263508Sdim
5140263508Sdim    // The user probably meant to invoke the given explicit
5141263508Sdim    // conversion; use it.
5142263508Sdim    QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5143263508Sdim    std::string TypeStr;
5144263508Sdim    ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5145263508Sdim
5146263508Sdim    Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5147263508Sdim        << FixItHint::CreateInsertion(From->getLocStart(),
5148263508Sdim                                      "static_cast<" + TypeStr + ">(")
5149263508Sdim        << FixItHint::CreateInsertion(
5150263508Sdim               SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5151263508Sdim    Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5152263508Sdim
5153263508Sdim    // If we aren't in a SFINAE context, build a call to the
5154263508Sdim    // explicit conversion function.
5155263508Sdim    if (SemaRef.isSFINAEContext())
5156263508Sdim      return true;
5157263508Sdim
5158263508Sdim    SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5159263508Sdim    ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5160263508Sdim                                                       HadMultipleCandidates);
5161263508Sdim    if (Result.isInvalid())
5162263508Sdim      return true;
5163263508Sdim    // Record usage of conversion in an implicit cast.
5164263508Sdim    From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5165263508Sdim                                    CK_UserDefinedConversion, Result.get(), 0,
5166263508Sdim                                    Result.get()->getValueKind());
5167263508Sdim  }
5168263508Sdim  return false;
5169263508Sdim}
5170263508Sdim
5171263508Sdimstatic bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5172263508Sdim                             Sema::ContextualImplicitConverter &Converter,
5173263508Sdim                             QualType T, bool HadMultipleCandidates,
5174263508Sdim                             DeclAccessPair &Found) {
5175263508Sdim  CXXConversionDecl *Conversion =
5176263508Sdim      cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5177263508Sdim  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5178263508Sdim
5179263508Sdim  QualType ToType = Conversion->getConversionType().getNonReferenceType();
5180263508Sdim  if (!Converter.SuppressConversion) {
5181263508Sdim    if (SemaRef.isSFINAEContext())
5182263508Sdim      return true;
5183263508Sdim
5184263508Sdim    Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5185263508Sdim        << From->getSourceRange();
5186263508Sdim  }
5187263508Sdim
5188263508Sdim  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5189263508Sdim                                                     HadMultipleCandidates);
5190263508Sdim  if (Result.isInvalid())
5191263508Sdim    return true;
5192263508Sdim  // Record usage of conversion in an implicit cast.
5193263508Sdim  From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5194263508Sdim                                  CK_UserDefinedConversion, Result.get(), 0,
5195263508Sdim                                  Result.get()->getValueKind());
5196263508Sdim  return false;
5197263508Sdim}
5198263508Sdim
5199263508Sdimstatic ExprResult finishContextualImplicitConversion(
5200263508Sdim    Sema &SemaRef, SourceLocation Loc, Expr *From,
5201263508Sdim    Sema::ContextualImplicitConverter &Converter) {
5202263508Sdim  if (!Converter.match(From->getType()) && !Converter.Suppress)
5203263508Sdim    Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5204263508Sdim        << From->getSourceRange();
5205263508Sdim
5206263508Sdim  return SemaRef.DefaultLvalueConversion(From);
5207263508Sdim}
5208263508Sdim
5209263508Sdimstatic void
5210263508SdimcollectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5211263508Sdim                                  UnresolvedSetImpl &ViableConversions,
5212263508Sdim                                  OverloadCandidateSet &CandidateSet) {
5213263508Sdim  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5214263508Sdim    DeclAccessPair FoundDecl = ViableConversions[I];
5215263508Sdim    NamedDecl *D = FoundDecl.getDecl();
5216263508Sdim    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5217263508Sdim    if (isa<UsingShadowDecl>(D))
5218263508Sdim      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5219263508Sdim
5220263508Sdim    CXXConversionDecl *Conv;
5221263508Sdim    FunctionTemplateDecl *ConvTemplate;
5222263508Sdim    if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5223263508Sdim      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5224263508Sdim    else
5225263508Sdim      Conv = cast<CXXConversionDecl>(D);
5226263508Sdim
5227263508Sdim    if (ConvTemplate)
5228263508Sdim      SemaRef.AddTemplateConversionCandidate(
5229263508Sdim        ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5230263508Sdim        /*AllowObjCConversionOnExplicit=*/false);
5231263508Sdim    else
5232263508Sdim      SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5233263508Sdim                                     ToType, CandidateSet,
5234263508Sdim                                     /*AllowObjCConversionOnExplicit=*/false);
5235263508Sdim  }
5236263508Sdim}
5237263508Sdim
5238263508Sdim/// \brief Attempt to convert the given expression to a type which is accepted
5239263508Sdim/// by the given converter.
5240210299Sed///
5241263508Sdim/// This routine will attempt to convert an expression of class type to a
5242263508Sdim/// type accepted by the specified converter. In C++11 and before, the class
5243263508Sdim/// must have a single non-explicit conversion function converting to a matching
5244263508Sdim/// type. In C++1y, there can be multiple such conversion functions, but only
5245263508Sdim/// one target type.
5246210299Sed///
5247210299Sed/// \param Loc The source location of the construct that requires the
5248210299Sed/// conversion.
5249210299Sed///
5250239462Sdim/// \param From The expression we're converting from.
5251210299Sed///
5252263508Sdim/// \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.
5256263508SdimExprResult Sema::PerformContextualImplicitConversion(
5257263508Sdim    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
5262234353Sdim  // Process placeholders immediately.
5263234353Sdim  if (From->hasPlaceholderType()) {
5264234353Sdim    ExprResult result = CheckPlaceholderExpr(From);
5265263508Sdim    if (result.isInvalid())
5266263508Sdim      return result;
5267234353Sdim    From = result.take();
5268234353Sdim  }
5269234353Sdim
5270263508Sdim  // If the expression already has a matching type, we're golden.
5271210299Sed  QualType T = From->getType();
5272263508Sdim  if (Converter.match(T))
5273234353Sdim    return DefaultLvalueConversion(From);
5274210299Sed
5275210299Sed  // FIXME: Check for missing '()' if T is a function type?
5276210299Sed
5277263508Sdim  // We can only perform contextual implicit conversions on objects of class
5278263508Sdim  // type.
5279210299Sed  const RecordType *RecordTy = T->getAs<RecordType>();
5280234353Sdim  if (!RecordTy || !getLangOpts().CPlusPlus) {
5281263508Sdim    if (!Converter.Suppress)
5282263508Sdim      Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5283212904Sdim    return Owned(From);
5284210299Sed  }
5285218893Sdim
5286210299Sed  // We must have a complete class type.
5287239462Sdim  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5288263508Sdim    ContextualImplicitConverter &Converter;
5289239462Sdim    Expr *From;
5290263508Sdim
5291263508Sdim    TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5292263508Sdim        : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5293263508Sdim
5294239462Sdim    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5295263508Sdim      Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5296239462Sdim    }
5297263508Sdim  } IncompleteDiagnoser(Converter, From);
5298239462Sdim
5299239462Sdim  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5300212904Sdim    return Owned(From);
5301218893Sdim
5302210299Sed  // Look for a conversion to an integral or enumeration type.
5303263508Sdim  UnresolvedSet<4>
5304263508Sdim      ViableConversions; // These are *potentially* viable in C++1y.
5305210299Sed  UnresolvedSet<4> ExplicitConversions;
5306249423Sdim  std::pair<CXXRecordDecl::conversion_iterator,
5307263508Sdim            CXXRecordDecl::conversion_iterator> Conversions =
5308263508Sdim      cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5309218893Sdim
5310263508Sdim  bool HadMultipleCandidates =
5311263508Sdim      (std::distance(Conversions.first, Conversions.second) > 1);
5312226633Sdim
5313263508Sdim  // To check that there is only one target type, in C++1y:
5314263508Sdim  QualType ToType;
5315263508Sdim  bool HasUniqueTargetType = true;
5316263508Sdim
5317263508Sdim  // Collect explicit or viable (potentially in C++1y) conversions.
5318263508Sdim  for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5319263508Sdim                                          E = Conversions.second;
5320263508Sdim       I != E; ++I) {
5321263508Sdim    NamedDecl *D = (*I)->getUnderlyingDecl();
5322263508Sdim    CXXConversionDecl *Conversion;
5323263508Sdim    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5324263508Sdim    if (ConvTemplate) {
5325263508Sdim      if (getLangOpts().CPlusPlus1y)
5326263508Sdim        Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5327263508Sdim      else
5328263508Sdim        continue; // C++11 does not consider conversion operator templates(?).
5329263508Sdim    } else
5330263508Sdim      Conversion = cast<CXXConversionDecl>(D);
5331263508Sdim
5332263508Sdim    assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5333263508Sdim           "Conversion operator templates are considered potentially "
5334263508Sdim           "viable in C++1y");
5335263508Sdim
5336263508Sdim    QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5337263508Sdim    if (Converter.match(CurToType) || ConvTemplate) {
5338263508Sdim
5339263508Sdim      if (Conversion->isExplicit()) {
5340263508Sdim        // FIXME: For C++1y, do we need this restriction?
5341263508Sdim        // cf. diagnoseNoViableConversion()
5342263508Sdim        if (!ConvTemplate)
5343210299Sed          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5344263508Sdim      } else {
5345263508Sdim        if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5346263508Sdim          if (ToType.isNull())
5347263508Sdim            ToType = CurToType.getUnqualifiedType();
5348263508Sdim          else if (HasUniqueTargetType &&
5349263508Sdim                   (CurToType.getUnqualifiedType() != ToType))
5350263508Sdim            HasUniqueTargetType = false;
5351263508Sdim        }
5352263508Sdim        ViableConversions.addDecl(I.getDecl(), I.getAccess());
5353210299Sed      }
5354234353Sdim    }
5355210299Sed  }
5356218893Sdim
5357263508Sdim  if (getLangOpts().CPlusPlus1y) {
5358263508Sdim    // C++1y [conv]p6:
5359263508Sdim    // ... An expression e of class type E appearing in such a context
5360263508Sdim    // is said to be contextually implicitly converted to a specified
5361263508Sdim    // type T and is well-formed if and only if e can be implicitly
5362263508Sdim    // converted to a type T that is determined as follows: E is searched
5363263508Sdim    // for conversion functions whose return type is cv T or reference to
5364263508Sdim    // cv T such that T is allowed by the context. There shall be
5365263508Sdim    // exactly one such T.
5366218893Sdim
5367263508Sdim    // If no unique T is found:
5368263508Sdim    if (ToType.isNull()) {
5369263508Sdim      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5370263508Sdim                                     HadMultipleCandidates,
5371263508Sdim                                     ExplicitConversions))
5372210299Sed        return ExprError();
5373263508Sdim      return finishContextualImplicitConversion(*this, Loc, From, Converter);
5374210299Sed    }
5375218893Sdim
5376263508Sdim    // If more than one unique Ts are found:
5377263508Sdim    if (!HasUniqueTargetType)
5378263508Sdim      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5379263508Sdim                                         ViableConversions);
5380218893Sdim
5381263508Sdim    // If one unique T is found:
5382263508Sdim    // First, build a candidate set from the previously recorded
5383263508Sdim    // potentially viable conversions.
5384263508Sdim    OverloadCandidateSet CandidateSet(Loc);
5385263508Sdim    collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5386263508Sdim                                      CandidateSet);
5387218893Sdim
5388263508Sdim    // Then, perform overload resolution over the candidate set.
5389263508Sdim    OverloadCandidateSet::iterator Best;
5390263508Sdim    switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5391263508Sdim    case OR_Success: {
5392263508Sdim      // Apply this conversion.
5393263508Sdim      DeclAccessPair Found =
5394263508Sdim          DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5395263508Sdim      if (recordConversion(*this, Loc, From, Converter, T,
5396263508Sdim                           HadMultipleCandidates, Found))
5397210299Sed        return ExprError();
5398263508Sdim      break;
5399210299Sed    }
5400263508Sdim    case OR_Ambiguous:
5401263508Sdim      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5402263508Sdim                                         ViableConversions);
5403263508Sdim    case OR_No_Viable_Function:
5404263508Sdim      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5405263508Sdim                                     HadMultipleCandidates,
5406263508Sdim                                     ExplicitConversions))
5407263508Sdim        return ExprError();
5408263508Sdim    // fall through 'OR_Deleted' case.
5409263508Sdim    case OR_Deleted:
5410263508Sdim      // We'll complain below about a non-integral condition type.
5411263508Sdim      break;
5412263508Sdim    }
5413263508Sdim  } else {
5414263508Sdim    switch (ViableConversions.size()) {
5415263508Sdim    case 0: {
5416263508Sdim      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5417263508Sdim                                     HadMultipleCandidates,
5418263508Sdim                                     ExplicitConversions))
5419263508Sdim        return ExprError();
5420218893Sdim
5421263508Sdim      // We'll complain below about a non-integral condition type.
5422263508Sdim      break;
5423210299Sed    }
5424263508Sdim    case 1: {
5425263508Sdim      // Apply this conversion.
5426263508Sdim      DeclAccessPair Found = ViableConversions[0];
5427263508Sdim      if (recordConversion(*this, Loc, From, Converter, T,
5428263508Sdim                           HadMultipleCandidates, Found))
5429263508Sdim        return ExprError();
5430263508Sdim      break;
5431263508Sdim    }
5432263508Sdim    default:
5433263508Sdim      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5434263508Sdim                                         ViableConversions);
5435263508Sdim    }
5436210299Sed  }
5437218893Sdim
5438263508Sdim  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///
5446239462Sdim/// \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,
5452249423Sdim                           ArrayRef<Expr *> Args,
5453193326Sed                           OverloadCandidateSet& CandidateSet,
5454193326Sed                           bool SuppressUserConversions,
5455234353Sdim                           bool PartialOverloading,
5456234353Sdim                           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(),
5474234353Sdim                         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
5484263508Sdim  // C++11 [class.copy]p11: [DR1402]
5485263508Sdim  //   A defaulted move constructor that is defined as deleted is ignored by
5486263508Sdim  //   overload resolution.
5487263508Sdim  CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5488263508Sdim  if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5489263508Sdim      Constructor->isMoveConstructor())
5490263508Sdim    return;
5491263508Sdim
5492199990Srdivacky  // Overload resolution is always an unevaluated context.
5493212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5494199990Srdivacky
5495263508Sdim  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());
5500234353Sdim    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
5508234353Sdim  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;
5514234353Sdim  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).
5521234353Sdim  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();
5534234353Sdim  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
5541226633Sdim  // (CUDA B.1): Check for invalid calls between targets.
5542234353Sdim  if (getLangOpts().CUDA)
5543226633Sdim    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5544226633Sdim      if (CheckCUDATarget(Caller, Function)) {
5545226633Sdim        Candidate.Viable = false;
5546226633Sdim        Candidate.FailureKind = ovl_fail_bad_target;
5547226633Sdim        return;
5548226633Sdim      }
5549226633Sdim
5550193326Sed  // Determine the implicit conversion sequences for each of the
5551193326Sed  // arguments.
5552234353Sdim  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=*/
5564234353Sdim                                  getLangOpts().ObjCAutoRefCount,
5565234353Sdim                                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
5581263508Sdim/// the overload candidate set.
5582203955Srdivackyvoid Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5583249423Sdim                                 ArrayRef<Expr *> Args,
5584193326Sed                                 OverloadCandidateSet& CandidateSet,
5585234353Sdim                                 bool SuppressUserConversions,
5586234353Sdim                               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),
5594234353Sdim                           Args.slice(1), CandidateSet,
5595234353Sdim                           SuppressUserConversions);
5596198092Srdivacky      else
5597234353Sdim        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()),
5605234353Sdim                                   ExplicitTemplateArgs,
5606218893Sdim                                   Args[0]->getType(),
5607234353Sdim                                   Args[0]->Classify(Context), Args.slice(1),
5608234353Sdim                                   CandidateSet, SuppressUserConversions);
5609198092Srdivacky      else
5610205408Srdivacky        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5611234353Sdim                                     ExplicitTemplateArgs, Args,
5612234353Sdim                                     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,
5622251662Sdim                              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,
5636234353Sdim                               ObjectType, ObjectClassification,
5637251662Sdim                               Args, CandidateSet,
5638207619Srdivacky                               SuppressUserConversions);
5639199482Srdivacky  } else {
5640205408Srdivacky    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5641234353Sdim                       ObjectType, ObjectClassification,
5642251662Sdim                       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,
5658249423Sdim                         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
5670263508Sdim  // C++11 [class.copy]p23: [DR1402]
5671263508Sdim  //   A defaulted move assignment operator that is defined as deleted is
5672263508Sdim  //   ignored by overload resolution.
5673263508Sdim  if (Method->isDefaulted() && Method->isDeleted() &&
5674263508Sdim      Method->isMoveAssignmentOperator())
5675263508Sdim    return;
5676263508Sdim
5677199990Srdivacky  // Overload resolution is always an unevaluated context.
5678212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5679199990Srdivacky
5680193326Sed  // Add this candidate
5681234353Sdim  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5682205408Srdivacky  Candidate.FoundDecl = FoundDecl;
5683193326Sed  Candidate.Function = Method;
5684193326Sed  Candidate.IsSurrogate = false;
5685193326Sed  Candidate.IgnoreObjectArgument = false;
5686234353Sdim  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).
5693234353Sdim  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();
5705234353Sdim  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.
5732234353Sdim  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=*/
5744234353Sdim                                  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,
5769249423Sdim                                 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.
5784243830Sdim  TemplateDeductionInfo Info(CandidateSet.getLocation());
5785198092Srdivacky  FunctionDecl *Specialization = 0;
5786198092Srdivacky  if (TemplateDeductionResult Result
5787234353Sdim      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5788234353Sdim                                Specialization, Info)) {
5789234353Sdim    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;
5796234353Sdim    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,
5808234353Sdim                     ActingContext, ObjectType, ObjectClassification, Args,
5809234353Sdim                     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,
5819249423Sdim                                   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.
5834243830Sdim  TemplateDeductionInfo Info(CandidateSet.getLocation());
5835195099Sed  FunctionDecl *Specialization = 0;
5836195099Sed  if (TemplateDeductionResult Result
5837234353Sdim        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5838234353Sdim                                  Specialization, Info)) {
5839234353Sdim    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;
5846234353Sdim    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?");
5855234353Sdim  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5856207619Srdivacky                       SuppressUserConversions);
5857195099Sed}
5858198092Srdivacky
5859263508Sdim/// Determine whether this is an allowable conversion from the result
5860263508Sdim/// of an explicit conversion operator to the expected type, per C++
5861263508Sdim/// [over.match.conv]p1 and [over.match.ref]p1.
5862263508Sdim///
5863263508Sdim/// \param ConvType The return type of the conversion function.
5864263508Sdim///
5865263508Sdim/// \param ToType The type we are converting to.
5866263508Sdim///
5867263508Sdim/// \param AllowObjCPointerConversion Allow a conversion from one
5868263508Sdim/// Objective-C pointer to another.
5869263508Sdim///
5870263508Sdim/// \returns true if the conversion is allowable, false otherwise.
5871263508Sdimstatic bool isAllowableExplicitConversion(Sema &S,
5872263508Sdim                                          QualType ConvType, QualType ToType,
5873263508Sdim                                          bool AllowObjCPointerConversion) {
5874263508Sdim  QualType ToNonRefType = ToType.getNonReferenceType();
5875263508Sdim
5876263508Sdim  // Easy case: the types are the same.
5877263508Sdim  if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
5878263508Sdim    return true;
5879263508Sdim
5880263508Sdim  // Allow qualification conversions.
5881263508Sdim  bool ObjCLifetimeConversion;
5882263508Sdim  if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
5883263508Sdim                                  ObjCLifetimeConversion))
5884263508Sdim    return true;
5885263508Sdim
5886263508Sdim  // If we're not allowed to consider Objective-C pointer conversions,
5887263508Sdim  // we're done.
5888263508Sdim  if (!AllowObjCPointerConversion)
5889263508Sdim    return false;
5890263508Sdim
5891263508Sdim  // Is this an Objective-C pointer conversion?
5892263508Sdim  bool IncompatibleObjC = false;
5893263508Sdim  QualType ConvertedType;
5894263508Sdim  return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
5895263508Sdim                                   IncompatibleObjC);
5896263508Sdim}
5897263508Sdim
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,
5909263508Sdim                             OverloadCandidateSet& CandidateSet,
5910263508Sdim                             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
5917251662Sdim  // If the conversion function has an undeduced return type, trigger its
5918251662Sdim  // deduction now.
5919251662Sdim  if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5920251662Sdim    if (DeduceReturnType(Conversion, From->getExprLoc()))
5921251662Sdim      return;
5922251662Sdim    ConvType = Conversion->getConversionType().getNonReferenceType();
5923251662Sdim  }
5924251662Sdim
5925263508Sdim  // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
5926263508Sdim  // operator is only a candidate if its return type is the target type or
5927263508Sdim  // can be converted to the target type with a qualification conversion.
5928263508Sdim  if (Conversion->isExplicit() &&
5929263508Sdim      !isAllowableExplicitConversion(*this, ConvType, ToType,
5930263508Sdim                                     AllowObjCConversionOnExplicit))
5931263508Sdim    return;
5932263508Sdim
5933199990Srdivacky  // Overload resolution is always an unevaluated context.
5934212904Sdim  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5935199990Srdivacky
5936193326Sed  // Add this candidate
5937234353Sdim  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.
5992234353Sdim  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);
6012251662Sdim  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:
6052226633Sdim    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,
6067263508Sdim                                     OverloadCandidateSet &CandidateSet,
6068263508Sdim                                     bool AllowObjCConversionOnExplicit) {
6069198092Srdivacky  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6070198092Srdivacky         "Only conversion function templates permitted here");
6071198092Srdivacky
6072198092Srdivacky  if (!CandidateSet.isNewCandidate(FunctionTemplate))
6073198092Srdivacky    return;
6074198092Srdivacky
6075243830Sdim  TemplateDeductionInfo Info(CandidateSet.getLocation());
6076198092Srdivacky  CXXConversionDecl *Specialization = 0;
6077198092Srdivacky  if (TemplateDeductionResult Result
6078198092Srdivacky        = DeduceTemplateArguments(FunctionTemplate, ToType,
6079198092Srdivacky                                  Specialization, Info)) {
6080234353Sdim    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,
6097263508Sdim                         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,
6110249423Sdim                                 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
6118234353Sdim  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;
6125234353Sdim  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;
6146226633Sdim  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6147193326Sed  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6148226633Sdim  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).
6159234353Sdim  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.
6167234353Sdim  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.
6176251662Sdim  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=*/
6188234353Sdim                                  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,
6213251662Sdim                                       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
6228251662Sdim  //     -- If T1 is a complete class type or a class currently being
6229251662Sdim  //        defined, the set of member candidates is the result of the
6230251662Sdim  //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6231251662Sdim  //        the set of member candidates is empty.
6232198092Srdivacky  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6233251662Sdim    // Complete the type if it can be completed.
6234251662Sdim    RequireCompleteType(OpLoc, T1, 0);
6235251662Sdim    // If the type is neither complete nor being defined, bail out now.
6236251662Sdim    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(),
6248251662Sdim                         Args[0]->Classify(Context),
6249251662Sdim                         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,
6264251662Sdim                               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
6272251662Sdim  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;
6278251662Sdim  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;
6284251662Sdim  Candidate.ExplicitCallArguments = Args.size();
6285251662Sdim  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=*/
6309234353Sdim                                  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
6319263508Sdimnamespace {
6320263508Sdim
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
6410263508Sdim} // end anonymous namespace
6411263508Sdim
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) {
6433239462Sdim    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6434239462Sdim    PointeeTy = PTy->getPointeeType();
6435239462Sdim    buildObjCPtr = true;
6436239462Sdim  } else {
6437239462Sdim    PointeeTy = PointerTy->getPointeeType();
6438212904Sdim  }
6439239462Sdim
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;
6446239462Sdim
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;
6454239462Sdim    // Skip over volatile if no volatile found anywhere in the types.
6455198398Srdivacky    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6456239462Sdim
6457239462Sdim    // Skip over restrict if no restrict found anywhere in the types, or if
6458239462Sdim    // the type cannot be restrict-qualified.
6459239462Sdim    if ((CVR & Qualifiers::Restrict) &&
6460239462Sdim        (!hasRestrict ||
6461239462Sdim         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6462239462Sdim      continue;
6463239462Sdim
6464239462Sdim    // Build qualified pointee type.
6465198092Srdivacky    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6466239462Sdim
6467239462Sdim    // Build qualified pointer type.
6468239462Sdim    QualType QPointerTy;
6469212904Sdim    if (!buildObjCPtr)
6470239462Sdim      QPointerTy = Context.getPointerType(QPointeeTy);
6471212904Sdim    else
6472239462Sdim      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6473239462Sdim
6474239462Sdim    // Insert qualified pointer type.
6475239462Sdim    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());
6587249423Sdim    std::pair<CXXRecordDecl::conversion_iterator,
6588249423Sdim              CXXRecordDecl::conversion_iterator>
6589249423Sdim      Conversions = ClassDecl->getVisibleConversionFunctions();
6590249423Sdim    for (CXXRecordDecl::conversion_iterator
6591249423Sdim           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,
6615251662Sdim                                                   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;
6622251662Sdim  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;
6630251662Sdim    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
6656249423Sdim    std::pair<CXXRecordDecl::conversion_iterator,
6657249423Sdim              CXXRecordDecl::conversion_iterator>
6658249423Sdim      Conversions = ClassDecl->getVisibleConversionFunctions();
6659218893Sdim
6660249423Sdim    for (CXXRecordDecl::conversion_iterator
6661249423Sdim           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) {
6673239462Sdim          if (CanTy.isRestrictQualified())
6674239462Sdim            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;
6701251662Sdim  ArrayRef<Expr *> Args;
6702198398Srdivacky  Qualifiers VisibleTypeConversionsQuals;
6703218893Sdim  bool HasArithmeticOrEnumeralCandidateType;
6704226633Sdim  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;
6712239462Sdim  static const unsigned LastIntegralType = 20;
6713218893Sdim  static const unsigned FirstPromotedIntegralType = 3,
6714239462Sdim                        LastPromotedIntegralType = 11;
6715218893Sdim  static const unsigned FirstPromotedArithmeticType = 0,
6716239462Sdim                        LastPromotedArithmeticType = 11;
6717239462Sdim  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,
6733239462Sdim      &ASTContext::Int128Ty,
6734218893Sdim      &ASTContext::UnsignedIntTy,
6735218893Sdim      &ASTContext::UnsignedLongTy,
6736218893Sdim      &ASTContext::UnsignedLongLongTy,
6737239462Sdim      &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.
6750239462Sdim      // 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).
6769239462Sdim    // We assume that int128 has a higher rank than long long on all platforms.
6770218893Sdim    enum PromotedType {
6771239462Sdim            Dep=-1,
6772239462Sdim            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6773218893Sdim    };
6774239462Sdim    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6775218893Sdim                                        [LastPromotedArithmeticType] = {
6776239462Sdim/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6777239462Sdim/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6778239462Sdim/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6779239462Sdim/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6780239462Sdim/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6781239462Sdim/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6782239462Sdim/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6783239462Sdim/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6784239462Sdim/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6785239462Sdim/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6786239462Sdim/*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,
6816239462Sdim                                           bool HasVolatile,
6817239462Sdim                                           bool HasRestrict) {
6818218893Sdim    QualType ParamTypes[2] = {
6819218893Sdim      S.Context.getLValueReferenceType(CandidateTy),
6820218893Sdim      S.Context.IntTy
6821218893Sdim    };
6822218893Sdim
6823218893Sdim    // Non-volatile version.
6824251662Sdim    if (Args.size() == 1)
6825251662Sdim      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6826193326Sed    else
6827251662Sdim      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));
6835251662Sdim      if (Args.size() == 1)
6836251662Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6837193326Sed      else
6838251662Sdim        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6839193326Sed    }
6840239462Sdim
6841239462Sdim    // Add restrict version only if there are conversions to a restrict type
6842239462Sdim    // and our candidate type is a non-restrict-qualified pointer.
6843239462Sdim    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6844239462Sdim        !CandidateTy.isRestrictQualified()) {
6845239462Sdim      ParamTypes[0]
6846239462Sdim        = S.Context.getLValueReferenceType(
6847239462Sdim            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6848251662Sdim      if (Args.size() == 1)
6849251662Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6850239462Sdim      else
6851251662Sdim        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6852239462Sdim
6853239462Sdim      if (HasVolatile) {
6854239462Sdim        ParamTypes[0]
6855239462Sdim          = S.Context.getLValueReferenceType(
6856239462Sdim              S.Context.getCVRQualifiedType(CandidateTy,
6857239462Sdim                                            (Qualifiers::Volatile |
6858239462Sdim                                             Qualifiers::Restrict)));
6859251662Sdim        if (Args.size() == 1)
6860251662Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6861239462Sdim        else
6862251662Sdim          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6863239462Sdim      }
6864239462Sdim    }
6865239462Sdim
6866218893Sdim  }
6867193326Sed
6868218893Sdimpublic:
6869218893Sdim  BuiltinOperatorOverloadBuilder(
6870251662Sdim    Sema &S, ArrayRef<Expr *> Args,
6871218893Sdim    Qualifiers VisibleTypeConversionsQuals,
6872218893Sdim    bool HasArithmeticOrEnumeralCandidateType,
6873226633Sdim    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6874218893Sdim    OverloadCandidateSet &CandidateSet)
6875251662Sdim    : 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)
6885239462Sdim             == 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)
6891239462Sdim             == 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),
6920239462Sdim        VisibleTypeConversionsQuals.hasVolatile(),
6921239462Sdim        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,
6945239462Sdim        (!(*Ptr).isVolatileQualified() &&
6946239462Sdim         VisibleTypeConversionsQuals.hasVolatile()),
6947239462Sdim        (!(*Ptr).isRestrictQualified() &&
6948239462Sdim         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),
6977251662Sdim                            &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);
6994251662Sdim      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;
7003251662Sdim      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;
7018251662Sdim      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);
7034251662Sdim      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;
7043251662Sdim      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
7057251662Sdim    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 };
7068251662Sdim        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() {
7085243830Sdim    // C++ [over.match.oper]p3:
7086243830Sdim    //   [...]the built-in candidates include all of the candidate operator
7087243830Sdim    //   functions defined in 13.6 that, compared to the given operator, [...]
7088243830Sdim    //   do not have the same parameter-type-list as any non-template non-member
7089243830Sdim    //   candidate.
7090218893Sdim    //
7091243830Sdim    // Note that in practice, this only affects enumeration types because there
7092243830Sdim    // aren't any built-in candidates of record type, and a user-defined operator
7093243830Sdim    // must have an operand of record or enumeration type. Also, the only other
7094243830Sdim    // 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
7100251662Sdim    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
7109243830Sdim          if (C->Function->isFunctionTemplateSpecialization())
7110243830Sdim            continue;
7111243830Sdim
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
7133251662Sdim    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 };
7143251662Sdim        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 };
7159251662Sdim        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) &&
7165251662Sdim            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7166223017Sdim                                                             NullPtrTy))) {
7167223017Sdim          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7168251662Sdim          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*);
7213251662Sdim          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,
7222251662Sdim                                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);
7270251662Sdim        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
7293251662Sdim        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);
7325251662Sdim        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
7349251662Sdim        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
7359251662Sdim        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      };
7399251662Sdim      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7400218893Sdim                            /*IsAssigmentOperator=*/ isEqualOp);
7401193326Sed
7402239462Sdim      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7403239462Sdim                          VisibleTypeConversionsQuals.hasVolatile();
7404239462Sdim      if (NeedVolatile) {
7405193326Sed        // volatile version
7406218893Sdim        ParamTypes[0] =
7407218893Sdim          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7408251662Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7409218893Sdim                              /*IsAssigmentOperator=*/isEqualOp);
7410193326Sed      }
7411239462Sdim
7412239462Sdim      if (!(*Ptr).isRestrictQualified() &&
7413239462Sdim          VisibleTypeConversionsQuals.hasRestrict()) {
7414239462Sdim        // restrict version
7415239462Sdim        ParamTypes[0]
7416239462Sdim          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7417251662Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7418239462Sdim                              /*IsAssigmentOperator=*/isEqualOp);
7419239462Sdim
7420239462Sdim        if (NeedVolatile) {
7421239462Sdim          // volatile restrict version
7422239462Sdim          ParamTypes[0]
7423239462Sdim            = S.Context.getLValueReferenceType(
7424239462Sdim                S.Context.getCVRQualifiedType(*Ptr,
7425239462Sdim                                              (Qualifiers::Volatile |
7426239462Sdim                                               Qualifiers::Restrict)));
7427251662Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7428239462Sdim                                /*IsAssigmentOperator=*/isEqualOp);
7429239462Sdim        }
7430239462Sdim      }
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
7448251662Sdim        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7449218893Sdim                              /*IsAssigmentOperator=*/true);
7450218893Sdim
7451239462Sdim        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7452239462Sdim                           VisibleTypeConversionsQuals.hasVolatile();
7453239462Sdim        if (NeedVolatile) {
7454218893Sdim          // volatile version
7455218893Sdim          ParamTypes[0] =
7456218893Sdim            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7457251662Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7458251662Sdim                                /*IsAssigmentOperator=*/true);
7459218893Sdim        }
7460239462Sdim
7461239462Sdim        if (!(*Ptr).isRestrictQualified() &&
7462239462Sdim            VisibleTypeConversionsQuals.hasRestrict()) {
7463239462Sdim          // restrict version
7464239462Sdim          ParamTypes[0]
7465239462Sdim            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7466251662Sdim          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7467251662Sdim                                /*IsAssigmentOperator=*/true);
7468239462Sdim
7469239462Sdim          if (NeedVolatile) {
7470239462Sdim            // volatile restrict version
7471239462Sdim            ParamTypes[0]
7472239462Sdim              = S.Context.getLValueReferenceType(
7473239462Sdim                  S.Context.getCVRQualifiedType(*Ptr,
7474239462Sdim                                                (Qualifiers::Volatile |
7475239462Sdim                                                 Qualifiers::Restrict)));
7476251662Sdim            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7477251662Sdim                                  /*IsAssigmentOperator=*/true);
7478239462Sdim          }
7479239462Sdim        }
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));
7509251662Sdim        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]);
7517251662Sdim          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);
7536251662Sdim        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]);
7543251662Sdim          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));
7575251662Sdim        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]);
7581251662Sdim          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;
7596251662Sdim    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 };
7602251662Sdim    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)
7630251662Sdim      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*)
7645251662Sdim      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);
7696251662Sdim        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 };
7724251662Sdim        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 };
7735251662Sdim        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7736218893Sdim      }
7737218893Sdim
7738249423Sdim      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 };
7750251662Sdim          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.
7764263508Sdimvoid Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7765263508Sdim                                        SourceLocation OpLoc,
7766263508Sdim                                        ArrayRef<Expr *> Args,
7767263508Sdim                                        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();
7774251662Sdim  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;
7779226633Sdim  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7780251662Sdim  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.
7798226633Sdim  //
7799226633Sdim  // We can't exit early for !, ||, or &&, since there we have always have
7800226633Sdim  // 'bool' overloads.
7801251662Sdim  if (!HasNonRecordCandidateType &&
7802226633Sdim      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7803218893Sdim    return;
7804218893Sdim
7805218893Sdim  // Setup an object to manage the common state for building overloads.
7806251662Sdim  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:
7815226633Sdim    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:
7822226633Sdim    llvm_unreachable(
7823226633Sdim                    "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
7833251662Sdim    if (Args.size() == 1)
7834218893Sdim      OpBuilder.addUnaryPlusPointerOverloads();
7835218893Sdim    // Fall through.
7836218893Sdim
7837218893Sdim  case OO_Minus: // '-' is either unary or binary
7838251662Sdim    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
7847251662Sdim    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
7885251662Sdim    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,
7954234353Sdim                                           bool Operator, SourceLocation Loc,
7955249423Sdim                                           ArrayRef<Expr *> Args,
7956221345Sdim                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7957198092Srdivacky                                           OverloadCandidateSet& CandidateSet,
7958243830Sdim                                           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?
7969243830Sdim  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
7989234353Sdim      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7990234353Sdim                           PartialOverloading);
7991198092Srdivacky    } else
7992203955Srdivacky      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7993205408Srdivacky                                   FoundDecl, ExplicitTemplateArgs,
7994234353Sdim                                   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...
8027234353Sdim  unsigned NumArgs = Cand1.NumConversions;
8028234353Sdim  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,
8072263508Sdim                                         Cand1.ExplicitCallArguments,
8073263508Sdim                                         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)) {
8086234353Sdim    // First check whether we prefer one of the conversion functions over the
8087234353Sdim    // other. This only distinguishes the results in non-standard, extension
8088234353Sdim    // cases such as the conversion from a lambda closure type to a function
8089234353Sdim    // pointer or block.
8090234353Sdim    ImplicitConversionSequence::CompareKind FuncResult
8091234353Sdim      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8092234353Sdim    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8093234353Sdim      return FuncResult;
8094234353Sdim
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///
8118239462Sdim/// \param Loc The location of the function name (or operator symbol) for
8119194613Sed/// which overload resolution occurs.
8120194613Sed///
8121239462Sdim/// \param Best If overload resolution was successful or found a deleted
8122239462Sdim/// 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
8218234353Sdim    if (Meth->isCopyAssignmentOperator())
8219234353Sdim      return oc_implicit_copy_assignment;
8220234353Sdim
8221234353Sdim    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8222234353Sdim    return oc_method;
8223202379Srdivacky  }
8224202379Srdivacky
8225202379Srdivacky  return isTemplate ? oc_function_template : oc_function;
8226202379Srdivacky}
8227202379Srdivacky
8228263508Sdimvoid 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.
8241234353Sdimvoid Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8242202379Srdivacky  std::string FnDesc;
8243202379Srdivacky  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8244234353Sdim  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8245234353Sdim                             << (unsigned) K << FnDesc;
8246234353Sdim  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8247234353Sdim  Diag(Fn->getLocation(), PD);
8248218893Sdim  MaybeEmitInheritedConstructorNote(*this, Fn);
8249202379Srdivacky}
8250202379Srdivacky
8251263508Sdim// Notes the location of all overload candidates designated through
8252218893Sdim// OverloadedExpr
8253234353Sdimvoid 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()) ) {
8264234353Sdim      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8265218893Sdim    } else if (FunctionDecl *Fun
8266218893Sdim                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8267234353Sdim      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();
8281243830Sdim  // FIXME: The note limiting machinery is borrowed from
8282243830Sdim  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8283243830Sdim  // refactoring here.
8284243830Sdim  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8285243830Sdim  unsigned CandsShown = 0;
8286243830Sdim  AmbiguousConversionSequence::const_iterator I, E;
8287243830Sdim  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8288243830Sdim    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8289243830Sdim      break;
8290243830Sdim    ++CandsShown;
8291212904Sdim    S.NoteOverloadCandidate(*I);
8292202379Srdivacky  }
8293243830Sdim  if (I != E)
8294243830Sdim    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
8407226633Sdim  // Special diagnostic for failure to convert an initializer list, since
8408226633Sdim  // telling the user that it has type void is not useful.
8409226633Sdim  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8410226633Sdim    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8411226633Sdim      << (unsigned) FnKind << FnDesc
8412226633Sdim      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8413226633Sdim      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8414226633Sdim    MaybeEmitInheritedConstructorNote(S, Fn);
8415226633Sdim    return;
8416226633Sdim  }
8417226633Sdim
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>()) {
8456239462Sdim    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8457239462Sdim        !FromTy->isIncompleteType() &&
8458239462Sdim        !ToRefTy->getPointeeType()->isIncompleteType() &&
8459239462Sdim        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8460239462Sdim      BaseToDerivedConversion = 3;
8461239462Sdim    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8462239462Sdim               ToTy.getNonReferenceType().getCanonicalType() ==
8463239462Sdim               FromTy.getNonReferenceType().getCanonicalType()) {
8464239462Sdim      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8465239462Sdim        << (unsigned) FnKind << FnDesc
8466239462Sdim        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8467239462Sdim        << (unsigned) isObjectArgument << I + 1;
8468239462Sdim      MaybeEmitInheritedConstructorNote(S, Fn);
8469239462Sdim      return;
8470210299Sed    }
8471239462Sdim  }
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
8484226633Sdim  if (isa<ObjCObjectPointerType>(CFromTy) &&
8485226633Sdim      isa<PointerType>(CToTy)) {
8486226633Sdim      Qualifiers FromQs = CFromTy.getQualifiers();
8487226633Sdim      Qualifiers ToQs = CToTy.getQualifiers();
8488226633Sdim      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8489226633Sdim        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8490226633Sdim        << (unsigned) FnKind << FnDesc
8491226633Sdim        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8492226633Sdim        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8493226633Sdim        MaybeEmitInheritedConstructorNote(S, Fn);
8494226633Sdim        return;
8495226633Sdim      }
8496226633Sdim  }
8497226633Sdim
8498226633Sdim  // Emit the generic diagnostic and, optionally, add the hints to it.
8499226633Sdim  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8500226633Sdim  FDiag << (unsigned) FnKind << FnDesc
8501202379Srdivacky    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8502226633Sdim    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8503226633Sdim    << (unsigned) (Cand->Fix.Kind);
8504226633Sdim
8505226633Sdim  // If we can fix the conversion, suggest the FixIts.
8506234353Sdim  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8507234353Sdim       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8508226633Sdim    FDiag << *HI;
8509226633Sdim  S.Diag(Fn->getLocation(), FDiag);
8510226633Sdim
8511218893Sdim  MaybeEmitInheritedConstructorNote(S, Fn);
8512202379Srdivacky}
8513202379Srdivacky
8514263508Sdim/// Additional arity mismatch diagnosis specific to a function overload
8515263508Sdim/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8516263508Sdim/// over a candidate in any candidate set.
8517263508Sdimbool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8518263508Sdim                        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
8523263508Sdim  // 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)
8529263508Sdim    return true;
8530223017Sdim
8531263508Sdim  if (NumArgs < MinParams) {
8532263508Sdim    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8533263508Sdim           (Cand->FailureKind == ovl_fail_bad_deduction &&
8534263508Sdim            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8535263508Sdim  } else {
8536263508Sdim    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8537263508Sdim           (Cand->FailureKind == ovl_fail_bad_deduction &&
8538263508Sdim            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8539263508Sdim  }
8540263508Sdim
8541263508Sdim  return false;
8542263508Sdim}
8543263508Sdim
8544263508Sdim/// General arity mismatch diagnosis over a candidate in a candidate set.
8545263508Sdimvoid DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8546263508Sdim  assert(isa<FunctionDecl>(D) &&
8547263508Sdim      "The templated declaration should at least be a function"
8548263508Sdim      " when diagnosing bad template argument deduction due to too many"
8549263508Sdim      " or too few arguments");
8550263508Sdim
8551263508Sdim  FunctionDecl *Fn = cast<FunctionDecl>(D);
8552263508Sdim
8553263508Sdim  // TODO: treat calls to a missing default constructor as a special case
8554263508Sdim  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8555263508Sdim  unsigned MinParams = Fn->getMinRequiredArguments();
8556263508Sdim
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
8577239462Sdim  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8578239462Sdim    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8579239462Sdim      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8580239462Sdim      << Fn->getParamDecl(0) << NumFormalArgs;
8581239462Sdim  else
8582239462Sdim    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8583239462Sdim      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8584239462Sdim      << modeCount << NumFormalArgs;
8585218893Sdim  MaybeEmitInheritedConstructorNote(S, Fn);
8586202379Srdivacky}
8587202379Srdivacky
8588263508Sdim/// Arity mismatch diagnosis specific to a function overload candidate.
8589263508Sdimvoid DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8590263508Sdim                           unsigned NumFormalArgs) {
8591263508Sdim  if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8592263508Sdim    DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8593263508Sdim}
8594263508Sdim
8595263508SdimTemplateDecl *getDescribedTemplate(Decl *Templated) {
8596263508Sdim  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8597263508Sdim    return FD->getDescribedFunctionTemplate();
8598263508Sdim  else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8599263508Sdim    return RD->getDescribedClassTemplate();
8600263508Sdim
8601263508Sdim  llvm_unreachable("Unsupported: Getting the described template declaration"
8602263508Sdim                   " for bad deduction diagnosis");
8603263508Sdim}
8604263508Sdim
8605203955Srdivacky/// Diagnose a failed template-argument deduction.
8606263508Sdimvoid DiagnoseBadDeduction(Sema &S, Decl *Templated,
8607263508Sdim                          DeductionFailureInfo &DeductionFailure,
8608234353Sdim                          unsigned NumArgs) {
8609263508Sdim  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*>());
8614263508Sdim  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");
8620263508Sdim    S.Diag(Templated->getLocation(),
8621263508Sdim           diag::note_ovl_candidate_incomplete_deduction)
8622263508Sdim        << ParamD->getDeclName();
8623263508Sdim    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
8631263508Sdim    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).
8644263508Sdim    QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8645212904Sdim
8646263508Sdim    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8647263508Sdim        << ParamD->getDeclName() << Arg << NonCanonParam;
8648263508Sdim    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
8663263508Sdim    S.Diag(Templated->getLocation(),
8664263508Sdim           diag::note_ovl_candidate_inconsistent_deduction)
8665263508Sdim        << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8666263508Sdim        << *DeductionFailure.getSecondArg();
8667263508Sdim    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())
8674263508Sdim      S.Diag(Templated->getLocation(),
8675208600Srdivacky             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8676263508Sdim          << 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();
8686263508Sdim      S.Diag(Templated->getLocation(),
8687208600Srdivacky             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8688263508Sdim          << (index + 1);
8689208600Srdivacky    }
8690263508Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8691208600Srdivacky    return;
8692218893Sdim
8693208600Srdivacky  case Sema::TDK_TooManyArguments:
8694208600Srdivacky  case Sema::TDK_TooFewArguments:
8695263508Sdim    DiagnoseArityMismatch(S, Templated, NumArgs);
8696208600Srdivacky    return;
8697208600Srdivacky
8698208600Srdivacky  case Sema::TDK_InstantiationDepth:
8699263508Sdim    S.Diag(Templated->getLocation(),
8700263508Sdim           diag::note_ovl_candidate_instantiation_depth);
8701263508Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8702208600Srdivacky    return;
8703208600Srdivacky
8704208600Srdivacky  case Sema::TDK_SubstitutionFailure: {
8705239462Sdim    // Format the template argument list into the argument string.
8706249423Sdim    SmallString<128> TemplateArgString;
8707239462Sdim    if (TemplateArgumentList *Args =
8708263508Sdim            DeductionFailure.getTemplateArgumentList()) {
8709239462Sdim      TemplateArgString = " ";
8710239462Sdim      TemplateArgString += S.getTemplateArgumentBindingsText(
8711263508Sdim          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8712239462Sdim    }
8713239462Sdim
8714239462Sdim    // If this candidate was disabled by enable_if, say so.
8715263508Sdim    PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8716239462Sdim    if (PDiag && PDiag->second.getDiagID() ==
8717239462Sdim          diag::err_typename_nested_not_found_enable_if) {
8718239462Sdim      // FIXME: Use the source range of the condition, and the fully-qualified
8719239462Sdim      //        name of the enable_if template. These are both present in PDiag.
8720239462Sdim      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8721239462Sdim        << "'enable_if'" << TemplateArgString;
8722239462Sdim      return;
8723239462Sdim    }
8724239462Sdim
8725239462Sdim    // Format the SFINAE diagnostic into the argument string.
8726239462Sdim    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8727239462Sdim    //        formatted message in another diagnostic.
8728249423Sdim    SmallString<128> SFINAEArgString;
8729239462Sdim    SourceRange R;
8730239462Sdim    if (PDiag) {
8731239462Sdim      SFINAEArgString = ": ";
8732239462Sdim      R = SourceRange(PDiag->first, PDiag->first);
8733239462Sdim      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8734239462Sdim    }
8735239462Sdim
8736263508Sdim    S.Diag(Templated->getLocation(),
8737263508Sdim           diag::note_ovl_candidate_substitution_failure)
8738263508Sdim        << TemplateArgString << SFINAEArgString << R;
8739263508Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8740208600Srdivacky    return;
8741208600Srdivacky  }
8742218893Sdim
8743249423Sdim  case Sema::TDK_FailedOverloadResolution: {
8744263508Sdim    OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8745263508Sdim    S.Diag(Templated->getLocation(),
8746249423Sdim           diag::note_ovl_candidate_failed_overload_resolution)
8747263508Sdim        << R.Expression->getName();
8748249423Sdim    return;
8749249423Sdim  }
8750249423Sdim
8751251662Sdim  case Sema::TDK_NonDeducedMismatch: {
8752249423Sdim    // FIXME: Provide a source location to indicate what we couldn't match.
8753263508Sdim    TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8754263508Sdim    TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8755251662Sdim    if (FirstTA.getKind() == TemplateArgument::Template &&
8756251662Sdim        SecondTA.getKind() == TemplateArgument::Template) {
8757251662Sdim      TemplateName FirstTN = FirstTA.getAsTemplate();
8758251662Sdim      TemplateName SecondTN = SecondTA.getAsTemplate();
8759251662Sdim      if (FirstTN.getKind() == TemplateName::Template &&
8760251662Sdim          SecondTN.getKind() == TemplateName::Template) {
8761251662Sdim        if (FirstTN.getAsTemplateDecl()->getName() ==
8762251662Sdim            SecondTN.getAsTemplateDecl()->getName()) {
8763251662Sdim          // FIXME: This fixes a bad diagnostic where both templates are named
8764251662Sdim          // the same.  This particular case is a bit difficult since:
8765251662Sdim          // 1) It is passed as a string to the diagnostic printer.
8766251662Sdim          // 2) The diagnostic printer only attempts to find a better
8767251662Sdim          //    name for types, not decls.
8768251662Sdim          // Ideally, this should folded into the diagnostic printer.
8769263508Sdim          S.Diag(Templated->getLocation(),
8770251662Sdim                 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8771251662Sdim              << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8772251662Sdim          return;
8773251662Sdim        }
8774251662Sdim      }
8775251662Sdim    }
8776263508Sdim    // FIXME: For generic lambda parameters, check if the function is a lambda
8777263508Sdim    // call operator, and if so, emit a prettier and more informative
8778263508Sdim    // diagnostic that mentions 'auto' and lambda in addition to
8779263508Sdim    // (or instead of?) the canonical template type parameters.
8780263508Sdim    S.Diag(Templated->getLocation(),
8781263508Sdim           diag::note_ovl_candidate_non_deduced_mismatch)
8782263508Sdim        << FirstTA << SecondTA;
8783249423Sdim    return;
8784251662Sdim  }
8785203955Srdivacky  // TODO: diagnose these individually, then kill off
8786203955Srdivacky  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8787249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
8788263508Sdim    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8789263508Sdim    MaybeEmitInheritedConstructorNote(S, Templated);
8790203955Srdivacky    return;
8791203955Srdivacky  }
8792203955Srdivacky}
8793203955Srdivacky
8794263508Sdim/// Diagnose a failed template-argument deduction, for function calls.
8795263508Sdimvoid DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8796263508Sdim  unsigned TDK = Cand->DeductionFailure.Result;
8797263508Sdim  if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8798263508Sdim    if (CheckArityMismatch(S, Cand, NumArgs))
8799263508Sdim      return;
8800263508Sdim  }
8801263508Sdim  DiagnoseBadDeduction(S, Cand->Function, // pattern
8802263508Sdim                       Cand->DeductionFailure, NumArgs);
8803263508Sdim}
8804263508Sdim
8805226633Sdim/// CUDA: diagnose an invalid call across targets.
8806226633Sdimvoid DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8807226633Sdim  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8808226633Sdim  FunctionDecl *Callee = Cand->Function;
8809226633Sdim
8810226633Sdim  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8811226633Sdim                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8812226633Sdim
8813226633Sdim  std::string FnDesc;
8814226633Sdim  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8815226633Sdim
8816226633Sdim  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8817226633Sdim      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8818226633Sdim}
8819226633Sdim
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,
8834234353Sdim                           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)
8844234353Sdim      << FnKind << FnDesc
8845234353Sdim      << (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:
8862234353Sdim    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);
8871234353Sdim    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  }
8880226633Sdim
8881226633Sdim  case ovl_fail_bad_target:
8882226633Sdim    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,
8920243830Sdim                                  StringRef Opc,
8921202379Srdivacky                                  SourceLocation OpLoc,
8922202379Srdivacky                                  OverloadCandidate *Cand) {
8923234353Sdim  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();
8928234353Sdim  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) {
8941234353Sdim  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
8952263508Sdimstatic 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
8960263508Sdimstatic unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
8961226633Sdim  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8962226633Sdim  case Sema::TDK_Success:
8963226633Sdim    llvm_unreachable("TDK_success while diagnosing bad deduction");
8964226633Sdim
8965243830Sdim  case Sema::TDK_Invalid:
8966226633Sdim  case Sema::TDK_Incomplete:
8967226633Sdim    return 1;
8968226633Sdim
8969226633Sdim  case Sema::TDK_Underqualified:
8970226633Sdim  case Sema::TDK_Inconsistent:
8971226633Sdim    return 2;
8972226633Sdim
8973226633Sdim  case Sema::TDK_SubstitutionFailure:
8974226633Sdim  case Sema::TDK_NonDeducedMismatch:
8975249423Sdim  case Sema::TDK_MiscellaneousDeductionFailure:
8976226633Sdim    return 3;
8977226633Sdim
8978226633Sdim  case Sema::TDK_InstantiationDepth:
8979226633Sdim  case Sema::TDK_FailedOverloadResolution:
8980226633Sdim    return 4;
8981226633Sdim
8982226633Sdim  case Sema::TDK_InvalidExplicitArguments:
8983226633Sdim    return 5;
8984226633Sdim
8985226633Sdim  case Sema::TDK_TooManyArguments:
8986226633Sdim  case Sema::TDK_TooFewArguments:
8987226633Sdim    return 6;
8988226633Sdim  }
8989226633Sdim  llvm_unreachable("Unhandled deduction result");
8990226633Sdim}
8991226633Sdim
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
9031226633Sdim        // The conversion that can be fixed with a smaller number of changes,
9032226633Sdim        // comes first.
9033226633Sdim        unsigned numLFixes = L->Fix.NumConversionsFixed;
9034226633Sdim        unsigned numRFixes = R->Fix.NumConversionsFixed;
9035226633Sdim        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9036226633Sdim        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9037226633Sdim        if (numLFixes != numRFixes) {
9038226633Sdim          if (numLFixes < numRFixes)
9039226633Sdim            return true;
9040226633Sdim          else
9041226633Sdim            return false;
9042226633Sdim        }
9043226633Sdim
9044202879Srdivacky        // If there's any ordering between the defined conversions...
9045202879Srdivacky        // FIXME: this might not be transitive.
9046234353Sdim        assert(L->NumConversions == R->NumConversions);
9047202879Srdivacky
9048202879Srdivacky        int leftBetter = 0;
9049204643Srdivacky        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9050234353Sdim        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
9072226633Sdim      if (L->FailureKind == ovl_fail_bad_deduction) {
9073226633Sdim        if (R->FailureKind != ovl_fail_bad_deduction)
9074226633Sdim          return true;
9075226633Sdim
9076226633Sdim        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9077226633Sdim          return RankDeductionFailure(L->DeductionFailure)
9078226633Sdim               < RankDeductionFailure(R->DeductionFailure);
9079226633Sdim      } else if (R->FailureKind == ovl_fail_bad_deduction)
9080226633Sdim        return false;
9081226633Sdim
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
9098226633Sdim/// computes up to the first. Produces the FixIt set if possible.
9099202879Srdivackyvoid CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9100249423Sdim                                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
9106226633Sdim  // We only want the FixIts if all the arguments can be corrected.
9107226633Sdim  bool Unfixable = false;
9108226633Sdim  // Use a implicit copy initialization to check conversion fixes.
9109226633Sdim  Cand->Fix.setConversionChecker(TryCopyInitialization);
9110226633Sdim
9111202879Srdivacky  // Skip forward to the first bad conversion.
9112204643Srdivacky  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9113234353Sdim  unsigned ConvCount = Cand->NumConversions;
9114202879Srdivacky  while (true) {
9115202879Srdivacky    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9116202879Srdivacky    ConvIdx++;
9117226633Sdim    if (Cand->Conversions[ConvIdx - 1].isBad()) {
9118226633Sdim      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9119202879Srdivacky      break;
9120226633Sdim    }
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=*/
9158234353Sdim                                  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) {
9165226633Sdim    if (ArgIdx < NumArgsInProto) {
9166202879Srdivacky      Cand->Conversions[ConvIdx]
9167207619Srdivacky        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
9168218893Sdim                                SuppressUserConversions,
9169224145Sdim                                /*InOverloadResolution=*/true,
9170224145Sdim                                /*AllowObjCWritebackConversion=*/
9171234353Sdim                                  S.getLangOpts().ObjCAutoRefCount);
9172226633Sdim      // Store the FixIt in the candidate if it exists.
9173226633Sdim      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9174226633Sdim        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9175226633Sdim    }
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,
9188249423Sdim                                          ArrayRef<Expr *> Args,
9189243830Sdim                                          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.
9193226633Sdim  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) {
9199234353Sdim      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
9212226633Sdim  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9213243830Sdim  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.
9221243830Sdim    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9222210299Sed      break;
9223210299Sed    }
9224210299Sed    ++CandsShown;
9225210299Sed
9226202379Srdivacky    if (Cand->Function)
9227234353Sdim      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
9253263508Sdimstatic SourceLocation
9254263508SdimGetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9255263508Sdim  return Cand->Specialization ? Cand->Specialization->getLocation()
9256263508Sdim                              : SourceLocation();
9257263508Sdim}
9258263508Sdim
9259263508Sdimstruct CompareTemplateSpecCandidatesForDisplay {
9260263508Sdim  Sema &S;
9261263508Sdim  CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9262263508Sdim
9263263508Sdim  bool operator()(const TemplateSpecCandidate *L,
9264263508Sdim                  const TemplateSpecCandidate *R) {
9265263508Sdim    // Fast-path this check.
9266263508Sdim    if (L == R)
9267263508Sdim      return false;
9268263508Sdim
9269263508Sdim    // Assuming that both candidates are not matches...
9270263508Sdim
9271263508Sdim    // Sort by the ranking of deduction failures.
9272263508Sdim    if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9273263508Sdim      return RankDeductionFailure(L->DeductionFailure) <
9274263508Sdim             RankDeductionFailure(R->DeductionFailure);
9275263508Sdim
9276263508Sdim    // Sort everything else by location.
9277263508Sdim    SourceLocation LLoc = GetLocationForCandidate(L);
9278263508Sdim    SourceLocation RLoc = GetLocationForCandidate(R);
9279263508Sdim
9280263508Sdim    // Put candidates without locations (e.g. builtins) at the end.
9281263508Sdim    if (LLoc.isInvalid())
9282263508Sdim      return false;
9283263508Sdim    if (RLoc.isInvalid())
9284263508Sdim      return true;
9285263508Sdim
9286263508Sdim    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9287263508Sdim  }
9288263508Sdim};
9289263508Sdim
9290263508Sdim/// Diagnose a template argument deduction failure.
9291263508Sdim/// We are treating these failures as overload failures due to bad
9292263508Sdim/// deductions.
9293263508Sdimvoid TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9294263508Sdim  DiagnoseBadDeduction(S, Specialization, // pattern
9295263508Sdim                       DeductionFailure, /*NumArgs=*/0);
9296263508Sdim}
9297263508Sdim
9298263508Sdimvoid TemplateSpecCandidateSet::destroyCandidates() {
9299263508Sdim  for (iterator i = begin(), e = end(); i != e; ++i) {
9300263508Sdim    i->DeductionFailure.Destroy();
9301263508Sdim  }
9302263508Sdim}
9303263508Sdim
9304263508Sdimvoid TemplateSpecCandidateSet::clear() {
9305263508Sdim  destroyCandidates();
9306263508Sdim  Candidates.clear();
9307263508Sdim}
9308263508Sdim
9309263508Sdim/// NoteCandidates - When no template specialization match is found, prints
9310263508Sdim/// diagnostic messages containing the non-matching specializations that form
9311263508Sdim/// the candidate set.
9312263508Sdim/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9313263508Sdim/// OCD == OCD_AllCandidates and Cand->Viable == false.
9314263508Sdimvoid TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9315263508Sdim  // Sort the candidates by position (assuming no candidate is a match).
9316263508Sdim  // Sorting directly would be prohibitive, so we make a set of pointers
9317263508Sdim  // and sort those.
9318263508Sdim  SmallVector<TemplateSpecCandidate *, 32> Cands;
9319263508Sdim  Cands.reserve(size());
9320263508Sdim  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9321263508Sdim    if (Cand->Specialization)
9322263508Sdim      Cands.push_back(Cand);
9323263508Sdim    // Otherwise, this is a non matching builtin candidate.  We do not,
9324263508Sdim    // in general, want to list every possible builtin candidate.
9325263508Sdim  }
9326263508Sdim
9327263508Sdim  std::sort(Cands.begin(), Cands.end(),
9328263508Sdim            CompareTemplateSpecCandidatesForDisplay(S));
9329263508Sdim
9330263508Sdim  // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9331263508Sdim  // for generalization purposes (?).
9332263508Sdim  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9333263508Sdim
9334263508Sdim  SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9335263508Sdim  unsigned CandsShown = 0;
9336263508Sdim  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9337263508Sdim    TemplateSpecCandidate *Cand = *I;
9338263508Sdim
9339263508Sdim    // Set an arbitrary limit on the number of candidates we'll spam
9340263508Sdim    // the user with.  FIXME: This limit should depend on details of the
9341263508Sdim    // candidate list.
9342263508Sdim    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9343263508Sdim      break;
9344263508Sdim    ++CandsShown;
9345263508Sdim
9346263508Sdim    assert(Cand->Specialization &&
9347263508Sdim           "Non-matching built-in candidates are not added to Cands.");
9348263508Sdim    Cand->NoteDeductionFailure(S);
9349263508Sdim  }
9350263508Sdim
9351263508Sdim  if (I != E)
9352263508Sdim    S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9353263508Sdim}
9354263508Sdim
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;
9392263508Sdim  bool StaticMemberFunctionFromBoundPointer;
9393207619Srdivacky
9394218893Sdim  OverloadExpr::FindResult OvlExprInfo;
9395218893Sdim  OverloadExpr *OvlExpr;
9396218893Sdim  TemplateArgumentListInfo OvlExplicitTemplateArgs;
9397226633Sdim  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9398263508Sdim  TemplateSpecCandidateSet FailedCandidates;
9399206084Srdivacky
9400218893Sdimpublic:
9401263508Sdim  AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9402263508Sdim                            const QualType &TargetType, bool Complain)
9403263508Sdim      : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9404263508Sdim        Complain(Complain), Context(S.getASTContext()),
9405263508Sdim        TargetTypeIsNonStaticMemberFunction(
9406263508Sdim            !!TargetType->getAs<MemberPointerType>()),
9407263508Sdim        FoundNonTemplateFunction(false),
9408263508Sdim        StaticMemberFunctionFromBoundPointer(false),
9409263508Sdim        OvlExprInfo(OverloadExpr::find(SourceExpr)),
9410263508Sdim        OvlExpr(OvlExprInfo.Expression),
9411263508Sdim        FailedCandidates(OvlExpr->getNameLoc()) {
9412218893Sdim    ExtractUnqualifiedFunctionTypeFromTargetType();
9413221345Sdim
9414263508Sdim    if (TargetFunctionType->isFunctionType()) {
9415263508Sdim      if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9416263508Sdim        if (!UME->isImplicitAccess() &&
9417263508Sdim            !S.ResolveSingleFunctionTemplateSpecialization(UME))
9418263508Sdim          StaticMemberFunctionFromBoundPointer = true;
9419263508Sdim    } else if (OvlExpr->hasExplicitTemplateArgs()) {
9420263508Sdim      DeclAccessPair dap;
9421263508Sdim      if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9422263508Sdim              OvlExpr, false, &dap)) {
9423263508Sdim        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9424263508Sdim          if (!Method->isStatic()) {
9425263508Sdim            // If the target type is a non-function type and the function found
9426263508Sdim            // is a non-static member function, pretend as if that was the
9427263508Sdim            // target, it's the only possible type to end up with.
9428263508Sdim            TargetTypeIsNonStaticMemberFunction = true;
9429221345Sdim
9430263508Sdim            // And skip adding the function if its not in the proper form.
9431263508Sdim            // We'll diagnose this due to an empty set of functions.
9432263508Sdim            if (!OvlExprInfo.HasFormOfMemberPointer)
9433263508Sdim              return;
9434221345Sdim          }
9435221345Sdim
9436263508Sdim        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;
9490263508Sdim    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9491218893Sdim    if (Sema::TemplateDeductionResult Result
9492218893Sdim          = S.DeduceTemplateArguments(FunctionTemplate,
9493218893Sdim                                      &OvlExplicitTemplateArgs,
9494218893Sdim                                      TargetFunctionType, Specialization,
9495251662Sdim                                      Info, /*InOverloadResolution=*/true)) {
9496263508Sdim      // Make a note of the failed deduction for diagnostics.
9497263508Sdim      FailedCandidates.addCandidate()
9498263508Sdim          .set(FunctionTemplate->getTemplatedDecl(),
9499263508Sdim               MakeDeductionFailureInfo(Context, Result, Info));
9500218893Sdim      return false;
9501218893Sdim    }
9502218893Sdim
9503251662Sdim    // Template argument deduction ensures that we have an exact match or
9504251662Sdim    // compatible pointer-to-function arguments that would be adjusted by ICS.
9505218893Sdim    // This function template specicalization works.
9506218893Sdim    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9507251662Sdim    assert(S.isSameOrCompatibleFunctionType(
9508251662Sdim              Context.getCanonicalType(Specialization->getType()),
9509251662Sdim              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)) {
9526234353Sdim      if (S.getLangOpts().CUDA)
9527226633Sdim        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9528226633Sdim          if (S.CheckCUDATarget(Caller, FunDecl))
9529226633Sdim            return false;
9530226633Sdim
9531251662Sdim      // If any candidate has a placeholder return type, trigger its deduction
9532251662Sdim      // now.
9533251662Sdim      if (S.getLangOpts().CPlusPlus1y &&
9534251662Sdim          FunDecl->getResultType()->isUndeducedType() &&
9535251662Sdim          S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9536251662Sdim        return false;
9537251662Sdim
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
9603263508Sdim    // TODO: It looks like FailedCandidates does not serve much purpose
9604263508Sdim    // here, since the no_viable diagnostic has index 0.
9605263508Sdim    UnresolvedSetIterator Result = S.getMostSpecialized(
9606263508Sdim        MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9607263508Sdim        SourceExpr->getLocStart(), S.PDiag(),
9608263508Sdim        S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9609263508Sdim                                                     .second->getDeclName(),
9610263508Sdim        S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9611263508Sdim        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();
9640263508Sdim    if (FailedCandidates.empty())
9641263508Sdim      S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9642263508Sdim    else {
9643263508Sdim      // We have some deduction failure messages. Use them to diagnose
9644263508Sdim      // the function templates, and diagnose the non-template candidates
9645263508Sdim      // normally.
9646263508Sdim      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9647263508Sdim                                 IEnd = OvlExpr->decls_end();
9648263508Sdim           I != IEnd; ++I)
9649263508Sdim        if (FunctionDecl *Fun =
9650263508Sdim                dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9651263508Sdim          S.NoteOverloadCandidate(Fun, TargetFunctionType);
9652263508Sdim      FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9653263508Sdim    }
9654263508Sdim  }
9655263508Sdim
9656218893Sdim  bool IsInvalidFormOfPointerToMemberFunction() const {
9657218893Sdim    return TargetTypeIsNonStaticMemberFunction &&
9658218893Sdim      !OvlExprInfo.HasFormOfMemberPointer;
9659198398Srdivacky  }
9660263508Sdim
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  }
9668263508Sdim
9669263508Sdim  bool IsStaticMemberFunctionFromBoundPointer() const {
9670263508Sdim    return StaticMemberFunctionFromBoundPointer;
9671263508Sdim  }
9672263508Sdim
9673263508Sdim  void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9674263508Sdim    S.Diag(OvlExpr->getLocStart(),
9675263508Sdim           diag::err_invalid_form_pointer_member_function)
9676263508Sdim      << OvlExpr->getSourceRange();
9677263508Sdim  }
9678263508Sdim
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();
9689234353Sdim    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9690218893Sdim  }
9691234353Sdim
9692234353Sdim  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9693234353Sdim
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 *
9723234353SdimSema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9724234353Sdim                                         QualType TargetType,
9725234353Sdim                                         bool Complain,
9726234353Sdim                                         DeclAccessPair &FoundResult,
9727234353Sdim                                         bool *pHadMultipleCandidates) {
9728234353Sdim  assert(AddressOfExpr->getType() == Context.OverloadTy);
9729218893Sdim
9730234353Sdim  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9731234353Sdim                                     Complain);
9732218893Sdim  int NumMatches = Resolver.getNumMatches();
9733218893Sdim  FunctionDecl* Fn = 0;
9734234353Sdim  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();
9746263508Sdim    if (Complain) {
9747263508Sdim      if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9748263508Sdim        Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9749263508Sdim      else
9750263508Sdim        CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9751263508Sdim    }
9752218893Sdim  }
9753234353Sdim
9754234353Sdim  if (pHadMultipleCandidates)
9755234353Sdim    *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.
9766263508Sdim///
9767263508Sdim/// If no template-ids are found, no diagnostics are emitted and NULL is
9768263508Sdim/// 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);
9786263508Sdim  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;
9809263508Sdim    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9810201361Srdivacky    if (TemplateDeductionResult Result
9811201361Srdivacky          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9812251662Sdim                                    Specialization, Info,
9813251662Sdim                                    /*InOverloadResolution=*/true)) {
9814263508Sdim      // Make a note of the failed deduction for diagnostics.
9815263508Sdim      // TODO: Actually use the failed-deduction info?
9816263508Sdim      FailedCandidates.addCandidate()
9817263508Sdim          .set(FunctionTemplate->getTemplatedDecl(),
9818263508Sdim               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
9838251662Sdim  if (Matched && getLangOpts().CPlusPlus1y &&
9839251662Sdim      Matched->getResultType()->isUndeducedType() &&
9840251662Sdim      DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9841251662Sdim    return 0;
9842251662Sdim
9843201361Srdivacky  return Matched;
9844201361Srdivacky}
9845218893Sdim
9846221345Sdim
9847221345Sdim
9848221345Sdim
9849226633Sdim// Resolve and fix an overloaded expression that can be resolved
9850226633Sdim// because it identifies a single function template specialization.
9851226633Sdim//
9852221345Sdim// Last three arguments should only be supplied if Complain = true
9853226633Sdim//
9854226633Sdim// Return true if it was logically possible to so resolve the
9855226633Sdim// expression, regardless of whether or not it succeeded.  Always
9856226633Sdim// returns true if 'complain' is set.
9857226633Sdimbool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9858226633Sdim                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9859226633Sdim                   bool complain, const SourceRange& OpRangeForComplaining,
9860221345Sdim                                           QualType DestTypeForComplaining,
9861221345Sdim                                            unsigned DiagIDForComplaining) {
9862226633Sdim  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9863221345Sdim
9864226633Sdim  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)) {
9870234353Sdim    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9871226633Sdim      SrcExpr = ExprError();
9872226633Sdim      return true;
9873226633Sdim    }
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()) {
9882226633Sdim      if (!complain) return false;
9883226633Sdim
9884226633Sdim      Diag(ovl.Expression->getExprLoc(),
9885226633Sdim           diag::err_bound_member_function)
9886226633Sdim        << 0 << ovl.Expression->getSourceRange();
9887226633Sdim
9888226633Sdim      // TODO: I believe we only end up here if there's a mix of
9889226633Sdim      // static and non-static candidates (otherwise the expression
9890226633Sdim      // would have 'bound member' type, not 'overload' type).
9891226633Sdim      // Ideally we would note which candidate was chosen and why
9892226633Sdim      // the static candidates were rejected.
9893226633Sdim      SrcExpr = ExprError();
9894226633Sdim      return true;
9895221345Sdim    }
9896221345Sdim
9897239462Sdim    // Fix the expression to refer to 'fn'.
9898221345Sdim    SingleFunctionExpression =
9899226633Sdim      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9900221345Sdim
9901221345Sdim    // If desired, do function-to-pointer decay.
9902226633Sdim    if (doFunctionPointerConverion) {
9903221345Sdim      SingleFunctionExpression =
9904221345Sdim        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9905226633Sdim      if (SingleFunctionExpression.isInvalid()) {
9906226633Sdim        SrcExpr = ExprError();
9907226633Sdim        return true;
9908226633Sdim      }
9909226633Sdim    }
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();
9919226633Sdim      NoteAllOverloadCandidates(SrcExpr.get());
9920226633Sdim
9921226633Sdim      SrcExpr = ExprError();
9922226633Sdim      return true;
9923226633Sdim    }
9924226633Sdim
9925226633Sdim    return false;
9926221345Sdim  }
9927221345Sdim
9928226633Sdim  SrcExpr = SingleFunctionExpression;
9929226633Sdim  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,
9936249423Sdim                                       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    }
9949234353Sdim    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9950234353Sdim                           PartialOverloading);
9951198092Srdivacky    return;
9952199990Srdivacky  }
9953199990Srdivacky
9954199990Srdivacky  if (FunctionTemplateDecl *FuncTemplate
9955199990Srdivacky      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9956205408Srdivacky    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9957234353Sdim                                   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,
9967249423Sdim                                       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)
10010234353Sdim    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10011234353Sdim                               CandidateSet, PartialOverloading,
10012234353Sdim                               /*KnownValid*/ true);
10013199990Srdivacky
10014201361Srdivacky  if (ULE->requiresADL())
10015203955Srdivacky    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
10016234353Sdim                                         ULE->getExprLoc(),
10017234353Sdim                                         Args, ExplicitTemplateArgs,
10018243830Sdim                                         CandidateSet, PartialOverloading);
10019198092Srdivacky}
10020201361Srdivacky
10021263508Sdim/// Determine whether a declaration with the specified name could be moved into
10022263508Sdim/// a different namespace.
10023263508Sdimstatic bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10024263508Sdim  switch (Name.getCXXOverloadedOperator()) {
10025263508Sdim  case OO_New: case OO_Array_New:
10026263508Sdim  case OO_Delete: case OO_Array_Delete:
10027263508Sdim    return false;
10028263508Sdim
10029263508Sdim  default:
10030263508Sdim    return true;
10031263508Sdim  }
10032263508Sdim}
10033263508Sdim
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,
10044249423Sdim                       ArrayRef<Expr *> Args) {
10045223017Sdim  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10046223017Sdim    return false;
10047223017Sdim
10048223017Sdim  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10049234353Sdim    if (DC->isTransparentContext())
10050234353Sdim      continue;
10051234353Sdim
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(),
10067234353Sdim                                   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;
10082243830Sdim      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10083223017Sdim                                                 AssociatedNamespaces,
10084223017Sdim                                                 AssociatedClasses);
10085223017Sdim      Sema::AssociatedNamespaceSet SuggestedNamespaces;
10086263508Sdim      if (canBeDeclaredInNamespace(R.getLookupName())) {
10087263508Sdim        DeclContext *Std = SemaRef.getStdNamespace();
10088263508Sdim        for (Sema::AssociatedNamespaceSet::iterator
10089263508Sdim               it = AssociatedNamespaces.begin(),
10090263508Sdim               end = AssociatedNamespaces.end(); it != end; ++it) {
10091263508Sdim          // Never suggest declaring a function within namespace 'std'.
10092263508Sdim          if (Std && Std->Encloses(*it))
10093263508Sdim            continue;
10094249423Sdim
10095263508Sdim          // Never suggest declaring a function within a namespace with a
10096263508Sdim          // reserved name, like __gnu_cxx.
10097263508Sdim          NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10098263508Sdim          if (NS &&
10099263508Sdim              NS->getQualifiedNameAsString().find("__") != std::string::npos)
10100263508Sdim            continue;
10101263508Sdim
10102263508Sdim          SuggestedNamespaces.insert(*it);
10103263508Sdim        }
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,
10143249423Sdim                               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,
10148234353Sdim                                /*ExplicitTemplateArgs=*/0, Args);
10149223017Sdim}
10150223017Sdim
10151234353Sdimnamespace {
10152243830Sdimclass BuildRecoveryCallExprRAII {
10153243830Sdim  Sema &SemaRef;
10154243830Sdimpublic:
10155243830Sdim  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10156243830Sdim    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10157243830Sdim    SemaRef.IsBuildingRecoveryCallExpr = true;
10158243830Sdim  }
10159243830Sdim
10160243830Sdim  ~BuildRecoveryCallExprRAII() {
10161243830Sdim    SemaRef.IsBuildingRecoveryCallExpr = false;
10162243830Sdim  }
10163243830Sdim};
10164243830Sdim
10165234353Sdim}
10166234353Sdim
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,
10174234353Sdim                      llvm::MutableArrayRef<Expr *> Args,
10175223017Sdim                      SourceLocation RParenLoc,
10176234353Sdim                      bool EmptyLookup, bool AllowTypoCorrection) {
10177243830Sdim  // Do not try to recover if it is already building a recovery call.
10178243830Sdim  // This stops infinite loops for template instantiations like
10179243830Sdim  //
10180243830Sdim  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10181243830Sdim  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10182243830Sdim  //
10183243830Sdim  if (SemaRef.IsBuildingRecoveryCallExpr)
10184243830Sdim    return ExprError();
10185243830Sdim  BuildRecoveryCallExprRAII RCE(SemaRef);
10186201361Srdivacky
10187201361Srdivacky  CXXScopeSpec SS;
10188221345Sdim  SS.Adopt(ULE->getQualifierLoc());
10189234353Sdim  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);
10200263508Sdim  FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10201263508Sdim                                  ExplicitTemplateArgs != 0);
10202234353Sdim  NoTypoCorrectionCCC RejectAll;
10203234353Sdim  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10204234353Sdim      (CorrectionCandidateCallback*)&Validator :
10205234353Sdim      (CorrectionCandidateCallback*)&RejectAll;
10206223017Sdim  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10207234353Sdim                              ExplicitTemplateArgs, Args) &&
10208223017Sdim      (!EmptyLookup ||
10209234353Sdim       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10210234353Sdim                                   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())
10219234353Sdim    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10220234353Sdim                                                    R, ExplicitTemplateArgs);
10221234353Sdim  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10222234353Sdim    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10223234353Sdim                                        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,
10234234353Sdim                               MultiExprArg(Args.data(), Args.size()),
10235234353Sdim                               RParenLoc);
10236201361Srdivacky}
10237210299Sed
10238243830Sdim/// \brief Constructs and populates an OverloadedCandidateSet from
10239243830Sdim/// the given function.
10240243830Sdim/// \returns true when an the ExprResult output parameter has been set.
10241243830Sdimbool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10242243830Sdim                                  UnresolvedLookupExpr *ULE,
10243263508Sdim                                  MultiExprArg Args,
10244243830Sdim                                  SourceLocation RParenLoc,
10245243830Sdim                                  OverloadCandidateSet *CandidateSet,
10246243830Sdim                                  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())
10258226633Sdim      llvm_unreachable("performing ADL for builtin");
10259218893Sdim
10260201361Srdivacky    // We don't perform ADL in C.
10261234353Sdim    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10262243830Sdim  }
10263201361Srdivacky#endif
10264201361Srdivacky
10265234353Sdim  UnbridgedCastsSet UnbridgedCasts;
10266263508Sdim  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10267243830Sdim    *Result = ExprError();
10268243830Sdim    return true;
10269243830Sdim  }
10270234353Sdim
10271201361Srdivacky  // Add the functions denoted by the callee to the set of candidate
10272201361Srdivacky  // functions, including those from argument-dependent lookup.
10273263508Sdim  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.
10278243830Sdim  if (CandidateSet->empty()) {
10279226633Sdim    // In Microsoft mode, if we are inside a template class member function then
10280226633Sdim    // create a type dependent CallExpr. The goal is to postpone name lookup
10281226633Sdim    // to instantiation time to be able to search into type dependent base
10282226633Sdim    // classes.
10283234353Sdim    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
10284234353Sdim        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10285263508Sdim      CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10286243830Sdim                                            Context.DependentTy, VK_RValue,
10287243830Sdim                                            RParenLoc);
10288226633Sdim      CE->setTypeDependent(true);
10289243830Sdim      *Result = Owned(CE);
10290243830Sdim      return true;
10291226633Sdim    }
10292243830Sdim    return false;
10293243830Sdim  }
10294243830Sdim
10295243830Sdim  UnbridgedCasts.restore();
10296243830Sdim  return false;
10297243830Sdim}
10298243830Sdim
10299243830Sdim/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10300243830Sdim/// the completed call expression. If overload resolution fails, emits
10301243830Sdim/// diagnostics and returns ExprError()
10302243830Sdimstatic ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10303243830Sdim                                           UnresolvedLookupExpr *ULE,
10304243830Sdim                                           SourceLocation LParenLoc,
10305263508Sdim                                           MultiExprArg Args,
10306243830Sdim                                           SourceLocation RParenLoc,
10307243830Sdim                                           Expr *ExecConfig,
10308243830Sdim                                           OverloadCandidateSet *CandidateSet,
10309243830Sdim                                           OverloadCandidateSet::iterator *Best,
10310243830Sdim                                           OverloadingResult OverloadResult,
10311243830Sdim                                           bool AllowTypoCorrection) {
10312243830Sdim  if (CandidateSet->empty())
10313263508Sdim    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10314234353Sdim                                 RParenLoc, /*EmptyLookup=*/true,
10315234353Sdim                                 AllowTypoCorrection);
10316201361Srdivacky
10317243830Sdim  switch (OverloadResult) {
10318201361Srdivacky  case OR_Success: {
10319243830Sdim    FunctionDecl *FDecl = (*Best)->Function;
10320243830Sdim    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10321251662Sdim    if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10322251662Sdim      return ExprError();
10323243830Sdim    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10324263508Sdim    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10325263508Sdim                                         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.
10331243830Sdim    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10332263508Sdim                                                Args, RParenLoc,
10333234353Sdim                                                /*EmptyLookup=*/false,
10334234353Sdim                                                AllowTypoCorrection);
10335223017Sdim    if (!Recovery.isInvalid())
10336223017Sdim      return Recovery;
10337223017Sdim
10338243830Sdim    SemaRef.Diag(Fn->getLocStart(),
10339193326Sed         diag::err_ovl_no_viable_function_in_call)
10340201361Srdivacky      << ULE->getName() << Fn->getSourceRange();
10341263508Sdim    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10342193326Sed    break;
10343223017Sdim  }
10344193326Sed
10345193326Sed  case OR_Ambiguous:
10346243830Sdim    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10347201361Srdivacky      << ULE->getName() << Fn->getSourceRange();
10348263508Sdim    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10349193326Sed    break;
10350193326Sed
10351243830Sdim  case OR_Deleted: {
10352243830Sdim    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10353243830Sdim      << (*Best)->Function->isDeleted()
10354243830Sdim      << ULE->getName()
10355243830Sdim      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10356243830Sdim      << Fn->getSourceRange();
10357263508Sdim    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10358234353Sdim
10359243830Sdim    // We emitted an error for the unvailable/deleted function call but keep
10360243830Sdim    // the call in the AST.
10361243830Sdim    FunctionDecl *FDecl = (*Best)->Function;
10362243830Sdim    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10363263508Sdim    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10364263508Sdim                                         ExecConfig);
10365193326Sed  }
10366243830Sdim  }
10367193326Sed
10368212904Sdim  // Overload resolution failed.
10369201361Srdivacky  return ExprError();
10370193326Sed}
10371193326Sed
10372243830Sdim/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10373243830Sdim/// (which eventually refers to the declaration Func) and the call
10374243830Sdim/// arguments Args/NumArgs, attempt to resolve the function call down
10375243830Sdim/// to a specific function. If overload resolution succeeds, returns
10376243830Sdim/// the call expression produced by overload resolution.
10377243830Sdim/// Otherwise, emits diagnostics and returns ExprError.
10378243830SdimExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10379243830Sdim                                         UnresolvedLookupExpr *ULE,
10380243830Sdim                                         SourceLocation LParenLoc,
10381263508Sdim                                         MultiExprArg Args,
10382243830Sdim                                         SourceLocation RParenLoc,
10383243830Sdim                                         Expr *ExecConfig,
10384243830Sdim                                         bool AllowTypoCorrection) {
10385243830Sdim  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10386243830Sdim  ExprResult result;
10387243830Sdim
10388263508Sdim  if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10389263508Sdim                             &result))
10390243830Sdim    return result;
10391243830Sdim
10392243830Sdim  OverloadCandidateSet::iterator Best;
10393243830Sdim  OverloadingResult OverloadResult =
10394243830Sdim      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10395243830Sdim
10396263508Sdim  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10397243830Sdim                                  RParenLoc, ExecConfig, &CandidateSet,
10398243830Sdim                                  &Best, OverloadResult,
10399243830Sdim                                  AllowTypoCorrection);
10400243830Sdim}
10401243830Sdim
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///
10415239462Sdim/// \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///
10422239462Sdim/// \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
10435234353Sdim  if (checkPlaceholderForOverload(*this, Input))
10436234353Sdim    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
10451251662Sdim  ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10452251662Sdim
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());
10467251662Sdim    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
10468193326Sed                                                   Context.DependentTy,
10469218893Sdim                                                   VK_RValue,
10470243830Sdim                                                   OpLoc, false));
10471193326Sed  }
10472193326Sed
10473193326Sed  // Build an empty overload set.
10474203955Srdivacky  OverloadCandidateSet CandidateSet(OpLoc);
10475193326Sed
10476193326Sed  // Add the candidates from the given function set.
10477251662Sdim  AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10478193326Sed
10479193326Sed  // Add operator candidates that are member functions.
10480251662Sdim  AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10481193326Sed
10482203955Srdivacky  // Add candidates from ADL.
10483251662Sdim  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10484251662Sdim                                       ArgsArray, /*ExplicitTemplateArgs*/ 0,
10485203955Srdivacky                                       CandidateSet);
10486203955Srdivacky
10487193326Sed  // Add builtin operator candidates.
10488251662Sdim  AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10489193326Sed
10490226633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10491226633Sdim
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.
10527249423Sdim      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10528234353Sdim                                                HadMultipleCandidates, OpLoc);
10529221345Sdim      if (FnExpr.isInvalid())
10530221345Sdim        return ExprError();
10531198092Srdivacky
10532263508Sdim      // Determine the result type.
10533263508Sdim      QualType ResultTy = FnDecl->getResultType();
10534263508Sdim      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10535263508Sdim      ResultTy = ResultTy.getNonLValueExprType(Context);
10536263508Sdim
10537199482Srdivacky      Args[0] = Input;
10538212904Sdim      CallExpr *TheCall =
10539251662Sdim        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
10540243830Sdim                                          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.
10565251662Sdim    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();
10578251662Sdim    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();
10588251662Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10589226633Sdim                                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///
10607239462Sdim/// \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,
10638243830Sdim                                                  OpLoc,
10639243830Sdim                                                  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,
10647243830Sdim                                                        OpLoc,
10648243830Sdim                                                        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());
10660243830Sdim    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10661243830Sdim                                                Context.DependentTy, VK_RValue,
10662243830Sdim                                                OpLoc, FPFeatures.fp_contract));
10663193326Sed  }
10664193326Sed
10665234353Sdim  // Always do placeholder-like conversions on the RHS.
10666234353Sdim  if (checkPlaceholderForOverload(*this, Args[1]))
10667234353Sdim    return ExprError();
10668193326Sed
10669234353Sdim  // Do placeholder-like conversion on the LHS; note that we should
10670234353Sdim  // not get here with a PseudoObject LHS.
10671234353Sdim  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10672234353Sdim  if (checkPlaceholderForOverload(*this, Args[0]))
10673234353Sdim    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.
10693234353Sdim  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10694193326Sed
10695193326Sed  // Add operator candidates that are member functions.
10696251662Sdim  AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10697193326Sed
10698203955Srdivacky  // Add candidates from ADL.
10699203955Srdivacky  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10700234353Sdim                                       OpLoc, Args,
10701203955Srdivacky                                       /*ExplicitTemplateArgs*/ 0,
10702203955Srdivacky                                       CandidateSet);
10703203955Srdivacky
10704193326Sed  // Add builtin operator candidates.
10705251662Sdim  AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10706193326Sed
10707226633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10708226633Sdim
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.
10761226633Sdim        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10762249423Sdim                                                  Best->FoundDecl,
10763226633Sdim                                                  HadMultipleCandidates, OpLoc);
10764221345Sdim        if (FnExpr.isInvalid())
10765221345Sdim          return ExprError();
10766193326Sed
10767263508Sdim        // Determine the result type.
10768263508Sdim        QualType ResultTy = FnDecl->getResultType();
10769263508Sdim        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10770263508Sdim        ResultTy = ResultTy.getNonLValueExprType(Context);
10771263508Sdim
10772212904Sdim        CXXOperatorCallExpr *TheCall =
10773221345Sdim          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10774243830Sdim                                            Args, ResultTy, VK, OpLoc,
10775243830Sdim                                            FPFeatures.fp_contract);
10776218893Sdim
10777218893Sdim        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10778198092Srdivacky                                FnDecl))
10779198092Srdivacky          return ExprError();
10780198092Srdivacky
10781249423Sdim        ArrayRef<const Expr *> ArgsArray(Args, 2);
10782249423Sdim        // Cut off the implicit 'this'.
10783249423Sdim        if (isa<CXXMethodDecl>(FnDecl))
10784249423Sdim          ArgsArray = ArgsArray.slice(1);
10785249423Sdim        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10786249423Sdim                  TheCall->getSourceRange(), VariadicDoesNotApply);
10787249423Sdim
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();
10827263508Sdim        if (Args[0]->getType()->isIncompleteType()) {
10828263508Sdim          Diag(OpLoc, diag::note_assign_lhs_incomplete)
10829263508Sdim            << Args[0]->getType()
10830263508Sdim            << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10831263508Sdim        }
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.
10836234353Sdim        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())
10847234353Sdim        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10848212904Sdim                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10849243830Sdim      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();
10857234353Sdim      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10858212904Sdim                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10859193326Sed      return ExprError();
10860193326Sed
10861193326Sed    case OR_Deleted:
10862234353Sdim      if (isImplicitlyDeleted(Best->Function)) {
10863234353Sdim        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10864234353Sdim        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10865249423Sdim          << Context.getRecordType(Method->getParent())
10866249423Sdim          << getSpecialMember(Method);
10867234353Sdim
10868249423Sdim        // The user probably meant to call this special member. Just
10869249423Sdim        // explain why it's deleted.
10870249423Sdim        NoteDeletedFunction(Method);
10871249423Sdim        return ExprError();
10872234353Sdim      } else {
10873234353Sdim        Diag(OpLoc, diag::err_ovl_deleted_oper)
10874234353Sdim          << Best->Function->isDeleted()
10875234353Sdim          << BinaryOperator::getOpcodeStr(Opc)
10876234353Sdim          << getDeletedOrUnavailableSuffix(Best->Function)
10877234353Sdim          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10878234353Sdim      }
10879234353Sdim      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10880226633Sdim                                  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,
10913243830Sdim                                                   Args,
10914198893Srdivacky                                                   Context.DependentTy,
10915218893Sdim                                                   VK_RValue,
10916243830Sdim                                                   RLoc, false));
10917198893Srdivacky  }
10918198893Srdivacky
10919234353Sdim  // Handle placeholders on both operands.
10920234353Sdim  if (checkPlaceholderForOverload(*this, Args[0]))
10921234353Sdim    return ExprError();
10922234353Sdim  if (checkPlaceholderForOverload(*this, Args[1]))
10923234353Sdim    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.
10931251662Sdim  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10932198893Srdivacky
10933198893Srdivacky  // Add builtin operator candidates.
10934251662Sdim  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10935198893Srdivacky
10936226633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10937226633Sdim
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.
10973234353Sdim        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10974234353Sdim        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10975226633Sdim        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10976249423Sdim                                                  Best->FoundDecl,
10977226633Sdim                                                  HadMultipleCandidates,
10978234353Sdim                                                  OpLocInfo.getLoc(),
10979234353Sdim                                                  OpLocInfo.getInfo());
10980221345Sdim        if (FnExpr.isInvalid())
10981221345Sdim          return ExprError();
10982198893Srdivacky
10983263508Sdim        // Determine the result type
10984263508Sdim        QualType ResultTy = FnDecl->getResultType();
10985263508Sdim        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10986263508Sdim        ResultTy = ResultTy.getNonLValueExprType(Context);
10987263508Sdim
10988212904Sdim        CXXOperatorCallExpr *TheCall =
10989212904Sdim          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10990243830Sdim                                            FnExpr.take(), Args,
10991243830Sdim                                            ResultTy, VK, RLoc,
10992243830Sdim                                            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();
11030234353Sdim      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();
11040234353Sdim      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();
11049234353Sdim      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,
11067263508Sdim                                SourceLocation LParenLoc,
11068263508Sdim                                MultiExprArg Args,
11069263508Sdim                                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
11110263508Sdim      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11111221345Sdim                                        resultType, valueKind, RParenLoc);
11112221345Sdim
11113221345Sdim    if (CheckCallReturnType(proto->getResultType(),
11114234353Sdim                            op->getRHS()->getLocStart(),
11115221345Sdim                            call, 0))
11116221345Sdim      return ExprError();
11117221345Sdim
11118263508Sdim    if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
11119221345Sdim      return ExprError();
11120221345Sdim
11121263508Sdim    if (CheckOtherCall(call, proto))
11122263508Sdim      return ExprError();
11123263508Sdim
11124221345Sdim    return MaybeBindToTemporary(call);
11125221345Sdim  }
11126221345Sdim
11127234353Sdim  UnbridgedCastsSet UnbridgedCasts;
11128263508Sdim  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11129234353Sdim    return ExprError();
11130234353Sdim
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();
11140234353Sdim    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.
11170234353Sdim      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11171234353Sdim        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11172263508Sdim                             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,
11180263508Sdim                           ObjectClassification, Args, CandidateSet,
11181218893Sdim                           /*SuppressUserConversions=*/false);
11182199990Srdivacky      } else {
11183199990Srdivacky        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11184205408Srdivacky                                   I.getPair(), ActingDC, TemplateArgs,
11185218893Sdim                                   ObjectType,  ObjectClassification,
11186263508Sdim                                   Args, CandidateSet,
11187198092Srdivacky                                   /*SuppressUsedConversions=*/false);
11188199990Srdivacky      }
11189193326Sed    }
11190193326Sed
11191199990Srdivacky    DeclarationName DeclName = UnresExpr->getMemberName();
11192199990Srdivacky
11193234353Sdim    UnbridgedCasts.restore();
11194234353Sdim
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);
11202251662Sdim      if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11203251662Sdim        return ExprError();
11204263508Sdim      // If FoundDecl is different from Method (such as if one is a template
11205263508Sdim      // and the other a specialization), make sure DiagnoseUseOfDecl is
11206263508Sdim      // called on both.
11207263508Sdim      // FIXME: This would be more comprehensively addressed by modifying
11208263508Sdim      // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11209263508Sdim      // being used.
11210263508Sdim      if (Method != FoundDecl.getDecl() &&
11211263508Sdim                      DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11212263508Sdim        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();
11219263508Sdim      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();
11226263508Sdim      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();
11236263508Sdim      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()) {
11246263508Sdim      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11247263508Sdim                                   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 =
11259263508Sdim    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>();
11282263508Sdim  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11283193326Sed                              RParenLoc))
11284200583Srdivacky    return ExprError();
11285193326Sed
11286263508Sdim  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11287234353Sdim
11288239462Sdim  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,
11315263508Sdim                                   MultiExprArg Args,
11316193326Sed                                   SourceLocation RParenLoc) {
11317234353Sdim  if (checkPlaceholderForOverload(*this, Obj))
11318234353Sdim    return ExprError();
11319221345Sdim  ExprResult Object = Owned(Obj);
11320218893Sdim
11321234353Sdim  UnbridgedCastsSet UnbridgedCasts;
11322263508Sdim  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11323234353Sdim    return ExprError();
11324234353Sdim
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(),
11339239462Sdim                          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(),
11349263508Sdim                       Object.get()->Classify(Context),
11350263508Sdim                       Args, CandidateSet,
11351199482Srdivacky                       /*SuppressUserConversions=*/ false);
11352199482Srdivacky  }
11353218893Sdim
11354193326Sed  // C++ [over.call.object]p2:
11355226633Sdim  //   In addition, for each (non-explicit in C++0x) conversion function
11356226633Sdim  //   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.
11371249423Sdim  std::pair<CXXRecordDecl::conversion_iterator,
11372249423Sdim            CXXRecordDecl::conversion_iterator> Conversions
11373202379Srdivacky    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11374249423Sdim  for (CXXRecordDecl::conversion_iterator
11375249423Sdim         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);
11387226633Sdim    if (!Conv->isExplicit()) {
11388226633Sdim      // Strip the reference type (if any) and then the pointer type (if
11389226633Sdim      // any) to get down to what might be a function type.
11390226633Sdim      QualType ConvType = Conv->getConversionType().getNonReferenceType();
11391226633Sdim      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11392226633Sdim        ConvType = ConvPtrType->getPointeeType();
11393199990Srdivacky
11394226633Sdim      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11395226633Sdim      {
11396226633Sdim        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11397263508Sdim                              Object.get(), Args, CandidateSet);
11398226633Sdim      }
11399226633Sdim    }
11400193326Sed  }
11401193326Sed
11402226633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11403226633Sdim
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())
11415234353Sdim      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11416221345Sdim        << Object.get()->getType() << /*call*/ 1
11417221345Sdim        << Object.get()->getSourceRange();
11418202379Srdivacky    else
11419234353Sdim      Diag(Object.get()->getLocStart(),
11420202379Srdivacky           diag::err_ovl_no_viable_object_call)
11421221345Sdim        << Object.get()->getType() << Object.get()->getSourceRange();
11422263508Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11423193326Sed    break;
11424193326Sed
11425193326Sed  case OR_Ambiguous:
11426234353Sdim    Diag(Object.get()->getLocStart(),
11427193326Sed         diag::err_ovl_ambiguous_object_call)
11428221345Sdim      << Object.get()->getType() << Object.get()->getSourceRange();
11429263508Sdim    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11430193326Sed    break;
11431193326Sed
11432193326Sed  case OR_Deleted:
11433234353Sdim    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();
11439263508Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11440193326Sed    break;
11441198092Srdivacky  }
11442193326Sed
11443212904Sdim  if (Best == CandidateSet.end())
11444193326Sed    return true;
11445193326Sed
11446234353Sdim  UnbridgedCasts.restore();
11447234353Sdim
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);
11456251662Sdim    if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11457251662Sdim      return ExprError();
11458263508Sdim    assert(Conv == Best->FoundDecl.getDecl() &&
11459263508Sdim             "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.
11466226633Sdim    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11467226633Sdim                                             Conv, HadMultipleCandidates);
11468218893Sdim    if (Call.isInvalid())
11469218893Sdim      return ExprError();
11470234353Sdim    // Record usage of conversion in an implicit cast.
11471234353Sdim    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11472234353Sdim                                          CK_UserDefinedConversion,
11473234353Sdim                                          Call.get(), 0, VK_RValue));
11474218893Sdim
11475263508Sdim    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);
11484243830Sdim
11485243830Sdim  // An error diagnostic has already been printed when parsing the declaration.
11486243830Sdim  if (Method->isInvalidDecl())
11487243830Sdim    return ExprError();
11488243830Sdim
11489218893Sdim  const FunctionProtoType *Proto =
11490218893Sdim    Method->getType()->getAs<FunctionProtoType>();
11491193326Sed
11492193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
11493193326Sed
11494234353Sdim  DeclarationNameInfo OpLocInfo(
11495234353Sdim               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11496234353Sdim  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11497249423Sdim  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11498234353Sdim                                           HadMultipleCandidates,
11499234353Sdim                                           OpLocInfo.getLoc(),
11500234353Sdim                                           OpLocInfo.getInfo());
11501221345Sdim  if (NewFn.isInvalid())
11502221345Sdim    return true;
11503193326Sed
11504263508Sdim  // Build the full argument list for the method call (the implicit object
11505263508Sdim  // parameter is placed at the beginning of the list).
11506263508Sdim  llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11507263508Sdim  MethodArgs[0] = Object.get();
11508263508Sdim  std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11509263508Sdim
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
11516263508Sdim  CXXOperatorCallExpr *TheCall = new (Context)
11517263508Sdim      CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11518263508Sdim                          llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11519263508Sdim                          ResultTy, VK, RParenLoc, false);
11520263508Sdim  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.
11528263508Sdim  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
11540243830Sdim    Object = ObjRes;
11541221345Sdim  TheCall->setArg(0, Object.take());
11542193326Sed
11543193326Sed  // Check the argument types.
11544263508Sdim  for (unsigned i = 0; i != NumArgsInProto; i++) {
11545193326Sed    Expr *Arg;
11546263508Sdim    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).
11576263508Sdim    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
11585263508Sdim  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11586234353Sdim
11587239462Sdim  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
11597263508SdimSema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11598263508Sdim                               bool *NoArrowOperatorFound) {
11599218893Sdim  assert(Base->getType()->isRecordType() &&
11600218893Sdim         "left-hand side must have class type");
11601198092Srdivacky
11602234353Sdim  if (checkPlaceholderForOverload(*this, Base))
11603234353Sdim    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(),
11619239462Sdim                          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),
11629251662Sdim                       None, CandidateSet, /*SuppressUserConversions=*/false);
11630200583Srdivacky  }
11631193326Sed
11632226633Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11633226633Sdim
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:
11642263508Sdim    if (CandidateSet.empty()) {
11643263508Sdim      QualType BaseType = Base->getType();
11644263508Sdim      if (NoArrowOperatorFound) {
11645263508Sdim        // Report this specific error to the caller instead of emitting a
11646263508Sdim        // diagnostic, as requested.
11647263508Sdim        *NoArrowOperatorFound = true;
11648263508Sdim        return ExprError();
11649263508Sdim      }
11650193326Sed      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11651263508Sdim        << BaseType << Base->getSourceRange();
11652263508Sdim      if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11653263508Sdim        Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11654263508Sdim          << FixItHint::CreateReplacement(OpLoc, ".");
11655263508Sdim      }
11656263508Sdim    } else
11657193326Sed      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11658198092Srdivacky        << "operator->" << Base->getSourceRange();
11659234353Sdim    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();
11665234353Sdim    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();
11674234353Sdim    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.
11690249423Sdim  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11691234353Sdim                                            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(),
11700243830Sdim                                      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
11709234353Sdim/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11710234353Sdim/// a literal operator described by the provided lookup results.
11711234353SdimExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11712234353Sdim                                          DeclarationNameInfo &SuffixInfo,
11713234353Sdim                                          ArrayRef<Expr*> Args,
11714234353Sdim                                          SourceLocation LitEndLoc,
11715234353Sdim                                       TemplateArgumentListInfo *TemplateArgs) {
11716234353Sdim  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11717234353Sdim
11718234353Sdim  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11719234353Sdim  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11720234353Sdim                        TemplateArgs);
11721234353Sdim
11722234353Sdim  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11723234353Sdim
11724234353Sdim  // Perform overload resolution. This will usually be trivial, but might need
11725234353Sdim  // to perform substitutions for a literal operator template.
11726234353Sdim  OverloadCandidateSet::iterator Best;
11727234353Sdim  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11728234353Sdim  case OR_Success:
11729234353Sdim  case OR_Deleted:
11730234353Sdim    break;
11731234353Sdim
11732234353Sdim  case OR_No_Viable_Function:
11733234353Sdim    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11734234353Sdim      << R.getLookupName();
11735234353Sdim    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11736234353Sdim    return ExprError();
11737234353Sdim
11738234353Sdim  case OR_Ambiguous:
11739234353Sdim    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11740234353Sdim    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11741234353Sdim    return ExprError();
11742234353Sdim  }
11743234353Sdim
11744234353Sdim  FunctionDecl *FD = Best->Function;
11745249423Sdim  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11746249423Sdim                                        HadMultipleCandidates,
11747234353Sdim                                        SuffixInfo.getLoc(),
11748234353Sdim                                        SuffixInfo.getInfo());
11749234353Sdim  if (Fn.isInvalid())
11750234353Sdim    return true;
11751234353Sdim
11752234353Sdim  // Check the argument types. This should almost always be a no-op, except
11753234353Sdim  // that array-to-pointer decay is applied to string literals.
11754234353Sdim  Expr *ConvArgs[2];
11755251662Sdim  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
11756234353Sdim    ExprResult InputInit = PerformCopyInitialization(
11757234353Sdim      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11758234353Sdim      SourceLocation(), Args[ArgIdx]);
11759234353Sdim    if (InputInit.isInvalid())
11760234353Sdim      return true;
11761234353Sdim    ConvArgs[ArgIdx] = InputInit.take();
11762234353Sdim  }
11763234353Sdim
11764234353Sdim  QualType ResultTy = FD->getResultType();
11765234353Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11766234353Sdim  ResultTy = ResultTy.getNonLValueExprType(Context);
11767234353Sdim
11768234353Sdim  UserDefinedLiteral *UDL =
11769243830Sdim    new (Context) UserDefinedLiteral(Context, Fn.take(),
11770243830Sdim                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11771234353Sdim                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11772234353Sdim
11773234353Sdim  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11774234353Sdim    return ExprError();
11775234353Sdim
11776239462Sdim  if (CheckFunctionCall(FD, UDL, NULL))
11777234353Sdim    return ExprError();
11778234353Sdim
11779234353Sdim  return MaybeBindToTemporary(UDL);
11780234353Sdim}
11781234353Sdim
11782243830Sdim/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11783243830Sdim/// given LookupResult is non-empty, it is assumed to describe a member which
11784243830Sdim/// will be invoked. Otherwise, the function will be found via argument
11785243830Sdim/// dependent lookup.
11786243830Sdim/// CallExpr is set to a valid expression and FRS_Success returned on success,
11787243830Sdim/// otherwise CallExpr is set to ExprError() and some non-success value
11788243830Sdim/// is returned.
11789243830SdimSema::ForRangeStatus
11790243830SdimSema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11791243830Sdim                                SourceLocation RangeLoc, VarDecl *Decl,
11792243830Sdim                                BeginEndFunction BEF,
11793243830Sdim                                const DeclarationNameInfo &NameInfo,
11794243830Sdim                                LookupResult &MemberLookup,
11795243830Sdim                                OverloadCandidateSet *CandidateSet,
11796243830Sdim                                Expr *Range, ExprResult *CallExpr) {
11797243830Sdim  CandidateSet->clear();
11798243830Sdim  if (!MemberLookup.empty()) {
11799243830Sdim    ExprResult MemberRef =
11800243830Sdim        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11801243830Sdim                                 /*IsPtr=*/false, CXXScopeSpec(),
11802243830Sdim                                 /*TemplateKWLoc=*/SourceLocation(),
11803243830Sdim                                 /*FirstQualifierInScope=*/0,
11804243830Sdim                                 MemberLookup,
11805243830Sdim                                 /*TemplateArgs=*/0);
11806243830Sdim    if (MemberRef.isInvalid()) {
11807243830Sdim      *CallExpr = ExprError();
11808243830Sdim      Diag(Range->getLocStart(), diag::note_in_for_range)
11809243830Sdim          << RangeLoc << BEF << Range->getType();
11810243830Sdim      return FRS_DiagnosticIssued;
11811243830Sdim    }
11812251662Sdim    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
11813243830Sdim    if (CallExpr->isInvalid()) {
11814243830Sdim      *CallExpr = ExprError();
11815243830Sdim      Diag(Range->getLocStart(), diag::note_in_for_range)
11816243830Sdim          << RangeLoc << BEF << Range->getType();
11817243830Sdim      return FRS_DiagnosticIssued;
11818243830Sdim    }
11819243830Sdim  } else {
11820243830Sdim    UnresolvedSet<0> FoundNames;
11821243830Sdim    UnresolvedLookupExpr *Fn =
11822243830Sdim      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11823243830Sdim                                   NestedNameSpecifierLoc(), NameInfo,
11824243830Sdim                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11825243830Sdim                                   FoundNames.begin(), FoundNames.end());
11826243830Sdim
11827263508Sdim    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
11828243830Sdim                                                    CandidateSet, CallExpr);
11829243830Sdim    if (CandidateSet->empty() || CandidateSetError) {
11830243830Sdim      *CallExpr = ExprError();
11831243830Sdim      return FRS_NoViableFunction;
11832243830Sdim    }
11833243830Sdim    OverloadCandidateSet::iterator Best;
11834243830Sdim    OverloadingResult OverloadResult =
11835243830Sdim        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11836243830Sdim
11837243830Sdim    if (OverloadResult == OR_No_Viable_Function) {
11838243830Sdim      *CallExpr = ExprError();
11839243830Sdim      return FRS_NoViableFunction;
11840243830Sdim    }
11841263508Sdim    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
11842243830Sdim                                         Loc, 0, CandidateSet, &Best,
11843243830Sdim                                         OverloadResult,
11844243830Sdim                                         /*AllowTypoCorrection=*/false);
11845243830Sdim    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11846243830Sdim      *CallExpr = ExprError();
11847243830Sdim      Diag(Range->getLocStart(), diag::note_in_for_range)
11848243830Sdim          << RangeLoc << BEF << Range->getType();
11849243830Sdim      return FRS_DiagnosticIssued;
11850243830Sdim    }
11851243830Sdim  }
11852243830Sdim  return FRS_Success;
11853243830Sdim}
11854243830Sdim
11855243830Sdim
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
11941226633Sdim    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11942226633Sdim                                           ULE->getQualifierLoc(),
11943234353Sdim                                           ULE->getTemplateKeywordLoc(),
11944226633Sdim                                           Fn,
11945234353Sdim                                           /*enclosing*/ false, // FIXME?
11946226633Sdim                                           ULE->getNameLoc(),
11947226633Sdim                                           Fn->getType(),
11948226633Sdim                                           VK_LValue,
11949226633Sdim                                           Found.getDecl(),
11950226633Sdim                                           TemplateArgs);
11951234982Sdim    MarkDeclRefReferenced(DRE);
11952226633Sdim    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11953226633Sdim    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()) {
11970226633Sdim        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11971226633Sdim                                               MemExpr->getQualifierLoc(),
11972234353Sdim                                               MemExpr->getTemplateKeywordLoc(),
11973226633Sdim                                               Fn,
11974234353Sdim                                               /*enclosing*/ false,
11975226633Sdim                                               MemExpr->getMemberLoc(),
11976226633Sdim                                               Fn->getType(),
11977226633Sdim                                               VK_LValue,
11978226633Sdim                                               Found.getDecl(),
11979226633Sdim                                               TemplateArgs);
11980234982Sdim        MarkDeclRefReferenced(DRE);
11981226633Sdim        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11982226633Sdim        return DRE;
11983202379Srdivacky      } else {
11984202379Srdivacky        SourceLocation Loc = MemExpr->getMemberLoc();
11985202379Srdivacky        if (MemExpr->getQualifier())
11986221345Sdim          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11987234353Sdim        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
12005226633Sdim    MemberExpr *ME = MemberExpr::Create(Context, Base,
12006226633Sdim                                        MemExpr->isArrow(),
12007226633Sdim                                        MemExpr->getQualifierLoc(),
12008234353Sdim                                        MemExpr->getTemplateKeywordLoc(),
12009226633Sdim                                        Fn,
12010226633Sdim                                        Found,
12011226633Sdim                                        MemExpr->getMemberNameInfo(),
12012226633Sdim                                        TemplateArgs,
12013226633Sdim                                        type, valueKind, OK_Ordinary);
12014226633Sdim    ME->setHadMultipleCandidates(true);
12015243830Sdim    MarkMemberReferenced(ME);
12016226633Sdim    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