SemaOverload.cpp revision 199482
189857Sobrien//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2218822Sdim//
3130561Sobrien//                     The LLVM Compiler Infrastructure
489857Sobrien//
589857Sobrien// This file is distributed under the University of Illinois Open Source
6130561Sobrien// License. See LICENSE.TXT for details.
789857Sobrien//
8130561Sobrien//===----------------------------------------------------------------------===//
989857Sobrien//
10130561Sobrien// This file provides Sema routines for C++ overloading.
11130561Sobrien//
12130561Sobrien//===----------------------------------------------------------------------===//
13130561Sobrien
1489857Sobrien#include "Sema.h"
15130561Sobrien#include "Lookup.h"
16130561Sobrien#include "clang/Basic/Diagnostic.h"
17130561Sobrien#include "clang/Lex/Preprocessor.h"
18130561Sobrien#include "clang/AST/ASTContext.h"
1989857Sobrien#include "clang/AST/CXXInheritance.h"
20130561Sobrien#include "clang/AST/Expr.h"
21130561Sobrien#include "clang/AST/ExprCXX.h"
22218822Sdim#include "clang/AST/TypeOrdering.h"
2389857Sobrien#include "clang/Basic/PartialDiagnostic.h"
24130561Sobrien#include "llvm/ADT/SmallPtrSet.h"
25130561Sobrien#include "llvm/ADT/STLExtras.h"
26130561Sobrien#include "llvm/Support/Compiler.h"
2789857Sobrien#include <algorithm>
28218822Sdim#include <cstdio>
29218822Sdim
3089857Sobriennamespace clang {
3189857Sobrien
3289857Sobrien/// GetConversionCategory - Retrieve the implicit conversion
3389857Sobrien/// category corresponding to the given implicit conversion kind.
34130561SobrienImplicitConversionCategory
3589857SobrienGetConversionCategory(ImplicitConversionKind Kind) {
3689857Sobrien  static const ImplicitConversionCategory
3799461Sobrien    Category[(int)ICK_Num_Conversion_Kinds] = {
38130561Sobrien    ICC_Identity,
39218822Sdim    ICC_Lvalue_Transformation,
40218822Sdim    ICC_Lvalue_Transformation,
4199461Sobrien    ICC_Lvalue_Transformation,
42130561Sobrien    ICC_Qualification_Adjustment,
4399461Sobrien    ICC_Promotion,
44130561Sobrien    ICC_Promotion,
4599461Sobrien    ICC_Promotion,
46130561Sobrien    ICC_Conversion,
4799461Sobrien    ICC_Conversion,
48130561Sobrien    ICC_Conversion,
4999461Sobrien    ICC_Conversion,
50130561Sobrien    ICC_Conversion,
5199461Sobrien    ICC_Conversion,
52130561Sobrien    ICC_Conversion,
5399461Sobrien    ICC_Conversion,
54130561Sobrien    ICC_Conversion,
55218822Sdim    ICC_Conversion
56218822Sdim  };
5789857Sobrien  return Category[(int)Kind];
58130561Sobrien}
59130561Sobrien
60130561Sobrien/// GetConversionRank - Retrieve the implicit conversion rank
61130561Sobrien/// corresponding to the given implicit conversion kind.
62130561SobrienImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63130561Sobrien  static const ImplicitConversionRank
64130561Sobrien    Rank[(int)ICK_Num_Conversion_Kinds] = {
65218822Sdim    ICR_Exact_Match,
66130561Sobrien    ICR_Exact_Match,
67130561Sobrien    ICR_Exact_Match,
68130561Sobrien    ICR_Exact_Match,
69130561Sobrien    ICR_Exact_Match,
70130561Sobrien    ICR_Promotion,
71130561Sobrien    ICR_Promotion,
72130561Sobrien    ICR_Promotion,
73130561Sobrien    ICR_Conversion,
74130561Sobrien    ICR_Conversion,
75130561Sobrien    ICR_Conversion,
76218822Sdim    ICR_Conversion,
77130561Sobrien    ICR_Conversion,
78130561Sobrien    ICR_Conversion,
79130561Sobrien    ICR_Conversion,
80218822Sdim    ICR_Conversion,
81130561Sobrien    ICR_Conversion,
82130561Sobrien    ICR_Conversion
83130561Sobrien  };
84130561Sobrien  return Rank[(int)Kind];
85218822Sdim}
86130561Sobrien
87130561Sobrien/// GetImplicitConversionName - Return the name of this kind of
88130561Sobrien/// implicit conversion.
89130561Sobrienconst char* GetImplicitConversionName(ImplicitConversionKind Kind) {
90218822Sdim  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
91130561Sobrien    "No conversion",
92130561Sobrien    "Lvalue-to-rvalue",
93130561Sobrien    "Array-to-pointer",
94218822Sdim    "Function-to-pointer",
95218822Sdim    "Qualification",
96218822Sdim    "Integral promotion",
97130561Sobrien    "Floating point promotion",
98218822Sdim    "Complex promotion",
99130561Sobrien    "Integral conversion",
100130561Sobrien    "Floating conversion",
101130561Sobrien    "Complex conversion",
102130561Sobrien    "Floating-integral conversion",
103130561Sobrien    "Complex-real conversion",
104130561Sobrien    "Pointer conversion",
105218822Sdim    "Pointer-to-member conversion",
106218822Sdim    "Boolean conversion",
107130561Sobrien    "Compatible-types conversion",
108130561Sobrien    "Derived-to-base conversion"
109130561Sobrien  };
110130561Sobrien  return Name[Kind];
111130561Sobrien}
112130561Sobrien
113130561Sobrien/// StandardConversionSequence - Set the standard conversion
11489857Sobrien/// sequence to the identity conversion.
11589857Sobrienvoid StandardConversionSequence::setAsIdentityConversion() {
11689857Sobrien  First = ICK_Identity;
11789857Sobrien  Second = ICK_Identity;
11889857Sobrien  Third = ICK_Identity;
11989857Sobrien  Deprecated = false;
12089857Sobrien  ReferenceBinding = false;
12189857Sobrien  DirectBinding = false;
12289857Sobrien  RRefBinding = false;
12389857Sobrien  CopyConstructor = 0;
12489857Sobrien}
125130561Sobrien
12689857Sobrien/// getRank - Retrieve the rank of this standard conversion sequence
127130561Sobrien/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
128130561Sobrien/// implicit conversions.
129130561SobrienImplicitConversionRank StandardConversionSequence::getRank() const {
130130561Sobrien  ImplicitConversionRank Rank = ICR_Exact_Match;
131130561Sobrien  if  (GetConversionRank(First) > Rank)
132130561Sobrien    Rank = GetConversionRank(First);
133130561Sobrien  if  (GetConversionRank(Second) > Rank)
134130561Sobrien    Rank = GetConversionRank(Second);
13589857Sobrien  if  (GetConversionRank(Third) > Rank)
13689857Sobrien    Rank = GetConversionRank(Third);
13789857Sobrien  return Rank;
13889857Sobrien}
13989857Sobrien
14089857Sobrien/// isPointerConversionToBool - Determines whether this conversion is
14189857Sobrien/// a conversion of a pointer or pointer-to-member to bool. This is
14289857Sobrien/// used as part of the ranking of standard conversion sequences
14389857Sobrien/// (C++ 13.3.3.2p4).
144218822Sdimbool StandardConversionSequence::isPointerConversionToBool() const {
145130561Sobrien  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
146130561Sobrien  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
14789857Sobrien
148130561Sobrien  // Note that FromType has not necessarily been transformed by the
14989857Sobrien  // array-to-pointer or function-to-pointer implicit conversions, so
150218822Sdim  // check for their presence as well as checking whether FromType is
151130561Sobrien  // a pointer.
152218822Sdim  if (ToType->isBooleanType() &&
153218822Sdim      (FromType->isPointerType() || FromType->isBlockPointerType() ||
154218822Sdim       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
155218822Sdim    return true;
156218822Sdim
157218822Sdim  return false;
158218822Sdim}
159218822Sdim
160218822Sdim/// isPointerConversionToVoidPointer - Determines whether this
161218822Sdim/// conversion is a conversion of a pointer to a void pointer. This is
162218822Sdim/// used as part of the ranking of standard conversion sequences (C++
163218822Sdim/// 13.3.3.2p4).
164218822Sdimbool
165218822SdimStandardConversionSequence::
166218822SdimisPointerConversionToVoidPointer(ASTContext& Context) const {
16789857Sobrien  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
16889857Sobrien  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
16989857Sobrien
17089857Sobrien  // Note that FromType has not necessarily been transformed by the
17199461Sobrien  // array-to-pointer implicit conversion, so check for its presence
17299461Sobrien  // and redo the conversion to get a pointer.
17399461Sobrien  if (First == ICK_Array_To_Pointer)
17499461Sobrien    FromType = Context.getArrayDecayedType(FromType);
175104834Sobrien
17689857Sobrien  if (Second == ICK_Pointer_Conversion)
17789857Sobrien    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
17889857Sobrien      return ToPtrType->getPointeeType()->isVoidType();
17989857Sobrien
18089857Sobrien  return false;
18189857Sobrien}
18289857Sobrien
18389857Sobrien/// DebugPrint - Print this standard conversion sequence to standard
184218822Sdim/// error. Useful for debugging overloading issues.
185218822Sdimvoid StandardConversionSequence::DebugPrint() const {
186218822Sdim  bool PrintedSomething = false;
187218822Sdim  if (First != ICK_Identity) {
188218822Sdim    fprintf(stderr, "%s", GetImplicitConversionName(First));
18992828Sobrien    PrintedSomething = true;
19092828Sobrien  }
191218822Sdim
192218822Sdim  if (Second != ICK_Identity) {
193218822Sdim    if (PrintedSomething) {
194218822Sdim      fprintf(stderr, " -> ");
19592828Sobrien    }
19692828Sobrien    fprintf(stderr, "%s", GetImplicitConversionName(Second));
19789857Sobrien
19889857Sobrien    if (CopyConstructor) {
19989857Sobrien      fprintf(stderr, " (by copy constructor)");
200104834Sobrien    } else if (DirectBinding) {
20189857Sobrien      fprintf(stderr, " (direct reference binding)");
20289857Sobrien    } else if (ReferenceBinding) {
20389857Sobrien      fprintf(stderr, " (reference binding)");
20489857Sobrien    }
205104834Sobrien    PrintedSomething = true;
206130561Sobrien  }
20789857Sobrien
208130561Sobrien  if (Third != ICK_Identity) {
20989857Sobrien    if (PrintedSomething) {
21089857Sobrien      fprintf(stderr, " -> ");
21189857Sobrien    }
21289857Sobrien    fprintf(stderr, "%s", GetImplicitConversionName(Third));
21389857Sobrien    PrintedSomething = true;
214130561Sobrien  }
215130561Sobrien
216130561Sobrien  if (!PrintedSomething) {
21789857Sobrien    fprintf(stderr, "No conversions required");
218104834Sobrien  }
21989857Sobrien}
22089857Sobrien
221130561Sobrien/// DebugPrint - Print this user-defined conversion sequence to standard
22289857Sobrien/// error. Useful for debugging overloading issues.
22389857Sobrienvoid UserDefinedConversionSequence::DebugPrint() const {
224130561Sobrien  if (Before.First || Before.Second || Before.Third) {
22589857Sobrien    Before.DebugPrint();
22689857Sobrien    fprintf(stderr, " -> ");
22789857Sobrien  }
22889857Sobrien  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
22989857Sobrien  if (After.First || After.Second || After.Third) {
23089857Sobrien    fprintf(stderr, " -> ");
231130561Sobrien    After.DebugPrint();
23289857Sobrien  }
23389857Sobrien}
23489857Sobrien
23589857Sobrien/// DebugPrint - Print this implicit conversion sequence to standard
236130561Sobrien/// error. Useful for debugging overloading issues.
23789857Sobrienvoid ImplicitConversionSequence::DebugPrint() const {
23889857Sobrien  switch (ConversionKind) {
239130561Sobrien  case StandardConversion:
24089857Sobrien    fprintf(stderr, "Standard conversion: ");
24189857Sobrien    Standard.DebugPrint();
24289857Sobrien    break;
24389857Sobrien  case UserDefinedConversion:
24489857Sobrien    fprintf(stderr, "User-defined conversion: ");
24589857Sobrien    UserDefined.DebugPrint();
24689857Sobrien    break;
247130561Sobrien  case EllipsisConversion:
24889857Sobrien    fprintf(stderr, "Ellipsis conversion");
24989857Sobrien    break;
25089857Sobrien  case BadConversion:
25189857Sobrien    fprintf(stderr, "Bad conversion");
252130561Sobrien    break;
25389857Sobrien  }
254104834Sobrien
255130561Sobrien  fprintf(stderr, "\n");
25689857Sobrien}
25789857Sobrien
25889857Sobrien// IsOverload - Determine whether the given New declaration is an
25989857Sobrien// overload of the Old declaration. This routine returns false if New
26089857Sobrien// and Old cannot be overloaded, e.g., if they are functions with the
26189857Sobrien// same signature (C++ 1.3.10) or if the Old declaration isn't a
262130561Sobrien// function (or overload set). When it does return false and Old is an
26389857Sobrien// OverloadedFunctionDecl, MatchedDecl will be set to point to the
26489857Sobrien// FunctionDecl that New cannot be overloaded with.
26589857Sobrien//
26689857Sobrien// Example: Given the following input:
267130561Sobrien//
26889857Sobrien//   void f(int, float); // #1
26989857Sobrien//   void f(int, int); // #2
270130561Sobrien//   int f(int, int); // #3
27189857Sobrien//
27289857Sobrien// When we process #1, there is no previous declaration of "f",
27389857Sobrien// so IsOverload will not be used.
27489857Sobrien//
27589857Sobrien// When we process #2, Old is a FunctionDecl for #1.  By comparing the
27689857Sobrien// parameter types, we see that #1 and #2 are overloaded (since they
277130561Sobrien// have different signatures), so this routine returns false;
27889857Sobrien// MatchedDecl is unchanged.
27989857Sobrien//
28089857Sobrien// When we process #3, Old is an OverloadedFunctionDecl containing #1
28189857Sobrien// and #2. We compare the signatures of #3 to #1 (they're overloaded,
282130561Sobrien// so we do nothing) and then #3 to #2. Since the signatures of #3 and
28389857Sobrien// #2 are identical (return types of functions are not part of the
28489857Sobrien// signature), IsOverload returns false and MatchedDecl will be set to
285130561Sobrien// point to the FunctionDecl for #2.
28689857Sobrienbool
28789857SobrienSema::IsOverload(FunctionDecl *New, Decl* OldD,
28889857Sobrien                 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
28989857Sobrien  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
29089857Sobrien    // Is this new function an overload of every function in the
29189857Sobrien    // overload set?
292130561Sobrien    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
29389857Sobrien                                           FuncEnd = Ovl->function_end();
29489857Sobrien    for (; Func != FuncEnd; ++Func) {
29589857Sobrien      if (!IsOverload(New, *Func, MatchedDecl)) {
29689857Sobrien        MatchedDecl = Func;
297130561Sobrien        return false;
29889857Sobrien      }
29989857Sobrien    }
300130561Sobrien
30189857Sobrien    // This function overloads every function in the overload set.
30289857Sobrien    return true;
30389857Sobrien  } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
30489857Sobrien    return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
30589857Sobrien  else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
30689857Sobrien    FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
30789857Sobrien    FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308130561Sobrien
30989857Sobrien    // C++ [temp.fct]p2:
31089857Sobrien    //   A function template can be overloaded with other function templates
31199461Sobrien    //   and with normal (non-template) functions.
31289857Sobrien    if ((OldTemplate == 0) != (NewTemplate == 0))
313130561Sobrien      return true;
31489857Sobrien
31589857Sobrien    // Is the function New an overload of the function Old?
316130561Sobrien    QualType OldQType = Context.getCanonicalType(Old->getType());
31789857Sobrien    QualType NewQType = Context.getCanonicalType(New->getType());
31889857Sobrien
31989857Sobrien    // Compare the signatures (C++ 1.3.10) of the two functions to
32089857Sobrien    // determine whether they are overloads. If we find any mismatch
32189857Sobrien    // in the signature, they are overloads.
32289857Sobrien
32389857Sobrien    // If either of these functions is a K&R-style function (no
324130561Sobrien    // prototype), then we consider them to have matching signatures.
32589857Sobrien    if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
32689857Sobrien        isa<FunctionNoProtoType>(NewQType.getTypePtr()))
327218822Sdim      return false;
32889857Sobrien
329130561Sobrien    FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
33089857Sobrien    FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
331104834Sobrien
332130561Sobrien    // The signature of a function includes the types of its
33389857Sobrien    // parameters (C++ 1.3.10), which includes the presence or absence
33489857Sobrien    // of the ellipsis; see C++ DR 357).
33589857Sobrien    if (OldQType != NewQType &&
33689857Sobrien        (OldType->getNumArgs() != NewType->getNumArgs() ||
33789857Sobrien         OldType->isVariadic() != NewType->isVariadic() ||
33889857Sobrien         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
33989857Sobrien                     NewType->arg_type_begin())))
34089857Sobrien      return true;
341130561Sobrien
34289857Sobrien    // C++ [temp.over.link]p4:
34389857Sobrien    //   The signature of a function template consists of its function
34499461Sobrien    //   signature, its return type and its template parameter list. The names
34589857Sobrien    //   of the template parameters are significant only for establishing the
346130561Sobrien    //   relationship between the template parameters and the rest of the
34789857Sobrien    //   signature.
348104834Sobrien    //
349130561Sobrien    // We check the return type and template parameter lists for function
35089857Sobrien    // templates first; the remaining checks follow.
35189857Sobrien    if (NewTemplate &&
35289857Sobrien        (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
35389857Sobrien                                         OldTemplate->getTemplateParameters(),
35489857Sobrien                                         false, TPL_TemplateMatch) ||
35589857Sobrien         OldType->getResultType() != NewType->getResultType()))
35689857Sobrien      return true;
35789857Sobrien
358130561Sobrien    // If the function is a class member, its signature includes the
35989857Sobrien    // cv-qualifiers (if any) on the function itself.
36089857Sobrien    //
36199461Sobrien    // As part of this, also check whether one of the member functions
36289857Sobrien    // is static, in which case they are not overloads (C++
363130561Sobrien    // 13.1p2). While not part of the definition of the signature,
36489857Sobrien    // this check is important to determine whether these functions
365104834Sobrien    // can be overloaded.
366130561Sobrien    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
36789857Sobrien    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
36889857Sobrien    if (OldMethod && NewMethod &&
36989857Sobrien        !OldMethod->isStatic() && !NewMethod->isStatic() &&
37089857Sobrien        OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
37189857Sobrien      return true;
37289857Sobrien
373130561Sobrien    // The signatures match; this is not an overload.
37489857Sobrien    return false;
37589857Sobrien  } else {
376218822Sdim    // (C++ 13p1):
37789857Sobrien    //   Only function declarations can be overloaded; object and type
378130561Sobrien    //   declarations cannot be overloaded.
37989857Sobrien    return false;
380104834Sobrien  }
381130561Sobrien}
38289857Sobrien
38389857Sobrien/// TryImplicitConversion - Attempt to perform an implicit conversion
38489857Sobrien/// from the given expression (Expr) to the given type (ToType). This
38589857Sobrien/// function returns an implicit conversion sequence that can be used
38689857Sobrien/// to perform the initialization. Given
38789857Sobrien///
388130561Sobrien///   void f(float f);
38989857Sobrien///   void g(int i) { f(i); }
39089857Sobrien///
391218822Sdim/// this routine would produce an implicit conversion sequence to
39289857Sobrien/// describe the initialization of f from i, which will be a standard
393130561Sobrien/// conversion sequence containing an lvalue-to-rvalue conversion (C++
39489857Sobrien/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395104834Sobrien//
396130561Sobrien/// Note that this routine only determines how the conversion can be
39789857Sobrien/// performed; it does not actually perform the conversion. As such,
39889857Sobrien/// it will not produce any diagnostics if no conversion is available,
39989857Sobrien/// but will instead return an implicit conversion sequence of kind
40089857Sobrien/// "BadConversion".
40189857Sobrien///
40289857Sobrien/// If @p SuppressUserConversions, then user-defined conversions are
40389857Sobrien/// not permitted.
40489857Sobrien/// If @p AllowExplicit, then explicit user-defined conversions are
405130561Sobrien/// permitted.
40689857Sobrien/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
40789857Sobrien/// no matter its actual lvalueness.
40899461Sobrien/// If @p UserCast, the implicit conversion is being done for a user-specified
40989857Sobrien/// cast.
410130561SobrienImplicitConversionSequence
41189857SobrienSema::TryImplicitConversion(Expr* From, QualType ToType,
412104834Sobrien                            bool SuppressUserConversions,
413130561Sobrien                            bool AllowExplicit, bool ForceRValue,
41489857Sobrien                            bool InOverloadResolution,
41589857Sobrien                            bool UserCast) {
41689857Sobrien  ImplicitConversionSequence ICS;
41789857Sobrien  OverloadCandidateSet Conversions;
41889857Sobrien  OverloadingResult UserDefResult = OR_Success;
41989857Sobrien  if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
42089857Sobrien    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
42189857Sobrien  else if (getLangOptions().CPlusPlus &&
422130561Sobrien           (UserDefResult = IsUserDefinedConversion(From, ToType,
42389857Sobrien                                   ICS.UserDefined,
42489857Sobrien                                   Conversions,
42599461Sobrien                                   !SuppressUserConversions, AllowExplicit,
42689857Sobrien				   ForceRValue, UserCast)) == OR_Success) {
427130561Sobrien    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
42889857Sobrien    // C++ [over.ics.user]p4:
429104834Sobrien    //   A conversion of an expression of class type to the same class
430130561Sobrien    //   type is given Exact Match rank, and a conversion of an
43189857Sobrien    //   expression of class type to a base class of that type is
43289857Sobrien    //   given Conversion rank, in spite of the fact that a copy
43389857Sobrien    //   constructor (i.e., a user-defined conversion function) is
43489857Sobrien    //   called for those cases.
43589857Sobrien    if (CXXConstructorDecl *Constructor
43689857Sobrien          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
43789857Sobrien      QualType FromCanon
438130561Sobrien        = Context.getCanonicalType(From->getType().getUnqualifiedType());
43989857Sobrien      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
44089857Sobrien      if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
44199461Sobrien        // Turn this into a "standard" conversion sequence, so that it
44289857Sobrien        // gets ranked with standard conversion sequences.
443130561Sobrien        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
44489857Sobrien        ICS.Standard.setAsIdentityConversion();
44589857Sobrien        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
446130561Sobrien        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
44789857Sobrien        ICS.Standard.CopyConstructor = Constructor;
44889857Sobrien        if (ToCanon != FromCanon)
44989857Sobrien          ICS.Standard.Second = ICK_Derived_To_Base;
45089857Sobrien      }
45189857Sobrien    }
45289857Sobrien
45389857Sobrien    // C++ [over.best.ics]p4:
454130561Sobrien    //   However, when considering the argument of a user-defined
45589857Sobrien    //   conversion function that is a candidate by 13.3.1.3 when
45689857Sobrien    //   invoked for the copying of the temporary in the second step
45799461Sobrien    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
45889857Sobrien    //   13.3.1.6 in all cases, only standard conversion sequences and
459130561Sobrien    //   ellipsis conversion sequences are allowed.
46089857Sobrien    if (SuppressUserConversions &&
46189857Sobrien        ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
462130561Sobrien      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
46389857Sobrien  } else {
46489857Sobrien    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
46589857Sobrien    if (UserDefResult == OR_Ambiguous) {
46689857Sobrien      for (OverloadCandidateSet::iterator Cand = Conversions.begin();
46789857Sobrien           Cand != Conversions.end(); ++Cand)
46889857Sobrien        if (Cand->Viable)
46989857Sobrien          ICS.ConversionFunctionSet.push_back(Cand->Function);
470130561Sobrien    }
47189857Sobrien  }
47289857Sobrien
47399461Sobrien  return ICS;
47489857Sobrien}
475130561Sobrien
47689857Sobrien/// IsStandardConversion - Determines whether there is a standard
47789857Sobrien/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
478130561Sobrien/// expression From to the type ToType. Standard conversion sequences
47989857Sobrien/// only consider non-class types; for conversions that involve class
48089857Sobrien/// types, use TryImplicitConversion. If a conversion exists, SCS will
48189857Sobrien/// contain the standard conversion sequence required to perform this
48289857Sobrien/// conversion and this routine will return true. Otherwise, this
48389857Sobrien/// routine will return false and the value of SCS is unspecified.
48489857Sobrienbool
48589857SobrienSema::IsStandardConversion(Expr* From, QualType ToType,
486130561Sobrien                           bool InOverloadResolution,
48789857Sobrien                           StandardConversionSequence &SCS) {
48889857Sobrien  QualType FromType = From->getType();
48999461Sobrien
49089857Sobrien  // Standard conversions (C++ [conv])
491130561Sobrien  SCS.setAsIdentityConversion();
49289857Sobrien  SCS.Deprecated = false;
49389857Sobrien  SCS.IncompatibleObjC = false;
494130561Sobrien  SCS.FromTypePtr = FromType.getAsOpaquePtr();
49589857Sobrien  SCS.CopyConstructor = 0;
49689857Sobrien
49789857Sobrien  // There are no standard conversions for class types in C++, so
49889857Sobrien  // abort early. When overloading in C, however, we do permit
49989857Sobrien  if (FromType->isRecordType() || ToType->isRecordType()) {
50089857Sobrien    if (getLangOptions().CPlusPlus)
50189857Sobrien      return false;
50289857Sobrien
503104834Sobrien    // When we're overloading in C, we allow, as standard conversions,
504104834Sobrien  }
505130561Sobrien
50689857Sobrien  // The first conversion can be an lvalue-to-rvalue conversion,
507104834Sobrien  // array-to-pointer conversion, or function-to-pointer conversion
508104834Sobrien  // (C++ 4p1).
50989857Sobrien
510130561Sobrien  // Lvalue-to-rvalue conversion (C++ 4.1):
51189857Sobrien  //   An lvalue (3.10) of a non-function, non-array type T can be
51289857Sobrien  //   converted to an rvalue.
513130561Sobrien  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
51489857Sobrien  if (argIsLvalue == Expr::LV_Valid &&
51589857Sobrien      !FromType->isFunctionType() && !FromType->isArrayType() &&
51689857Sobrien      Context.getCanonicalType(FromType) != Context.OverloadTy) {
51789857Sobrien    SCS.First = ICK_Lvalue_To_Rvalue;
51889857Sobrien
51989857Sobrien    // If T is a non-class type, the type of the rvalue is the
52089857Sobrien    // cv-unqualified version of T. Otherwise, the type of the rvalue
521130561Sobrien    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
52289857Sobrien    // just strip the qualifiers because they don't matter.
52389857Sobrien    FromType = FromType.getUnqualifiedType();
52499461Sobrien  } else if (FromType->isArrayType()) {
52589857Sobrien    // Array-to-pointer conversion (C++ 4.2)
526130561Sobrien    SCS.First = ICK_Array_To_Pointer;
52789857Sobrien
528104834Sobrien    // An lvalue or rvalue of type "array of N T" or "array of unknown
529130561Sobrien    // bound of T" can be converted to an rvalue of type "pointer to
53089857Sobrien    // T" (C++ 4.2p1).
53189857Sobrien    FromType = Context.getArrayDecayedType(FromType);
53289857Sobrien
53389857Sobrien    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
53489857Sobrien      // This conversion is deprecated. (C++ D.4).
53589857Sobrien      SCS.Deprecated = true;
53689857Sobrien
537130561Sobrien      // For the purpose of ranking in overload resolution
53889857Sobrien      // (13.3.3.1.1), this conversion is considered an
53989857Sobrien      // array-to-pointer conversion followed by a qualification
54099461Sobrien      // conversion (4.4). (C++ 4.2p2)
54189857Sobrien      SCS.Second = ICK_Identity;
542130561Sobrien      SCS.Third = ICK_Qualification;
54389857Sobrien      SCS.ToTypePtr = ToType.getAsOpaquePtr();
54489857Sobrien      return true;
545130561Sobrien    }
54689857Sobrien  } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
54789857Sobrien    // Function-to-pointer conversion (C++ 4.3).
54889857Sobrien    SCS.First = ICK_Function_To_Pointer;
54989857Sobrien
55089857Sobrien    // An lvalue of function type T can be converted to an rvalue of
55189857Sobrien    // type "pointer to T." The result is a pointer to the
55289857Sobrien    // function. (C++ 4.3p1).
55389857Sobrien    FromType = Context.getPointerType(FromType);
554130561Sobrien  } else if (FunctionDecl *Fn
55589857Sobrien             = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
55689857Sobrien    // Address of overloaded function (C++ [over.over]).
55789857Sobrien    SCS.First = ICK_Function_To_Pointer;
55889857Sobrien
559130561Sobrien    // We were able to resolve the address of the overloaded function,
56089857Sobrien    // so we can convert to the type of that function.
561104834Sobrien    FromType = Fn->getType();
562130561Sobrien    if (ToType->isLValueReferenceType())
56389857Sobrien      FromType = Context.getLValueReferenceType(FromType);
56489857Sobrien    else if (ToType->isRValueReferenceType())
56589857Sobrien      FromType = Context.getRValueReferenceType(FromType);
56689857Sobrien    else if (ToType->isMemberPointerType()) {
56789857Sobrien      // Resolve address only succeeds if both sides are member pointers,
56889857Sobrien      // but it doesn't have to be the same class. See DR 247.
569130561Sobrien      // Note that this means that the type of &Derived::fn can be
57089857Sobrien      // Ret (Base::*)(Args) if the fn overload actually found is from the
57189857Sobrien      // base class, even if it was brought into the derived class via a
57289857Sobrien      // using declaration. The standard isn't clear on this issue at all.
57389857Sobrien      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
574130561Sobrien      FromType = Context.getMemberPointerType(FromType,
57589857Sobrien                    Context.getTypeDeclType(M->getParent()).getTypePtr());
57689857Sobrien    } else
577130561Sobrien      FromType = Context.getPointerType(FromType);
57889857Sobrien  } else {
57989857Sobrien    // We don't require any conversions for the first step.
58089857Sobrien    SCS.First = ICK_Identity;
58189857Sobrien  }
58289857Sobrien
58389857Sobrien  // The second conversion can be an integral promotion, floating
584130561Sobrien  // point promotion, integral conversion, floating point conversion,
58589857Sobrien  // floating-integral conversion, pointer conversion,
58689857Sobrien  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
58789857Sobrien  // For overloading in C, this can also be a "compatible-type"
58889857Sobrien  // conversion.
589130561Sobrien  bool IncompatibleObjC = false;
59089857Sobrien  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
59189857Sobrien    // The unqualified versions of the types are the same: there's no
592130561Sobrien    // conversion to do.
59389857Sobrien    SCS.Second = ICK_Identity;
59489857Sobrien  } else if (IsIntegralPromotion(From, FromType, ToType)) {
59589857Sobrien    // Integral promotion (C++ 4.5).
59689857Sobrien    SCS.Second = ICK_Integral_Promotion;
59789857Sobrien    FromType = ToType.getUnqualifiedType();
59889857Sobrien  } else if (IsFloatingPointPromotion(FromType, ToType)) {
599130561Sobrien    // Floating point promotion (C++ 4.6).
60089857Sobrien    SCS.Second = ICK_Floating_Promotion;
601104834Sobrien    FromType = ToType.getUnqualifiedType();
60289857Sobrien  } else if (IsComplexPromotion(FromType, ToType)) {
60389857Sobrien    // Complex promotion (Clang extension)
60489857Sobrien    SCS.Second = ICK_Complex_Promotion;
605130561Sobrien    FromType = ToType.getUnqualifiedType();
60689857Sobrien  } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
60789857Sobrien           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
608130561Sobrien    // Integral conversions (C++ 4.7).
60989857Sobrien    // FIXME: isIntegralType shouldn't be true for enums in C++.
61089857Sobrien    SCS.Second = ICK_Integral_Conversion;
61189857Sobrien    FromType = ToType.getUnqualifiedType();
61289857Sobrien  } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
61389857Sobrien    // Floating point conversions (C++ 4.8).
61489857Sobrien    SCS.Second = ICK_Floating_Conversion;
615130561Sobrien    FromType = ToType.getUnqualifiedType();
61689857Sobrien  } else if (FromType->isComplexType() && ToType->isComplexType()) {
61789857Sobrien    // Complex conversions (C99 6.3.1.6)
61899461Sobrien    SCS.Second = ICK_Complex_Conversion;
61989857Sobrien    FromType = ToType.getUnqualifiedType();
620130561Sobrien  } else if ((FromType->isFloatingType() &&
62189857Sobrien              ToType->isIntegralType() && (!ToType->isBooleanType() &&
622104834Sobrien                                           !ToType->isEnumeralType())) ||
623130561Sobrien             ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
62489857Sobrien              ToType->isFloatingType())) {
62589857Sobrien    // Floating-integral conversions (C++ 4.9).
62689857Sobrien    // FIXME: isIntegralType shouldn't be true for enums in C++.
62789857Sobrien    SCS.Second = ICK_Floating_Integral;
62889857Sobrien    FromType = ToType.getUnqualifiedType();
62989857Sobrien  } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
63089857Sobrien             (ToType->isComplexType() && FromType->isArithmeticType())) {
631130561Sobrien    // Complex-real conversions (C99 6.3.1.7)
63289857Sobrien    SCS.Second = ICK_Complex_Real;
63389857Sobrien    FromType = ToType.getUnqualifiedType();
63489857Sobrien  } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
63589857Sobrien                                 FromType, IncompatibleObjC)) {
636130561Sobrien    // Pointer conversions (C++ 4.10).
63789857Sobrien    SCS.Second = ICK_Pointer_Conversion;
638104834Sobrien    SCS.IncompatibleObjC = IncompatibleObjC;
639130561Sobrien  } else if (IsMemberPointerConversion(From, FromType, ToType,
64089857Sobrien                                       InOverloadResolution, FromType)) {
64189857Sobrien    // Pointer to member conversions (4.11).
64289857Sobrien    SCS.Second = ICK_Pointer_Member;
64389857Sobrien  } else if (ToType->isBooleanType() &&
64489857Sobrien             (FromType->isArithmeticType() ||
64589857Sobrien              FromType->isEnumeralType() ||
64689857Sobrien              FromType->isPointerType() ||
647130561Sobrien              FromType->isBlockPointerType() ||
64889857Sobrien              FromType->isMemberPointerType() ||
64989857Sobrien              FromType->isNullPtrType())) {
65099461Sobrien    // Boolean conversions (C++ 4.12).
65189857Sobrien    SCS.Second = ICK_Boolean_Conversion;
652130561Sobrien    FromType = Context.BoolTy;
65389857Sobrien  } else if (!getLangOptions().CPlusPlus &&
65489857Sobrien             Context.typesAreCompatible(ToType, FromType)) {
655130561Sobrien    // Compatible conversions (Clang extension for C function overloading)
65689857Sobrien    SCS.Second = ICK_Compatible_Conversion;
65789857Sobrien  } else {
65889857Sobrien    // No second conversion required.
65989857Sobrien    SCS.Second = ICK_Identity;
66089857Sobrien  }
66189857Sobrien
66289857Sobrien  QualType CanonFrom;
663130561Sobrien  QualType CanonTo;
66489857Sobrien  // The third conversion can be a qualification conversion (C++ 4p1).
66589857Sobrien  if (IsQualificationConversion(FromType, ToType)) {
66699461Sobrien    SCS.Third = ICK_Qualification;
66789857Sobrien    FromType = ToType;
668130561Sobrien    CanonFrom = Context.getCanonicalType(FromType);
66989857Sobrien    CanonTo = Context.getCanonicalType(ToType);
67089857Sobrien  } else {
671130561Sobrien    // No conversion required
67289857Sobrien    SCS.Third = ICK_Identity;
67389857Sobrien
67489857Sobrien    // C++ [over.best.ics]p6:
67589857Sobrien    //   [...] Any difference in top-level cv-qualification is
67689857Sobrien    //   subsumed by the initialization itself and does not constitute
67789857Sobrien    //   a conversion. [...]
67889857Sobrien    CanonFrom = Context.getCanonicalType(FromType);
679130561Sobrien    CanonTo = Context.getCanonicalType(ToType);
68089857Sobrien    if (CanonFrom.getLocalUnqualifiedType()
68189857Sobrien                                       == CanonTo.getLocalUnqualifiedType() &&
68299461Sobrien        CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
68389857Sobrien      FromType = ToType;
684130561Sobrien      CanonFrom = CanonTo;
68589857Sobrien    }
68689857Sobrien  }
687130561Sobrien
68889857Sobrien  // If we have not converted the argument type to the parameter type,
68999461Sobrien  // this is a bad conversion sequence.
69089857Sobrien  if (CanonFrom != CanonTo)
69189857Sobrien    return false;
69299461Sobrien
69399461Sobrien  SCS.ToTypePtr = FromType.getAsOpaquePtr();
694130561Sobrien  return true;
69589857Sobrien}
69689857Sobrien
69799461Sobrien/// IsIntegralPromotion - Determines whether the conversion from the
69889857Sobrien/// expression From (whose potentially-adjusted type is FromType) to
699130561Sobrien/// ToType is an integral promotion (C++ 4.5). If so, returns true and
70089857Sobrien/// sets PromotedType to the promoted type.
70199461Sobrienbool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
702130561Sobrien  const BuiltinType *To = ToType->getAs<BuiltinType>();
70389857Sobrien  // All integers are built-in.
70499461Sobrien  if (!To) {
70589857Sobrien    return false;
70689857Sobrien  }
70789857Sobrien
70889857Sobrien  // An rvalue of type char, signed char, unsigned char, short int, or
709130561Sobrien  // unsigned short int can be converted to an rvalue of type int if
71089857Sobrien  // int can represent all the values of the source type; otherwise,
71189857Sobrien  // the source rvalue can be converted to an rvalue of type unsigned
71299461Sobrien  // int (C++ 4.5p1).
71389857Sobrien  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
714130561Sobrien    if (// We can promote any signed, promotable integer type to an int
71589857Sobrien        (FromType->isSignedIntegerType() ||
71689857Sobrien         // We can promote any unsigned integer type whose size is
717130561Sobrien         // less than int to an int.
71889857Sobrien         (!FromType->isSignedIntegerType() &&
71989857Sobrien          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
72089857Sobrien      return To->getKind() == BuiltinType::Int;
72189857Sobrien    }
72289857Sobrien
72389857Sobrien    return To->getKind() == BuiltinType::UInt;
724130561Sobrien  }
72589857Sobrien
72689857Sobrien  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
72799461Sobrien  // can be converted to an rvalue of the first of the following types
72889857Sobrien  // that can represent all the values of its underlying type: int,
729130561Sobrien  // unsigned int, long, or unsigned long (C++ 4.5p2).
73089857Sobrien  if ((FromType->isEnumeralType() || FromType->isWideCharType())
73189857Sobrien      && ToType->isIntegerType()) {
732130561Sobrien    // Determine whether the type we're converting from is signed or
73389857Sobrien    // unsigned.
73489857Sobrien    bool FromIsSigned;
73589857Sobrien    uint64_t FromSize = Context.getTypeSize(FromType);
73689857Sobrien    if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
73789857Sobrien      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
73889857Sobrien      FromIsSigned = UnderlyingType->isSignedIntegerType();
739130561Sobrien    } else {
74089857Sobrien      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
74189857Sobrien      FromIsSigned = true;
74299461Sobrien    }
74389857Sobrien
744130561Sobrien    // The types we'll try to promote to, in the appropriate
74589857Sobrien    // order. Try each of these types.
74689857Sobrien    QualType PromoteTypes[6] = {
747130561Sobrien      Context.IntTy, Context.UnsignedIntTy,
74889857Sobrien      Context.LongTy, Context.UnsignedLongTy ,
749130561Sobrien      Context.LongLongTy, Context.UnsignedLongLongTy
750130561Sobrien    };
75189857Sobrien    for (int Idx = 0; Idx < 6; ++Idx) {
75289857Sobrien      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
75389857Sobrien      if (FromSize < ToSize ||
754130561Sobrien          (FromSize == ToSize &&
75589857Sobrien           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
75689857Sobrien        // We found the type that we can promote to. If this is the
75789857Sobrien        // type we wanted, we have a promotion. Otherwise, no
758130561Sobrien        // promotion.
759130561Sobrien        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
76089857Sobrien      }
76189857Sobrien    }
762130561Sobrien  }
76389857Sobrien
76489857Sobrien  // An rvalue for an integral bit-field (9.6) can be converted to an
76589857Sobrien  // rvalue of type int if int can represent all the values of the
76689857Sobrien  // bit-field; otherwise, it can be converted to unsigned int if
76789857Sobrien  // unsigned int can represent all the values of the bit-field. If
76889857Sobrien  // the bit-field is larger yet, no integral promotion applies to
76989857Sobrien  // it. If the bit-field has an enumerated type, it is treated as any
77089857Sobrien  // other value of that type for promotion purposes (C++ 4.5p3).
771130561Sobrien  // FIXME: We should delay checking of bit-fields until we actually perform the
77289857Sobrien  // conversion.
77389857Sobrien  using llvm::APSInt;
77489857Sobrien  if (From)
77589857Sobrien    if (FieldDecl *MemberDecl = From->getBitField()) {
776130561Sobrien      APSInt BitWidth;
77789857Sobrien      if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
778104834Sobrien          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
779130561Sobrien        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
78089857Sobrien        ToSize = Context.getTypeSize(ToType);
78189857Sobrien
78289857Sobrien        // Are we promoting to an int from a bitfield that fits in an int?
78389857Sobrien        if (BitWidth < ToSize ||
78489857Sobrien            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
78589857Sobrien          return To->getKind() == BuiltinType::Int;
786130561Sobrien        }
78789857Sobrien
78889857Sobrien        // Are we promoting to an unsigned int from an unsigned bitfield
78989857Sobrien        // that fits into an unsigned int?
79089857Sobrien        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
791130561Sobrien          return To->getKind() == BuiltinType::UInt;
79289857Sobrien        }
79389857Sobrien
794130561Sobrien        return false;
79589857Sobrien      }
79689857Sobrien    }
79789857Sobrien
79889857Sobrien  // An rvalue of type bool can be converted to an rvalue of type int,
79989857Sobrien  // with false becoming zero and true becoming one (C++ 4.5p4).
80089857Sobrien  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
80189857Sobrien    return true;
802130561Sobrien  }
80389857Sobrien
80489857Sobrien  return false;
80599461Sobrien}
80689857Sobrien
807130561Sobrien/// IsFloatingPointPromotion - Determines whether the conversion from
80889857Sobrien/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
80989857Sobrien/// returns true and sets PromotedType to the promoted type.
810130561Sobrienbool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
81189857Sobrien  /// An rvalue of type float can be converted to an rvalue of type
81289857Sobrien  /// double. (C++ 4.6p1).
81389857Sobrien  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
81489857Sobrien    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
81589857Sobrien      if (FromBuiltin->getKind() == BuiltinType::Float &&
81689857Sobrien          ToBuiltin->getKind() == BuiltinType::Double)
817130561Sobrien        return true;
81889857Sobrien
81989857Sobrien      // C99 6.3.1.5p1:
82089857Sobrien      //   When a float is promoted to double or long double, or a
82189857Sobrien      //   double is promoted to long double [...].
822130561Sobrien      if (!getLangOptions().CPlusPlus &&
82389857Sobrien          (FromBuiltin->getKind() == BuiltinType::Float ||
82489857Sobrien           FromBuiltin->getKind() == BuiltinType::Double) &&
825130561Sobrien          (ToBuiltin->getKind() == BuiltinType::LongDouble))
82689857Sobrien        return true;
82789857Sobrien    }
82889857Sobrien
82989857Sobrien  return false;
83089857Sobrien}
83189857Sobrien
83289857Sobrien/// \brief Determine if a conversion is a complex promotion.
833130561Sobrien///
83489857Sobrien/// A complex promotion is defined as a complex -> complex conversion
83589857Sobrien/// where the conversion between the underlying real types is a
83699461Sobrien/// floating-point or integral promotion.
83789857Sobrienbool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
838130561Sobrien  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
83989857Sobrien  if (!FromComplex)
84089857Sobrien    return false;
841130561Sobrien
84289857Sobrien  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
84389857Sobrien  if (!ToComplex)
84489857Sobrien    return false;
84589857Sobrien
84689857Sobrien  return IsFloatingPointPromotion(FromComplex->getElementType(),
84789857Sobrien                                  ToComplex->getElementType()) ||
848130561Sobrien    IsIntegralPromotion(0, FromComplex->getElementType(),
84989857Sobrien                        ToComplex->getElementType());
85089857Sobrien}
85189857Sobrien
85289857Sobrien/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
853130561Sobrien/// the pointer type FromPtr to a pointer to type ToPointee, with the
85489857Sobrien/// same type qualifiers as FromPtr has on its pointee type. ToType,
855104834Sobrien/// if non-empty, will be a pointer to ToType that may or may not have
856130561Sobrien/// the right set of qualifiers on its pointee.
85789857Sobrienstatic QualType
85889857SobrienBuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
85989857Sobrien                                   QualType ToPointee, QualType ToType,
86089857Sobrien                                   ASTContext &Context) {
86189857Sobrien  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
86289857Sobrien  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
863130561Sobrien  Qualifiers Quals = CanonFromPointee.getQualifiers();
86489857Sobrien
86589857Sobrien  // Exact qualifier match -> return the pointer type we're converting to.
86689857Sobrien  if (CanonToPointee.getLocalQualifiers() == Quals) {
86789857Sobrien    // ToType is exactly what we need. Return it.
868130561Sobrien    if (!ToType.isNull())
86989857Sobrien      return ToType;
870104834Sobrien
871130561Sobrien    // Build a pointer to ToPointee. It has the right qualifiers
87289857Sobrien    // already.
873104834Sobrien    return Context.getPointerType(ToPointee);
87489857Sobrien  }
87589857Sobrien
87689857Sobrien  // Just build a canonical type that has the right qualifiers.
87789857Sobrien  return Context.getPointerType(
878130561Sobrien         Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
87989857Sobrien                                  Quals));
88089857Sobrien}
88199461Sobrien
88289857Sobrienstatic bool isNullPointerConstantForConversion(Expr *Expr,
883130561Sobrien                                               bool InOverloadResolution,
88489857Sobrien                                               ASTContext &Context) {
885104834Sobrien  // Handle value-dependent integral null pointer constants correctly.
886130561Sobrien  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
88789857Sobrien  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
88889857Sobrien      Expr->getType()->isIntegralType())
88989857Sobrien    return !InOverloadResolution;
89089857Sobrien
89189857Sobrien  return Expr->isNullPointerConstant(Context,
89289857Sobrien                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
89389857Sobrien                                        : Expr::NPC_ValueDependentIsNull);
89489857Sobrien}
895130561Sobrien
89689857Sobrien/// IsPointerConversion - Determines whether the conversion of the
89789857Sobrien/// expression From, which has the (possibly adjusted) type FromType,
89899461Sobrien/// can be converted to the type ToType via a pointer conversion (C++
89989857Sobrien/// 4.10). If so, returns true and places the converted type (that
900130561Sobrien/// might differ from ToType in its cv-qualifiers at some level) into
90189857Sobrien/// ConvertedType.
902104834Sobrien///
903130561Sobrien/// This routine also supports conversions to and from block pointers
90489857Sobrien/// and conversions with Objective-C's 'id', 'id<protocols...>', and
90589857Sobrien/// pointers to interfaces. FIXME: Once we've determined the
90689857Sobrien/// appropriate overloading rules for Objective-C, we may want to
90789857Sobrien/// split the Objective-C checks into a different routine; however,
90889857Sobrien/// GCC seems to consider all of these conversions to be pointer
90989857Sobrien/// conversions, so for now they live here. IncompatibleObjC will be
91089857Sobrien/// set if the conversion is an allowed Objective-C conversion that
91189857Sobrien/// should result in a warning.
912130561Sobrienbool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
91389857Sobrien                               bool InOverloadResolution,
91489857Sobrien                               QualType& ConvertedType,
91599461Sobrien                               bool &IncompatibleObjC) {
91689857Sobrien  IncompatibleObjC = false;
917130561Sobrien  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
91889857Sobrien    return true;
91989857Sobrien
920130561Sobrien  // Conversion from a null pointer constant to any Objective-C pointer type.
92189857Sobrien  if (ToType->isObjCObjectPointerType() &&
92289857Sobrien      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
92389857Sobrien    ConvertedType = ToType;
92489857Sobrien    return true;
92589857Sobrien  }
92689857Sobrien
92789857Sobrien  // Blocks: Block pointers can be converted to void*.
92889857Sobrien  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
929130561Sobrien      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
93089857Sobrien    ConvertedType = ToType;
93189857Sobrien    return true;
93299461Sobrien  }
93389857Sobrien  // Blocks: A null pointer constant can be converted to a block
934130561Sobrien  // pointer type.
93589857Sobrien  if (ToType->isBlockPointerType() &&
93689857Sobrien      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
937130561Sobrien    ConvertedType = ToType;
93889857Sobrien    return true;
93989857Sobrien  }
94089857Sobrien
94189857Sobrien  // If the left-hand-side is nullptr_t, the right side can be a null
94289857Sobrien  // pointer constant.
94389857Sobrien  if (ToType->isNullPtrType() &&
94489857Sobrien      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
94589857Sobrien    ConvertedType = ToType;
946130561Sobrien    return true;
94789857Sobrien  }
94889857Sobrien
94999461Sobrien  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
95089857Sobrien  if (!ToTypePtr)
951130561Sobrien    return false;
95289857Sobrien
95389857Sobrien  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
954130561Sobrien  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
95589857Sobrien    ConvertedType = ToType;
95689857Sobrien    return true;
95789857Sobrien  }
95889857Sobrien
95989857Sobrien  // Beyond this point, both types need to be pointers.
96089857Sobrien  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
96189857Sobrien  if (!FromTypePtr)
96289857Sobrien    return false;
96389857Sobrien
96489857Sobrien  QualType FromPointeeType = FromTypePtr->getPointeeType();
965130561Sobrien  QualType ToPointeeType = ToTypePtr->getPointeeType();
96689857Sobrien
96789857Sobrien  // An rvalue of type "pointer to cv T," where T is an object type,
96899461Sobrien  // can be converted to an rvalue of type "pointer to cv void" (C++
96989857Sobrien  // 4.10p2).
970130561Sobrien  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
97189857Sobrien    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
97289857Sobrien                                                       ToPointeeType,
973130561Sobrien                                                       ToType, Context);
97489857Sobrien    return true;
97589857Sobrien  }
97689857Sobrien
97789857Sobrien  // When we're overloading in C, we allow a special kind of pointer
97889857Sobrien  // conversion for compatible-but-not-identical pointee types.
97989857Sobrien  if (!getLangOptions().CPlusPlus &&
98089857Sobrien      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
98189857Sobrien    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
982130561Sobrien                                                       ToPointeeType,
98389857Sobrien                                                       ToType, Context);
98489857Sobrien    return true;
98599461Sobrien  }
98689857Sobrien
987130561Sobrien  // C++ [conv.ptr]p3:
98889857Sobrien  //
989104834Sobrien  //   An rvalue of type "pointer to cv D," where D is a class type,
990130561Sobrien  //   can be converted to an rvalue of type "pointer to cv B," where
99189857Sobrien  //   B is a base class (clause 10) of D. If B is an inaccessible
99289857Sobrien  //   (clause 11) or ambiguous (10.2) base class of D, a program that
99389857Sobrien  //   necessitates this conversion is ill-formed. The result of the
99489857Sobrien  //   conversion is a pointer to the base class sub-object of the
99589857Sobrien  //   derived class object. The null pointer value is converted to
99689857Sobrien  //   the null pointer value of the destination type.
99789857Sobrien  //
99889857Sobrien  // Note that we do not check for ambiguity or inaccessibility
99989857Sobrien  // here. That is handled by CheckPointerConversion.
100089857Sobrien  if (getLangOptions().CPlusPlus &&
100189857Sobrien      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
100289857Sobrien      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
100389857Sobrien      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
100489857Sobrien    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1005130561Sobrien                                                       ToPointeeType,
100689857Sobrien                                                       ToType, Context);
100789857Sobrien    return true;
100899461Sobrien  }
100989857Sobrien
1010130561Sobrien  return false;
101189857Sobrien}
101289857Sobrien
1013130561Sobrien/// isObjCPointerConversion - Determines whether this is an
101489857Sobrien/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
101589857Sobrien/// with the same arguments and return values.
101689857Sobrienbool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
101789857Sobrien                                   QualType& ConvertedType,
101889857Sobrien                                   bool &IncompatibleObjC) {
101989857Sobrien  if (!getLangOptions().ObjC1)
102089857Sobrien    return false;
1021130561Sobrien
102289857Sobrien  // First, we handle all conversions on ObjC object pointer types.
102389857Sobrien  const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
102499461Sobrien  const ObjCObjectPointerType *FromObjCPtr =
102589857Sobrien    FromType->getAs<ObjCObjectPointerType>();
1026130561Sobrien
102789857Sobrien  if (ToObjCPtr && FromObjCPtr) {
102889857Sobrien    // Objective C++: We're able to convert between "id" or "Class" and a
1029130561Sobrien    // pointer to any interface (in both directions).
103089857Sobrien    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
103189857Sobrien      ConvertedType = ToType;
103289857Sobrien      return true;
103389857Sobrien    }
103489857Sobrien    // Conversions with Objective-C's id<...>.
103589857Sobrien    if ((FromObjCPtr->isObjCQualifiedIdType() ||
103689857Sobrien         ToObjCPtr->isObjCQualifiedIdType()) &&
1037130561Sobrien        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
103889857Sobrien                                                  /*compare=*/false)) {
103989857Sobrien      ConvertedType = ToType;
104099461Sobrien      return true;
104189857Sobrien    }
1042130561Sobrien    // Objective C++: We're able to convert from a pointer to an
104389857Sobrien    // interface to a pointer to a different interface.
104489857Sobrien    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1045130561Sobrien      ConvertedType = ToType;
104689857Sobrien      return true;
104789857Sobrien    }
104889857Sobrien
104989857Sobrien    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
105089857Sobrien      // Okay: this is some kind of implicit downcast of Objective-C
105189857Sobrien      // interfaces, which is permitted. However, we're going to
105289857Sobrien      // complain about it.
105389857Sobrien      IncompatibleObjC = true;
105489857Sobrien      ConvertedType = FromType;
1055130561Sobrien      return true;
105689857Sobrien    }
105789857Sobrien  }
105899461Sobrien  // Beyond this point, both types need to be C pointers or block pointers.
105989857Sobrien  QualType ToPointeeType;
1060130561Sobrien  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
106189857Sobrien    ToPointeeType = ToCPtr->getPointeeType();
106289857Sobrien  else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
1063130561Sobrien    ToPointeeType = ToBlockPtr->getPointeeType();
106489857Sobrien  else
106589857Sobrien    return false;
106689857Sobrien
106789857Sobrien  QualType FromPointeeType;
106889857Sobrien  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
106989857Sobrien    FromPointeeType = FromCPtr->getPointeeType();
1070130561Sobrien  else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
107189857Sobrien    FromPointeeType = FromBlockPtr->getPointeeType();
107289857Sobrien  else
107389857Sobrien    return false;
107489857Sobrien
1075130561Sobrien  // If we have pointers to pointers, recursively check whether this
107689857Sobrien  // is an Objective-C conversion.
107789857Sobrien  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1078130561Sobrien      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
107989857Sobrien                              IncompatibleObjC)) {
108089857Sobrien    // We always complain about this conversion.
108189857Sobrien    IncompatibleObjC = true;
108289857Sobrien    ConvertedType = ToType;
108389857Sobrien    return true;
108489857Sobrien  }
1085130561Sobrien  // If we have pointers to functions or blocks, check whether the only
108689857Sobrien  // differences in the argument and result types are in Objective-C
108789857Sobrien  // pointer conversions. If so, we permit the conversion (but
108889857Sobrien  // complain about it).
108989857Sobrien  const FunctionProtoType *FromFunctionType
1090130561Sobrien    = FromPointeeType->getAs<FunctionProtoType>();
109189857Sobrien  const FunctionProtoType *ToFunctionType
109289857Sobrien    = ToPointeeType->getAs<FunctionProtoType>();
1093130561Sobrien  if (FromFunctionType && ToFunctionType) {
109489857Sobrien    // If the function types are exactly the same, this isn't an
109589857Sobrien    // Objective-C pointer conversion.
109689857Sobrien    if (Context.getCanonicalType(FromPointeeType)
109789857Sobrien          == Context.getCanonicalType(ToPointeeType))
109889857Sobrien      return false;
109989857Sobrien
1100130561Sobrien    // Perform the quick checks that will tell us whether these
110189857Sobrien    // function types are obviously different.
110289857Sobrien    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
110399461Sobrien        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
110489857Sobrien        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1105130561Sobrien      return false;
110689857Sobrien
110789857Sobrien    bool HasObjCConversion = false;
1108130561Sobrien    if (Context.getCanonicalType(FromFunctionType->getResultType())
110989857Sobrien          == Context.getCanonicalType(ToFunctionType->getResultType())) {
111089857Sobrien      // Okay, the types match exactly. Nothing to do.
111189857Sobrien    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
111289857Sobrien                                       ToFunctionType->getResultType(),
111389857Sobrien                                       ConvertedType, IncompatibleObjC)) {
111489857Sobrien      // Okay, we have an Objective-C pointer conversion.
1115130561Sobrien      HasObjCConversion = true;
111689857Sobrien    } else {
111789857Sobrien      // Function types are too different. Abort.
111899461Sobrien      return false;
111989857Sobrien    }
1120130561Sobrien
112189857Sobrien    // Check argument types.
112289857Sobrien    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1123130561Sobrien         ArgIdx != NumArgs; ++ArgIdx) {
112489857Sobrien      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
112589857Sobrien      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
112689857Sobrien      if (Context.getCanonicalType(FromArgType)
112789857Sobrien            == Context.getCanonicalType(ToArgType)) {
112889857Sobrien        // Okay, the types match exactly. Nothing to do.
112989857Sobrien      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1130130561Sobrien                                         ConvertedType, IncompatibleObjC)) {
113189857Sobrien        // Okay, we have an Objective-C pointer conversion.
113289857Sobrien        HasObjCConversion = true;
113399461Sobrien      } else {
113489857Sobrien        // Argument types are too different. Abort.
1135130561Sobrien        return false;
113689857Sobrien      }
113789857Sobrien    }
1138130561Sobrien
113989857Sobrien    if (HasObjCConversion) {
114089857Sobrien      // We had an Objective-C conversion. Allow this pointer
114189857Sobrien      // conversion, but complain about it.
114289857Sobrien      ConvertedType = ToType;
114399461Sobrien      IncompatibleObjC = true;
114499461Sobrien      return true;
1145130561Sobrien    }
114689857Sobrien  }
114789857Sobrien
114899461Sobrien  return false;
114989857Sobrien}
1150130561Sobrien
115189857Sobrien/// CheckPointerConversion - Check the pointer conversion from the
115299461Sobrien/// expression From to the type ToType. This routine checks for
1153130561Sobrien/// ambiguous or inaccessible derived-to-base pointer
115489857Sobrien/// conversions for which IsPointerConversion has already returned
115589857Sobrien/// true. It returns true and produces a diagnostic if there was an
115689857Sobrien/// error, or returns false otherwise.
115789857Sobrienbool Sema::CheckPointerConversion(Expr *From, QualType ToType,
115889857Sobrien                                  CastExpr::CastKind &Kind,
115989857Sobrien                                  bool IgnoreBaseAccess) {
1160130561Sobrien  QualType FromType = From->getType();
116189857Sobrien
116289857Sobrien  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
116399461Sobrien    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
116489857Sobrien      QualType FromPointeeType = FromPtrType->getPointeeType(),
1165130561Sobrien               ToPointeeType   = ToPtrType->getPointeeType();
116689857Sobrien
116789857Sobrien      if (FromPointeeType->isRecordType() &&
1168130561Sobrien          ToPointeeType->isRecordType()) {
116989857Sobrien        // We must have a derived-to-base conversion. Check an
117089857Sobrien        // ambiguous or inaccessible conversion.
117189857Sobrien        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
117289857Sobrien                                         From->getExprLoc(),
117389857Sobrien                                         From->getSourceRange(),
117489857Sobrien                                         IgnoreBaseAccess))
1175130561Sobrien          return true;
117689857Sobrien
117789857Sobrien        // The conversion was successful.
117899461Sobrien        Kind = CastExpr::CK_DerivedToBase;
117989857Sobrien      }
1180130561Sobrien    }
118189857Sobrien  if (const ObjCObjectPointerType *FromPtrType =
118289857Sobrien        FromType->getAs<ObjCObjectPointerType>())
1183130561Sobrien    if (const ObjCObjectPointerType *ToPtrType =
118489857Sobrien          ToType->getAs<ObjCObjectPointerType>()) {
118589857Sobrien      // Objective-C++ conversions are always okay.
118689857Sobrien      // FIXME: We should have a different class of conversions for the
118789857Sobrien      // Objective-C++ implicit conversions.
118889857Sobrien      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
118989857Sobrien        return false;
1190130561Sobrien
119189857Sobrien  }
119289857Sobrien  return false;
119399461Sobrien}
119489857Sobrien
1195130561Sobrien/// IsMemberPointerConversion - Determines whether the conversion of the
119689857Sobrien/// expression From, which has the (possibly adjusted) type FromType, can be
119789857Sobrien/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1198130561Sobrien/// If so, returns true and places the converted type (that might differ from
119989857Sobrien/// ToType in its cv-qualifiers at some level) into ConvertedType.
120089857Sobrienbool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
120189857Sobrien                                     QualType ToType,
1202218822Sdim                                     bool InOverloadResolution,
120389857Sobrien                                     QualType &ConvertedType) {
120489857Sobrien  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
120589857Sobrien  if (!ToTypePtr)
1206130561Sobrien    return false;
120789857Sobrien
120889857Sobrien  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
120999461Sobrien  if (From->isNullPointerConstant(Context,
121089857Sobrien                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1211130561Sobrien                                        : Expr::NPC_ValueDependentIsNull)) {
121289857Sobrien    ConvertedType = ToType;
121389857Sobrien    return true;
1214130561Sobrien  }
121589857Sobrien
121689857Sobrien  // Otherwise, both types have to be member pointers.
121789857Sobrien  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
121889857Sobrien  if (!FromTypePtr)
121989857Sobrien    return false;
122089857Sobrien
122189857Sobrien  // A pointer to member of B can be converted to a pointer to member of D,
1222130561Sobrien  // where D is derived from B (C++ 4.11p2).
122389857Sobrien  QualType FromClass(FromTypePtr->getClass(), 0);
122489857Sobrien  QualType ToClass(ToTypePtr->getClass(), 0);
122599461Sobrien  // FIXME: What happens when these are dependent? Is this function even called?
122689857Sobrien
1227130561Sobrien  if (IsDerivedFrom(ToClass, FromClass)) {
122889857Sobrien    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
122989857Sobrien                                                 ToClass.getTypePtr());
1230130561Sobrien    return true;
123189857Sobrien  }
1232130561Sobrien
1233130561Sobrien  return false;
1234130561Sobrien}
1235130561Sobrien
1236130561Sobrien/// CheckMemberPointerConversion - Check the member pointer conversion from the
1237130561Sobrien/// expression From to the type ToType. This routine checks for ambiguous or
1238130561Sobrien/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1239130561Sobrien/// for which IsMemberPointerConversion has already returned true. It returns
1240130561Sobrien/// true and produces a diagnostic if there was an error, or returns false
1241130561Sobrien/// otherwise.
1242130561Sobrienbool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1243130561Sobrien                                        CastExpr::CastKind &Kind,
1244130561Sobrien                                        bool IgnoreBaseAccess) {
1245130561Sobrien  (void)IgnoreBaseAccess;
1246130561Sobrien  QualType FromType = From->getType();
1247130561Sobrien  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1248130561Sobrien  if (!FromPtrType) {
1249130561Sobrien    // This must be a null pointer to member pointer conversion
1250130561Sobrien    assert(From->isNullPointerConstant(Context,
1251130561Sobrien                                       Expr::NPC_ValueDependentIsNull) &&
1252130561Sobrien           "Expr must be null pointer constant!");
1253130561Sobrien    Kind = CastExpr::CK_NullToMemberPointer;
1254130561Sobrien    return false;
1255130561Sobrien  }
1256130561Sobrien
1257130561Sobrien  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1258130561Sobrien  assert(ToPtrType && "No member pointer cast has a target type "
1259130561Sobrien                      "that is not a member pointer.");
1260130561Sobrien
1261130561Sobrien  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1262130561Sobrien  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1263130561Sobrien
1264130561Sobrien  // FIXME: What about dependent types?
1265130561Sobrien  assert(FromClass->isRecordType() && "Pointer into non-class.");
1266130561Sobrien  assert(ToClass->isRecordType() && "Pointer into non-class.");
1267130561Sobrien
1268130561Sobrien  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1269130561Sobrien                     /*DetectVirtual=*/true);
1270130561Sobrien  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1271130561Sobrien  assert(DerivationOkay &&
1272130561Sobrien         "Should not have been called if derivation isn't OK.");
1273130561Sobrien  (void)DerivationOkay;
1274130561Sobrien
1275130561Sobrien  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1276130561Sobrien                                  getUnqualifiedType())) {
1277130561Sobrien    // Derivation is ambiguous. Redo the check to find the exact paths.
1278130561Sobrien    Paths.clear();
1279130561Sobrien    Paths.setRecordingPaths(true);
1280130561Sobrien    bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1281130561Sobrien    assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1282130561Sobrien    (void)StillOkay;
1283130561Sobrien
1284130561Sobrien    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1285130561Sobrien    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1286130561Sobrien      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1287130561Sobrien    return true;
1288130561Sobrien  }
1289130561Sobrien
1290130561Sobrien  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1291130561Sobrien    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1292130561Sobrien      << FromClass << ToClass << QualType(VBase, 0)
1293130561Sobrien      << From->getSourceRange();
1294130561Sobrien    return true;
1295130561Sobrien  }
1296130561Sobrien
1297130561Sobrien  // Must be a base to derived member conversion.
1298130561Sobrien  Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1299130561Sobrien  return false;
1300130561Sobrien}
1301130561Sobrien
1302130561Sobrien/// IsQualificationConversion - Determines whether the conversion from
1303130561Sobrien/// an rvalue of type FromType to ToType is a qualification conversion
1304130561Sobrien/// (C++ 4.4).
1305130561Sobrienbool
1306130561SobrienSema::IsQualificationConversion(QualType FromType, QualType ToType) {
1307130561Sobrien  FromType = Context.getCanonicalType(FromType);
1308130561Sobrien  ToType = Context.getCanonicalType(ToType);
1309130561Sobrien
1310130561Sobrien  // If FromType and ToType are the same type, this is not a
1311130561Sobrien  // qualification conversion.
1312130561Sobrien  if (FromType == ToType)
1313130561Sobrien    return false;
1314130561Sobrien
1315130561Sobrien  // (C++ 4.4p4):
1316130561Sobrien  //   A conversion can add cv-qualifiers at levels other than the first
1317130561Sobrien  //   in multi-level pointers, subject to the following rules: [...]
1318130561Sobrien  bool PreviousToQualsIncludeConst = true;
1319130561Sobrien  bool UnwrappedAnyPointer = false;
1320130561Sobrien  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1321130561Sobrien    // Within each iteration of the loop, we check the qualifiers to
1322130561Sobrien    // determine if this still looks like a qualification
1323130561Sobrien    // conversion. Then, if all is well, we unwrap one more level of
1324130561Sobrien    // pointers or pointers-to-members and do it all again
1325130561Sobrien    // until there are no more pointers or pointers-to-members left to
1326130561Sobrien    // unwrap.
1327130561Sobrien    UnwrappedAnyPointer = true;
1328130561Sobrien
1329130561Sobrien    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1330130561Sobrien    //      2,j, and similarly for volatile.
1331130561Sobrien    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1332130561Sobrien      return false;
1333130561Sobrien
1334130561Sobrien    //   -- if the cv 1,j and cv 2,j are different, then const is in
1335130561Sobrien    //      every cv for 0 < k < j.
1336130561Sobrien    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1337130561Sobrien        && !PreviousToQualsIncludeConst)
1338130561Sobrien      return false;
1339130561Sobrien
1340130561Sobrien    // Keep track of whether all prior cv-qualifiers in the "to" type
1341130561Sobrien    // include const.
1342130561Sobrien    PreviousToQualsIncludeConst
1343130561Sobrien      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1344130561Sobrien  }
1345130561Sobrien
1346130561Sobrien  // We are left with FromType and ToType being the pointee types
1347130561Sobrien  // after unwrapping the original FromType and ToType the same number
1348130561Sobrien  // of types. If we unwrapped any pointers, and if FromType and
1349130561Sobrien  // ToType have the same unqualified type (since we checked
1350130561Sobrien  // qualifiers above), then this is a qualification conversion.
1351130561Sobrien  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
1352130561Sobrien}
1353130561Sobrien
1354130561Sobrien/// \brief Given a function template or function, extract the function template
1355130561Sobrien/// declaration (if any) and the underlying function declaration.
1356130561Sobrientemplate<typename T>
1357130561Sobrienstatic void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1358130561Sobrien                                   FunctionTemplateDecl *&FunctionTemplate) {
1359130561Sobrien  FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1360130561Sobrien  if (FunctionTemplate)
1361130561Sobrien    Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1362130561Sobrien  else
1363130561Sobrien    Function = cast<T>(Orig);
1364130561Sobrien}
1365130561Sobrien
1366130561Sobrien/// Determines whether there is a user-defined conversion sequence
1367130561Sobrien/// (C++ [over.ics.user]) that converts expression From to the type
1368130561Sobrien/// ToType. If such a conversion exists, User will contain the
1369130561Sobrien/// user-defined conversion sequence that performs such a conversion
1370130561Sobrien/// and this routine will return true. Otherwise, this routine returns
1371130561Sobrien/// false and User is unspecified.
1372130561Sobrien///
1373130561Sobrien/// \param AllowConversionFunctions true if the conversion should
1374130561Sobrien/// consider conversion functions at all. If false, only constructors
1375130561Sobrien/// will be considered.
1376130561Sobrien///
1377130561Sobrien/// \param AllowExplicit  true if the conversion should consider C++0x
1378130561Sobrien/// "explicit" conversion functions as well as non-explicit conversion
1379130561Sobrien/// functions (C++0x [class.conv.fct]p2).
1380130561Sobrien///
1381130561Sobrien/// \param ForceRValue  true if the expression should be treated as an rvalue
1382130561Sobrien/// for overload resolution.
1383130561Sobrien/// \param UserCast true if looking for user defined conversion for a static
1384130561Sobrien/// cast.
1385130561SobrienSema::OverloadingResult Sema::IsUserDefinedConversion(
1386130561Sobrien                                   Expr *From, QualType ToType,
1387130561Sobrien                                   UserDefinedConversionSequence& User,
1388130561Sobrien                                   OverloadCandidateSet& CandidateSet,
1389130561Sobrien                                   bool AllowConversionFunctions,
1390130561Sobrien                                   bool AllowExplicit, bool ForceRValue,
1391130561Sobrien                                   bool UserCast) {
1392130561Sobrien  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1393130561Sobrien    if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1394130561Sobrien      // We're not going to find any constructors.
1395130561Sobrien    } else if (CXXRecordDecl *ToRecordDecl
1396130561Sobrien                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1397130561Sobrien      // C++ [over.match.ctor]p1:
1398130561Sobrien      //   When objects of class type are direct-initialized (8.5), or
1399130561Sobrien      //   copy-initialized from an expression of the same or a
1400130561Sobrien      //   derived class type (8.5), overload resolution selects the
1401130561Sobrien      //   constructor. [...] For copy-initialization, the candidate
1402130561Sobrien      //   functions are all the converting constructors (12.3.1) of
1403130561Sobrien      //   that class. The argument list is the expression-list within
1404130561Sobrien      //   the parentheses of the initializer.
1405130561Sobrien      bool SuppressUserConversions = !UserCast;
1406130561Sobrien      if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1407130561Sobrien          IsDerivedFrom(From->getType(), ToType)) {
1408130561Sobrien        SuppressUserConversions = false;
1409130561Sobrien        AllowConversionFunctions = false;
1410130561Sobrien      }
1411130561Sobrien
1412130561Sobrien      DeclarationName ConstructorName
1413130561Sobrien        = Context.DeclarationNames.getCXXConstructorName(
1414130561Sobrien                          Context.getCanonicalType(ToType).getUnqualifiedType());
1415130561Sobrien      DeclContext::lookup_iterator Con, ConEnd;
1416130561Sobrien      for (llvm::tie(Con, ConEnd)
1417130561Sobrien             = ToRecordDecl->lookup(ConstructorName);
1418130561Sobrien           Con != ConEnd; ++Con) {
1419130561Sobrien        // Find the constructor (which may be a template).
1420130561Sobrien        CXXConstructorDecl *Constructor = 0;
1421130561Sobrien        FunctionTemplateDecl *ConstructorTmpl
1422130561Sobrien          = dyn_cast<FunctionTemplateDecl>(*Con);
1423130561Sobrien        if (ConstructorTmpl)
1424130561Sobrien          Constructor
1425130561Sobrien            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1426130561Sobrien        else
1427130561Sobrien          Constructor = cast<CXXConstructorDecl>(*Con);
1428130561Sobrien
1429130561Sobrien        if (!Constructor->isInvalidDecl() &&
1430130561Sobrien            Constructor->isConvertingConstructor(AllowExplicit)) {
1431130561Sobrien          if (ConstructorTmpl)
1432130561Sobrien            AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1433130561Sobrien                                         1, CandidateSet,
1434130561Sobrien                                         SuppressUserConversions, ForceRValue);
1435130561Sobrien          else
1436130561Sobrien            // Allow one user-defined conversion when user specifies a
1437130561Sobrien            // From->ToType conversion via an static cast (c-style, etc).
1438130561Sobrien            AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1439130561Sobrien                                 SuppressUserConversions, ForceRValue);
1440130561Sobrien        }
1441130561Sobrien      }
1442130561Sobrien    }
1443130561Sobrien  }
1444130561Sobrien
1445130561Sobrien  if (!AllowConversionFunctions) {
1446130561Sobrien    // Don't allow any conversion functions to enter the overload set.
1447130561Sobrien  } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1448130561Sobrien                                 PDiag(0)
1449130561Sobrien                                   << From->getSourceRange())) {
1450130561Sobrien    // No conversion functions from incomplete types.
1451130561Sobrien  } else if (const RecordType *FromRecordType
1452130561Sobrien               = From->getType()->getAs<RecordType>()) {
1453130561Sobrien    if (CXXRecordDecl *FromRecordDecl
1454130561Sobrien         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1455130561Sobrien      // Add all of the conversion functions as candidates.
1456130561Sobrien      OverloadedFunctionDecl *Conversions
1457130561Sobrien        = FromRecordDecl->getVisibleConversionFunctions();
1458130561Sobrien      for (OverloadedFunctionDecl::function_iterator Func
1459130561Sobrien             = Conversions->function_begin();
1460130561Sobrien           Func != Conversions->function_end(); ++Func) {
1461130561Sobrien        CXXConversionDecl *Conv;
1462130561Sobrien        FunctionTemplateDecl *ConvTemplate;
1463130561Sobrien        GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1464130561Sobrien        if (ConvTemplate)
1465130561Sobrien          Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1466130561Sobrien        else
1467130561Sobrien          Conv = dyn_cast<CXXConversionDecl>(*Func);
1468130561Sobrien
1469130561Sobrien        if (AllowExplicit || !Conv->isExplicit()) {
1470130561Sobrien          if (ConvTemplate)
1471130561Sobrien            AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1472130561Sobrien                                           CandidateSet);
1473130561Sobrien          else
1474130561Sobrien            AddConversionCandidate(Conv, From, ToType, CandidateSet);
1475130561Sobrien        }
1476130561Sobrien      }
1477130561Sobrien    }
1478130561Sobrien  }
1479130561Sobrien
1480130561Sobrien  OverloadCandidateSet::iterator Best;
1481130561Sobrien  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1482130561Sobrien    case OR_Success:
1483130561Sobrien      // Record the standard conversion we used and the conversion function.
1484130561Sobrien      if (CXXConstructorDecl *Constructor
1485130561Sobrien            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1486130561Sobrien        // C++ [over.ics.user]p1:
1487130561Sobrien        //   If the user-defined conversion is specified by a
1488130561Sobrien        //   constructor (12.3.1), the initial standard conversion
1489130561Sobrien        //   sequence converts the source type to the type required by
1490130561Sobrien        //   the argument of the constructor.
1491130561Sobrien        //
1492130561Sobrien        QualType ThisType = Constructor->getThisType(Context);
1493130561Sobrien        if (Best->Conversions[0].ConversionKind ==
1494130561Sobrien            ImplicitConversionSequence::EllipsisConversion)
1495130561Sobrien          User.EllipsisConversion = true;
1496130561Sobrien        else {
1497130561Sobrien          User.Before = Best->Conversions[0].Standard;
1498130561Sobrien          User.EllipsisConversion = false;
1499130561Sobrien        }
1500130561Sobrien        User.ConversionFunction = Constructor;
1501130561Sobrien        User.After.setAsIdentityConversion();
1502130561Sobrien        User.After.FromTypePtr
1503130561Sobrien          = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
1504130561Sobrien        User.After.ToTypePtr = ToType.getAsOpaquePtr();
1505130561Sobrien        return OR_Success;
1506130561Sobrien      } else if (CXXConversionDecl *Conversion
1507130561Sobrien                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1508130561Sobrien        // C++ [over.ics.user]p1:
1509130561Sobrien        //
1510130561Sobrien        //   [...] If the user-defined conversion is specified by a
1511130561Sobrien        //   conversion function (12.3.2), the initial standard
1512130561Sobrien        //   conversion sequence converts the source type to the
1513130561Sobrien        //   implicit object parameter of the conversion function.
1514130561Sobrien        User.Before = Best->Conversions[0].Standard;
1515130561Sobrien        User.ConversionFunction = Conversion;
1516130561Sobrien        User.EllipsisConversion = false;
1517130561Sobrien
1518130561Sobrien        // C++ [over.ics.user]p2:
1519130561Sobrien        //   The second standard conversion sequence converts the
1520130561Sobrien        //   result of the user-defined conversion to the target type
1521130561Sobrien        //   for the sequence. Since an implicit conversion sequence
1522130561Sobrien        //   is an initialization, the special rules for
1523130561Sobrien        //   initialization by user-defined conversion apply when
1524130561Sobrien        //   selecting the best user-defined conversion for a
1525130561Sobrien        //   user-defined conversion sequence (see 13.3.3 and
1526130561Sobrien        //   13.3.3.1).
1527130561Sobrien        User.After = Best->FinalConversion;
1528130561Sobrien        return OR_Success;
1529130561Sobrien      } else {
1530130561Sobrien        assert(false && "Not a constructor or conversion function?");
1531130561Sobrien        return OR_No_Viable_Function;
1532130561Sobrien      }
1533130561Sobrien
1534130561Sobrien    case OR_No_Viable_Function:
1535130561Sobrien      return OR_No_Viable_Function;
1536130561Sobrien    case OR_Deleted:
1537130561Sobrien      // No conversion here! We're done.
1538130561Sobrien      return OR_Deleted;
1539130561Sobrien
1540130561Sobrien    case OR_Ambiguous:
1541130561Sobrien      return OR_Ambiguous;
1542130561Sobrien    }
1543130561Sobrien
1544130561Sobrien  return OR_No_Viable_Function;
1545130561Sobrien}
1546130561Sobrien
1547130561Sobrienbool
1548130561SobrienSema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1549130561Sobrien  ImplicitConversionSequence ICS;
1550130561Sobrien  OverloadCandidateSet CandidateSet;
1551130561Sobrien  OverloadingResult OvResult =
1552130561Sobrien    IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1553130561Sobrien                            CandidateSet, true, false, false);
1554130561Sobrien  if (OvResult != OR_Ambiguous)
1555130561Sobrien    return false;
1556130561Sobrien  Diag(From->getSourceRange().getBegin(),
1557130561Sobrien       diag::err_typecheck_ambiguous_condition)
1558130561Sobrien  << From->getType() << ToType << From->getSourceRange();
1559130561Sobrien    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1560130561Sobrien  return true;
1561130561Sobrien}
1562130561Sobrien
1563130561Sobrien/// CompareImplicitConversionSequences - Compare two implicit
1564130561Sobrien/// conversion sequences to determine whether one is better than the
1565130561Sobrien/// other or if they are indistinguishable (C++ 13.3.3.2).
1566130561SobrienImplicitConversionSequence::CompareKind
1567130561SobrienSema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1568130561Sobrien                                         const ImplicitConversionSequence& ICS2)
1569130561Sobrien{
1570130561Sobrien  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1571130561Sobrien  // conversion sequences (as defined in 13.3.3.1)
1572130561Sobrien  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1573130561Sobrien  //      conversion sequence than a user-defined conversion sequence or
1574130561Sobrien  //      an ellipsis conversion sequence, and
1575130561Sobrien  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1576130561Sobrien  //      conversion sequence than an ellipsis conversion sequence
1577130561Sobrien  //      (13.3.3.1.3).
1578130561Sobrien  //
1579130561Sobrien  if (ICS1.ConversionKind < ICS2.ConversionKind)
1580130561Sobrien    return ImplicitConversionSequence::Better;
1581130561Sobrien  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1582130561Sobrien    return ImplicitConversionSequence::Worse;
1583130561Sobrien
1584130561Sobrien  // Two implicit conversion sequences of the same form are
1585130561Sobrien  // indistinguishable conversion sequences unless one of the
1586130561Sobrien  // following rules apply: (C++ 13.3.3.2p3):
1587130561Sobrien  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1588130561Sobrien    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1589130561Sobrien  else if (ICS1.ConversionKind ==
1590130561Sobrien             ImplicitConversionSequence::UserDefinedConversion) {
1591130561Sobrien    // User-defined conversion sequence U1 is a better conversion
1592130561Sobrien    // sequence than another user-defined conversion sequence U2 if
1593130561Sobrien    // they contain the same user-defined conversion function or
1594130561Sobrien    // constructor and if the second standard conversion sequence of
1595130561Sobrien    // U1 is better than the second standard conversion sequence of
1596130561Sobrien    // U2 (C++ 13.3.3.2p3).
1597130561Sobrien    if (ICS1.UserDefined.ConversionFunction ==
1598130561Sobrien          ICS2.UserDefined.ConversionFunction)
1599130561Sobrien      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1600130561Sobrien                                                ICS2.UserDefined.After);
1601130561Sobrien  }
1602130561Sobrien
1603130561Sobrien  return ImplicitConversionSequence::Indistinguishable;
1604130561Sobrien}
1605130561Sobrien
1606130561Sobrien/// CompareStandardConversionSequences - Compare two standard
1607130561Sobrien/// conversion sequences to determine whether one is better than the
1608130561Sobrien/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1609130561SobrienImplicitConversionSequence::CompareKind
1610130561SobrienSema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1611130561Sobrien                                         const StandardConversionSequence& SCS2)
1612130561Sobrien{
1613130561Sobrien  // Standard conversion sequence S1 is a better conversion sequence
1614130561Sobrien  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1615130561Sobrien
1616130561Sobrien  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1617130561Sobrien  //     sequences in the canonical form defined by 13.3.3.1.1,
1618130561Sobrien  //     excluding any Lvalue Transformation; the identity conversion
1619130561Sobrien  //     sequence is considered to be a subsequence of any
1620130561Sobrien  //     non-identity conversion sequence) or, if not that,
1621130561Sobrien  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1622130561Sobrien    // Neither is a proper subsequence of the other. Do nothing.
1623130561Sobrien    ;
1624130561Sobrien  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1625130561Sobrien           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1626130561Sobrien           (SCS1.Second == ICK_Identity &&
1627130561Sobrien            SCS1.Third == ICK_Identity))
1628130561Sobrien    // SCS1 is a proper subsequence of SCS2.
1629130561Sobrien    return ImplicitConversionSequence::Better;
1630130561Sobrien  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1631130561Sobrien           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1632130561Sobrien           (SCS2.Second == ICK_Identity &&
1633130561Sobrien            SCS2.Third == ICK_Identity))
1634130561Sobrien    // SCS2 is a proper subsequence of SCS1.
1635130561Sobrien    return ImplicitConversionSequence::Worse;
1636130561Sobrien
1637130561Sobrien  //  -- the rank of S1 is better than the rank of S2 (by the rules
1638130561Sobrien  //     defined below), or, if not that,
1639130561Sobrien  ImplicitConversionRank Rank1 = SCS1.getRank();
1640130561Sobrien  ImplicitConversionRank Rank2 = SCS2.getRank();
1641130561Sobrien  if (Rank1 < Rank2)
1642130561Sobrien    return ImplicitConversionSequence::Better;
1643130561Sobrien  else if (Rank2 < Rank1)
1644130561Sobrien    return ImplicitConversionSequence::Worse;
1645130561Sobrien
1646130561Sobrien  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1647130561Sobrien  // are indistinguishable unless one of the following rules
1648130561Sobrien  // applies:
1649130561Sobrien
1650130561Sobrien  //   A conversion that is not a conversion of a pointer, or
1651130561Sobrien  //   pointer to member, to bool is better than another conversion
1652130561Sobrien  //   that is such a conversion.
1653130561Sobrien  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1654130561Sobrien    return SCS2.isPointerConversionToBool()
1655130561Sobrien             ? ImplicitConversionSequence::Better
1656130561Sobrien             : ImplicitConversionSequence::Worse;
1657130561Sobrien
1658130561Sobrien  // C++ [over.ics.rank]p4b2:
1659130561Sobrien  //
1660130561Sobrien  //   If class B is derived directly or indirectly from class A,
1661130561Sobrien  //   conversion of B* to A* is better than conversion of B* to
1662130561Sobrien  //   void*, and conversion of A* to void* is better than conversion
1663130561Sobrien  //   of B* to void*.
1664130561Sobrien  bool SCS1ConvertsToVoid
1665130561Sobrien    = SCS1.isPointerConversionToVoidPointer(Context);
1666130561Sobrien  bool SCS2ConvertsToVoid
1667130561Sobrien    = SCS2.isPointerConversionToVoidPointer(Context);
1668130561Sobrien  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1669130561Sobrien    // Exactly one of the conversion sequences is a conversion to
1670130561Sobrien    // a void pointer; it's the worse conversion.
1671130561Sobrien    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1672130561Sobrien                              : ImplicitConversionSequence::Worse;
1673130561Sobrien  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1674130561Sobrien    // Neither conversion sequence converts to a void pointer; compare
1675130561Sobrien    // their derived-to-base conversions.
1676130561Sobrien    if (ImplicitConversionSequence::CompareKind DerivedCK
1677130561Sobrien          = CompareDerivedToBaseConversions(SCS1, SCS2))
1678130561Sobrien      return DerivedCK;
1679130561Sobrien  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1680130561Sobrien    // Both conversion sequences are conversions to void
1681130561Sobrien    // pointers. Compare the source types to determine if there's an
1682130561Sobrien    // inheritance relationship in their sources.
1683130561Sobrien    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1684130561Sobrien    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1685130561Sobrien
1686130561Sobrien    // Adjust the types we're converting from via the array-to-pointer
1687130561Sobrien    // conversion, if we need to.
1688130561Sobrien    if (SCS1.First == ICK_Array_To_Pointer)
1689130561Sobrien      FromType1 = Context.getArrayDecayedType(FromType1);
1690130561Sobrien    if (SCS2.First == ICK_Array_To_Pointer)
1691130561Sobrien      FromType2 = Context.getArrayDecayedType(FromType2);
1692130561Sobrien
1693130561Sobrien    QualType FromPointee1
1694130561Sobrien      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1695130561Sobrien    QualType FromPointee2
1696130561Sobrien      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1697130561Sobrien
1698130561Sobrien    if (IsDerivedFrom(FromPointee2, FromPointee1))
1699130561Sobrien      return ImplicitConversionSequence::Better;
1700130561Sobrien    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1701130561Sobrien      return ImplicitConversionSequence::Worse;
1702130561Sobrien
1703130561Sobrien    // Objective-C++: If one interface is more specific than the
1704130561Sobrien    // other, it is the better one.
1705130561Sobrien    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1706130561Sobrien    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1707130561Sobrien    if (FromIface1 && FromIface1) {
1708130561Sobrien      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1709130561Sobrien        return ImplicitConversionSequence::Better;
1710130561Sobrien      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1711130561Sobrien        return ImplicitConversionSequence::Worse;
1712130561Sobrien    }
1713130561Sobrien  }
1714130561Sobrien
1715130561Sobrien  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1716130561Sobrien  // bullet 3).
1717130561Sobrien  if (ImplicitConversionSequence::CompareKind QualCK
1718130561Sobrien        = CompareQualificationConversions(SCS1, SCS2))
1719130561Sobrien    return QualCK;
1720130561Sobrien
1721130561Sobrien  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1722130561Sobrien    // C++0x [over.ics.rank]p3b4:
1723130561Sobrien    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1724130561Sobrien    //      implicit object parameter of a non-static member function declared
1725130561Sobrien    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1726130561Sobrien    //      rvalue and S2 binds an lvalue reference.
1727130561Sobrien    // FIXME: We don't know if we're dealing with the implicit object parameter,
1728130561Sobrien    // or if the member function in this case has a ref qualifier.
1729130561Sobrien    // (Of course, we don't have ref qualifiers yet.)
1730130561Sobrien    if (SCS1.RRefBinding != SCS2.RRefBinding)
1731130561Sobrien      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1732130561Sobrien                              : ImplicitConversionSequence::Worse;
1733130561Sobrien
1734130561Sobrien    // C++ [over.ics.rank]p3b4:
1735130561Sobrien    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1736130561Sobrien    //      which the references refer are the same type except for
1737130561Sobrien    //      top-level cv-qualifiers, and the type to which the reference
1738130561Sobrien    //      initialized by S2 refers is more cv-qualified than the type
1739130561Sobrien    //      to which the reference initialized by S1 refers.
1740130561Sobrien    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1741130561Sobrien    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1742130561Sobrien    T1 = Context.getCanonicalType(T1);
1743130561Sobrien    T2 = Context.getCanonicalType(T2);
1744130561Sobrien    if (Context.hasSameUnqualifiedType(T1, T2)) {
1745130561Sobrien      if (T2.isMoreQualifiedThan(T1))
1746130561Sobrien        return ImplicitConversionSequence::Better;
1747130561Sobrien      else if (T1.isMoreQualifiedThan(T2))
1748130561Sobrien        return ImplicitConversionSequence::Worse;
1749130561Sobrien    }
1750130561Sobrien  }
1751130561Sobrien
1752130561Sobrien  return ImplicitConversionSequence::Indistinguishable;
1753130561Sobrien}
1754130561Sobrien
1755130561Sobrien/// CompareQualificationConversions - Compares two standard conversion
1756130561Sobrien/// sequences to determine whether they can be ranked based on their
1757130561Sobrien/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1758130561SobrienImplicitConversionSequence::CompareKind
1759130561SobrienSema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1760130561Sobrien                                      const StandardConversionSequence& SCS2) {
1761130561Sobrien  // C++ 13.3.3.2p3:
1762130561Sobrien  //  -- S1 and S2 differ only in their qualification conversion and
1763130561Sobrien  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1764130561Sobrien  //     cv-qualification signature of type T1 is a proper subset of
1765130561Sobrien  //     the cv-qualification signature of type T2, and S1 is not the
1766130561Sobrien  //     deprecated string literal array-to-pointer conversion (4.2).
1767130561Sobrien  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1768130561Sobrien      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1769130561Sobrien    return ImplicitConversionSequence::Indistinguishable;
1770130561Sobrien
1771130561Sobrien  // FIXME: the example in the standard doesn't use a qualification
1772130561Sobrien  // conversion (!)
1773130561Sobrien  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1774130561Sobrien  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1775130561Sobrien  T1 = Context.getCanonicalType(T1);
1776130561Sobrien  T2 = Context.getCanonicalType(T2);
1777130561Sobrien
1778130561Sobrien  // If the types are the same, we won't learn anything by unwrapped
1779130561Sobrien  // them.
1780130561Sobrien  if (Context.hasSameUnqualifiedType(T1, T2))
1781130561Sobrien    return ImplicitConversionSequence::Indistinguishable;
1782130561Sobrien
1783130561Sobrien  ImplicitConversionSequence::CompareKind Result
1784130561Sobrien    = ImplicitConversionSequence::Indistinguishable;
1785130561Sobrien  while (UnwrapSimilarPointerTypes(T1, T2)) {
1786130561Sobrien    // Within each iteration of the loop, we check the qualifiers to
1787130561Sobrien    // determine if this still looks like a qualification
1788130561Sobrien    // conversion. Then, if all is well, we unwrap one more level of
1789130561Sobrien    // pointers or pointers-to-members and do it all again
1790130561Sobrien    // until there are no more pointers or pointers-to-members left
1791130561Sobrien    // to unwrap. This essentially mimics what
1792130561Sobrien    // IsQualificationConversion does, but here we're checking for a
1793130561Sobrien    // strict subset of qualifiers.
1794130561Sobrien    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1795130561Sobrien      // The qualifiers are the same, so this doesn't tell us anything
1796130561Sobrien      // about how the sequences rank.
1797130561Sobrien      ;
1798130561Sobrien    else if (T2.isMoreQualifiedThan(T1)) {
1799130561Sobrien      // T1 has fewer qualifiers, so it could be the better sequence.
1800130561Sobrien      if (Result == ImplicitConversionSequence::Worse)
1801130561Sobrien        // Neither has qualifiers that are a subset of the other's
1802130561Sobrien        // qualifiers.
1803130561Sobrien        return ImplicitConversionSequence::Indistinguishable;
1804130561Sobrien
1805130561Sobrien      Result = ImplicitConversionSequence::Better;
1806130561Sobrien    } else if (T1.isMoreQualifiedThan(T2)) {
1807130561Sobrien      // T2 has fewer qualifiers, so it could be the better sequence.
1808130561Sobrien      if (Result == ImplicitConversionSequence::Better)
1809130561Sobrien        // Neither has qualifiers that are a subset of the other's
1810130561Sobrien        // qualifiers.
1811130561Sobrien        return ImplicitConversionSequence::Indistinguishable;
1812130561Sobrien
1813130561Sobrien      Result = ImplicitConversionSequence::Worse;
1814130561Sobrien    } else {
1815130561Sobrien      // Qualifiers are disjoint.
1816130561Sobrien      return ImplicitConversionSequence::Indistinguishable;
1817130561Sobrien    }
1818130561Sobrien
1819130561Sobrien    // If the types after this point are equivalent, we're done.
1820130561Sobrien    if (Context.hasSameUnqualifiedType(T1, T2))
1821130561Sobrien      break;
1822130561Sobrien  }
1823130561Sobrien
1824130561Sobrien  // Check that the winning standard conversion sequence isn't using
1825130561Sobrien  // the deprecated string literal array to pointer conversion.
1826130561Sobrien  switch (Result) {
1827130561Sobrien  case ImplicitConversionSequence::Better:
1828130561Sobrien    if (SCS1.Deprecated)
1829130561Sobrien      Result = ImplicitConversionSequence::Indistinguishable;
1830130561Sobrien    break;
1831130561Sobrien
1832130561Sobrien  case ImplicitConversionSequence::Indistinguishable:
1833130561Sobrien    break;
1834130561Sobrien
1835130561Sobrien  case ImplicitConversionSequence::Worse:
1836130561Sobrien    if (SCS2.Deprecated)
1837130561Sobrien      Result = ImplicitConversionSequence::Indistinguishable;
1838130561Sobrien    break;
1839130561Sobrien  }
1840130561Sobrien
1841130561Sobrien  return Result;
184289857Sobrien}
184389857Sobrien
184489857Sobrien/// CompareDerivedToBaseConversions - Compares two standard conversion
184589857Sobrien/// sequences to determine whether they can be ranked based on their
184689857Sobrien/// various kinds of derived-to-base conversions (C++
1847130561Sobrien/// [over.ics.rank]p4b3).  As part of these checks, we also look at
184889857Sobrien/// conversions between Objective-C interface types.
184989857SobrienImplicitConversionSequence::CompareKind
185089857SobrienSema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
185189857Sobrien                                      const StandardConversionSequence& SCS2) {
1852130561Sobrien  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
185389857Sobrien  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
185489857Sobrien  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1855130561Sobrien  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
185689857Sobrien
185789857Sobrien  // Adjust the types we're converting from via the array-to-pointer
185889857Sobrien  // conversion, if we need to.
185989857Sobrien  if (SCS1.First == ICK_Array_To_Pointer)
186089857Sobrien    FromType1 = Context.getArrayDecayedType(FromType1);
186189857Sobrien  if (SCS2.First == ICK_Array_To_Pointer)
1862130561Sobrien    FromType2 = Context.getArrayDecayedType(FromType2);
186389857Sobrien
186489857Sobrien  // Canonicalize all of the types.
186589857Sobrien  FromType1 = Context.getCanonicalType(FromType1);
186689857Sobrien  ToType1 = Context.getCanonicalType(ToType1);
1867130561Sobrien  FromType2 = Context.getCanonicalType(FromType2);
186889857Sobrien  ToType2 = Context.getCanonicalType(ToType2);
186989857Sobrien
1870130561Sobrien  // C++ [over.ics.rank]p4b3:
187189857Sobrien  //
187289857Sobrien  //   If class B is derived directly or indirectly from class A and
187389857Sobrien  //   class C is derived directly or indirectly from B,
187489857Sobrien  //
187589857Sobrien  // For Objective-C, we let A, B, and C also be Objective-C
187689857Sobrien  // interfaces.
187789857Sobrien
1878130561Sobrien  // Compare based on pointer conversions.
187989857Sobrien  if (SCS1.Second == ICK_Pointer_Conversion &&
188089857Sobrien      SCS2.Second == ICK_Pointer_Conversion &&
188189857Sobrien      /*FIXME: Remove if Objective-C id conversions get their own rank*/
188289857Sobrien      FromType1->isPointerType() && FromType2->isPointerType() &&
188389857Sobrien      ToType1->isPointerType() && ToType2->isPointerType()) {
188489857Sobrien    QualType FromPointee1
188589857Sobrien      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
188689857Sobrien    QualType ToPointee1
188789857Sobrien      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
188889857Sobrien    QualType FromPointee2
188989857Sobrien      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
189089857Sobrien    QualType ToPointee2
189189857Sobrien      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
189289857Sobrien
189389857Sobrien    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1894130561Sobrien    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1895130561Sobrien    const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
189689857Sobrien    const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
1897130561Sobrien
189889857Sobrien    //   -- conversion of C* to B* is better than conversion of C* to A*,
189989857Sobrien    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
190089857Sobrien      if (IsDerivedFrom(ToPointee1, ToPointee2))
190189857Sobrien        return ImplicitConversionSequence::Better;
190289857Sobrien      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1903130561Sobrien        return ImplicitConversionSequence::Worse;
190489857Sobrien
190589857Sobrien      if (ToIface1 && ToIface2) {
1906130561Sobrien        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
190789857Sobrien          return ImplicitConversionSequence::Better;
1908130561Sobrien        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
190989857Sobrien          return ImplicitConversionSequence::Worse;
1910130561Sobrien      }
191189857Sobrien    }
1912130561Sobrien
191389857Sobrien    //   -- conversion of B* to A* is better than conversion of C* to A*,
1914130561Sobrien    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
191589857Sobrien      if (IsDerivedFrom(FromPointee2, FromPointee1))
1916130561Sobrien        return ImplicitConversionSequence::Better;
191789857Sobrien      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1918130561Sobrien        return ImplicitConversionSequence::Worse;
191989857Sobrien
1920130561Sobrien      if (FromIface1 && FromIface2) {
192189857Sobrien        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1922130561Sobrien          return ImplicitConversionSequence::Better;
192389857Sobrien        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1924130561Sobrien          return ImplicitConversionSequence::Worse;
192589857Sobrien      }
1926130561Sobrien    }
192789857Sobrien  }
1928130561Sobrien
192989857Sobrien  // Compare based on reference bindings.
1930130561Sobrien  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
193189857Sobrien      SCS1.Second == ICK_Derived_To_Base) {
1932130561Sobrien    //   -- binding of an expression of type C to a reference of type
193389857Sobrien    //      B& is better than binding an expression of type C to a
1934130561Sobrien    //      reference of type A&,
193589857Sobrien    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1936130561Sobrien        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
193789857Sobrien      if (IsDerivedFrom(ToType1, ToType2))
1938130561Sobrien        return ImplicitConversionSequence::Better;
193989857Sobrien      else if (IsDerivedFrom(ToType2, ToType1))
1940130561Sobrien        return ImplicitConversionSequence::Worse;
194189857Sobrien    }
1942130561Sobrien
194389857Sobrien    //   -- binding of an expression of type B to a reference of type
1944130561Sobrien    //      A& is better than binding an expression of type C to a
194589857Sobrien    //      reference of type A&,
1946130561Sobrien    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
194789857Sobrien        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
1948130561Sobrien      if (IsDerivedFrom(FromType2, FromType1))
194989857Sobrien        return ImplicitConversionSequence::Better;
1950130561Sobrien      else if (IsDerivedFrom(FromType1, FromType2))
195189857Sobrien        return ImplicitConversionSequence::Worse;
1952130561Sobrien    }
195389857Sobrien  }
1954130561Sobrien
195589857Sobrien  // Ranking of member-pointer types.
1956130561Sobrien  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
195789857Sobrien      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1958130561Sobrien      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
195989857Sobrien    const MemberPointerType * FromMemPointer1 =
1960130561Sobrien                                        FromType1->getAs<MemberPointerType>();
196189857Sobrien    const MemberPointerType * ToMemPointer1 =
1962130561Sobrien                                          ToType1->getAs<MemberPointerType>();
196389857Sobrien    const MemberPointerType * FromMemPointer2 =
1964130561Sobrien                                          FromType2->getAs<MemberPointerType>();
196589857Sobrien    const MemberPointerType * ToMemPointer2 =
1966130561Sobrien                                          ToType2->getAs<MemberPointerType>();
196789857Sobrien    const Type *FromPointeeType1 = FromMemPointer1->getClass();
1968130561Sobrien    const Type *ToPointeeType1 = ToMemPointer1->getClass();
196989857Sobrien    const Type *FromPointeeType2 = FromMemPointer2->getClass();
1970130561Sobrien    const Type *ToPointeeType2 = ToMemPointer2->getClass();
197189857Sobrien    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1972130561Sobrien    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
197389857Sobrien    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1974130561Sobrien    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
197589857Sobrien    // conversion of A::* to B::* is better than conversion of A::* to C::*,
1976130561Sobrien    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
197789857Sobrien      if (IsDerivedFrom(ToPointee1, ToPointee2))
1978130561Sobrien        return ImplicitConversionSequence::Worse;
197989857Sobrien      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1980130561Sobrien        return ImplicitConversionSequence::Better;
198189857Sobrien    }
1982130561Sobrien    // conversion of B::* to C::* is better than conversion of A::* to C::*
198389857Sobrien    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1984130561Sobrien      if (IsDerivedFrom(FromPointee1, FromPointee2))
198589857Sobrien        return ImplicitConversionSequence::Better;
1986130561Sobrien      else if (IsDerivedFrom(FromPointee2, FromPointee1))
198789857Sobrien        return ImplicitConversionSequence::Worse;
1988130561Sobrien    }
198989857Sobrien  }
1990130561Sobrien
199189857Sobrien  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1992130561Sobrien      SCS1.Second == ICK_Derived_To_Base) {
199389857Sobrien    //   -- conversion of C to B is better than conversion of C to A,
1994130561Sobrien    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
199589857Sobrien        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
1996130561Sobrien      if (IsDerivedFrom(ToType1, ToType2))
199789857Sobrien        return ImplicitConversionSequence::Better;
1998130561Sobrien      else if (IsDerivedFrom(ToType2, ToType1))
199989857Sobrien        return ImplicitConversionSequence::Worse;
2000130561Sobrien    }
200189857Sobrien
2002130561Sobrien    //   -- conversion of B to A is better than conversion of C to A.
200389857Sobrien    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2004130561Sobrien        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
200589857Sobrien      if (IsDerivedFrom(FromType2, FromType1))
2006130561Sobrien        return ImplicitConversionSequence::Better;
200789857Sobrien      else if (IsDerivedFrom(FromType1, FromType2))
2008130561Sobrien        return ImplicitConversionSequence::Worse;
200989857Sobrien    }
2010130561Sobrien  }
201189857Sobrien
2012130561Sobrien  return ImplicitConversionSequence::Indistinguishable;
201389857Sobrien}
2014130561Sobrien
201589857Sobrien/// TryCopyInitialization - Try to copy-initialize a value of type
2016130561Sobrien/// ToType from the expression From. Return the implicit conversion
201789857Sobrien/// sequence required to pass this argument, which may be a bad
2018130561Sobrien/// conversion sequence (meaning that the argument cannot be passed to
201989857Sobrien/// a parameter of this type). If @p SuppressUserConversions, then we
2020130561Sobrien/// do not permit any user-defined conversion sequences. If @p ForceRValue,
202189857Sobrien/// then we treat @p From as an rvalue, even if it is an lvalue.
2022130561SobrienImplicitConversionSequence
202389857SobrienSema::TryCopyInitialization(Expr *From, QualType ToType,
2024130561Sobrien                            bool SuppressUserConversions, bool ForceRValue,
202589857Sobrien                            bool InOverloadResolution) {
2026130561Sobrien  if (ToType->isReferenceType()) {
202789857Sobrien    ImplicitConversionSequence ICS;
2028130561Sobrien    CheckReferenceInit(From, ToType,
202989857Sobrien                       /*FIXME:*/From->getLocStart(),
2030130561Sobrien                       SuppressUserConversions,
2031130561Sobrien                       /*AllowExplicit=*/false,
2032130561Sobrien                       ForceRValue,
2033130561Sobrien                       &ICS);
2034130561Sobrien    return ICS;
2035130561Sobrien  } else {
2036130561Sobrien    return TryImplicitConversion(From, ToType,
2037130561Sobrien                                 SuppressUserConversions,
2038130561Sobrien                                 /*AllowExplicit=*/false,
2039130561Sobrien                                 ForceRValue,
2040130561Sobrien                                 InOverloadResolution);
2041130561Sobrien  }
2042130561Sobrien}
2043130561Sobrien
2044130561Sobrien/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2045130561Sobrien/// the expression @p From. Returns true (and emits a diagnostic) if there was
2046130561Sobrien/// an error, returns false if the initialization succeeded. Elidable should
2047130561Sobrien/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2048130561Sobrien/// differently in C++0x for this case.
2049130561Sobrienbool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
2050130561Sobrien                                     const char* Flavor, bool Elidable) {
2051130561Sobrien  if (!getLangOptions().CPlusPlus) {
2052130561Sobrien    // In C, argument passing is the same as performing an assignment.
2053130561Sobrien    QualType FromType = From->getType();
2054130561Sobrien
2055130561Sobrien    AssignConvertType ConvTy =
2056130561Sobrien      CheckSingleAssignmentConstraints(ToType, From);
2057130561Sobrien    if (ConvTy != Compatible &&
2058130561Sobrien        CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2059130561Sobrien      ConvTy = Compatible;
2060130561Sobrien
2061130561Sobrien    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2062130561Sobrien                                    FromType, From, Flavor);
2063130561Sobrien  }
2064130561Sobrien
2065130561Sobrien  if (ToType->isReferenceType())
2066130561Sobrien    return CheckReferenceInit(From, ToType,
2067130561Sobrien                              /*FIXME:*/From->getLocStart(),
2068130561Sobrien                              /*SuppressUserConversions=*/false,
2069130561Sobrien                              /*AllowExplicit=*/false,
2070130561Sobrien                              /*ForceRValue=*/false);
2071130561Sobrien
2072130561Sobrien  if (!PerformImplicitConversion(From, ToType, Flavor,
2073130561Sobrien                                 /*AllowExplicit=*/false, Elidable))
2074130561Sobrien    return false;
2075130561Sobrien  if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
2076130561Sobrien    return Diag(From->getSourceRange().getBegin(),
2077130561Sobrien                diag::err_typecheck_convert_incompatible)
2078130561Sobrien      << ToType << From->getType() << Flavor << From->getSourceRange();
2079130561Sobrien  return true;
2080130561Sobrien}
2081130561Sobrien
2082130561Sobrien/// TryObjectArgumentInitialization - Try to initialize the object
2083130561Sobrien/// parameter of the given member function (@c Method) from the
2084130561Sobrien/// expression @p From.
2085130561SobrienImplicitConversionSequence
2086130561SobrienSema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2087130561Sobrien  QualType ClassType = Context.getTypeDeclType(Method->getParent());
2088130561Sobrien  QualType ImplicitParamType
2089130561Sobrien    = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
2090130561Sobrien
2091130561Sobrien  // Set up the conversion sequence as a "bad" conversion, to allow us
2092130561Sobrien  // to exit early.
2093130561Sobrien  ImplicitConversionSequence ICS;
2094130561Sobrien  ICS.Standard.setAsIdentityConversion();
2095130561Sobrien  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2096130561Sobrien
2097130561Sobrien  // We need to have an object of class type.
2098130561Sobrien  QualType FromType = From->getType();
2099130561Sobrien  if (const PointerType *PT = FromType->getAs<PointerType>())
2100130561Sobrien    FromType = PT->getPointeeType();
2101130561Sobrien
2102130561Sobrien  assert(FromType->isRecordType());
2103130561Sobrien
2104130561Sobrien  // The implicit object parmeter is has the type "reference to cv X",
2105130561Sobrien  // where X is the class of which the function is a member
2106130561Sobrien  // (C++ [over.match.funcs]p4). However, when finding an implicit
2107130561Sobrien  // conversion sequence for the argument, we are not allowed to
2108130561Sobrien  // create temporaries or perform user-defined conversions
2109130561Sobrien  // (C++ [over.match.funcs]p5). We perform a simplified version of
211089857Sobrien  // reference binding here, that allows class rvalues to bind to
211189857Sobrien  // non-constant references.
2112130561Sobrien
211389857Sobrien  // First check the qualifiers. We don't care about lvalue-vs-rvalue
211489857Sobrien  // with the implicit object parameter (C++ [over.match.funcs]p5).
2115218822Sdim  QualType FromTypeCanon = Context.getCanonicalType(FromType);
2116218822Sdim  if (ImplicitParamType.getCVRQualifiers()
2117218822Sdim                                    != FromTypeCanon.getLocalCVRQualifiers() &&
2118218822Sdim      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
2119218822Sdim    return ICS;
2120218822Sdim
2121218822Sdim  // Check that we have either the same type or a derived type. It
2122218822Sdim  // affects the conversion rank.
2123218822Sdim  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2124218822Sdim  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
2125218822Sdim    ICS.Standard.Second = ICK_Identity;
2126218822Sdim  else if (IsDerivedFrom(FromType, ClassType))
2127218822Sdim    ICS.Standard.Second = ICK_Derived_To_Base;
2128218822Sdim  else
2129218822Sdim    return ICS;
2130218822Sdim
213189857Sobrien  // Success. Mark this as a reference binding.
213289857Sobrien  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
213389857Sobrien  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2134130561Sobrien  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2135130561Sobrien  ICS.Standard.ReferenceBinding = true;
213689857Sobrien  ICS.Standard.DirectBinding = true;
213789857Sobrien  ICS.Standard.RRefBinding = false;
213889857Sobrien  return ICS;
2139104834Sobrien}
214089857Sobrien
214189857Sobrien/// PerformObjectArgumentInitialization - Perform initialization of
214289857Sobrien/// the implicit object parameter for the given Method with the given
214389857Sobrien/// expression.
2144218822Sdimbool
2145218822SdimSema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2146218822Sdim  QualType FromRecordType, DestType;
2147218822Sdim  QualType ImplicitParamRecordType  =
2148218822Sdim    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2149218822Sdim
2150218822Sdim  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
215189857Sobrien    FromRecordType = PT->getPointeeType();
215289857Sobrien    DestType = Method->getThisType(Context);
215389857Sobrien  } else {
2154130561Sobrien    FromRecordType = From->getType();
215589857Sobrien    DestType = ImplicitParamRecordType;
215689857Sobrien  }
2157130561Sobrien
2158130561Sobrien  ImplicitConversionSequence ICS
2159130561Sobrien    = TryObjectArgumentInitialization(From, Method);
216089857Sobrien  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
216199461Sobrien    return Diag(From->getSourceRange().getBegin(),
216299461Sobrien                diag::err_implicit_object_parameter_init)
216399461Sobrien       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
216499461Sobrien
2165104834Sobrien  if (ICS.Standard.Second == ICK_Derived_To_Base &&
216699461Sobrien      CheckDerivedToBaseConversion(FromRecordType,
216789857Sobrien                                   ImplicitParamRecordType,
216899461Sobrien                                   From->getSourceRange().getBegin(),
216999461Sobrien                                   From->getSourceRange()))
217099461Sobrien    return true;
217199461Sobrien
217299461Sobrien  ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
217399461Sobrien                    /*isLvalue=*/true);
217499461Sobrien  return false;
217599461Sobrien}
2176218822Sdim
2177218822Sdim/// TryContextuallyConvertToBool - Attempt to contextually convert the
2178218822Sdim/// expression From to bool (C++0x [conv]p3).
2179218822SdimImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2180218822Sdim  return TryImplicitConversion(From, Context.BoolTy,
2181218822Sdim                               // FIXME: Are these flags correct?
2182218822Sdim                               /*SuppressUserConversions=*/false,
2183218822Sdim                               /*AllowExplicit=*/true,
2184218822Sdim                               /*ForceRValue=*/false,
2185218822Sdim                               /*InOverloadResolution=*/false);
2186218822Sdim}
2187218822Sdim
2188218822Sdim/// PerformContextuallyConvertToBool - Perform a contextual conversion
2189218822Sdim/// of the expression From to bool (C++0x [conv]p3).
2190218822Sdimbool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2191218822Sdim  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2192218822Sdim  if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2193218822Sdim    return false;
2194218822Sdim
2195218822Sdim  if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2196218822Sdim    return  Diag(From->getSourceRange().getBegin(),
2197218822Sdim                 diag::err_typecheck_bool_condition)
2198218822Sdim                  << From->getType() << From->getSourceRange();
2199130561Sobrien  return true;
2200130561Sobrien}
2201130561Sobrien
220299461Sobrien/// AddOverloadCandidate - Adds the given function to the set of
220399461Sobrien/// candidate functions, using the given function call arguments.  If
2204130561Sobrien/// @p SuppressUserConversions, then don't allow user-defined
220599461Sobrien/// conversions via constructors or conversion operators.
220699461Sobrien/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2207130561Sobrien/// hacky way to implement the overloading rules for elidable copy
220899461Sobrien/// initialization in C++0x (C++0x 12.8p15).
220999461Sobrien///
221099461Sobrien/// \para PartialOverloading true if we are performing "partial" overloading
221199461Sobrien/// based on an incomplete set of function arguments. This feature is used by
221289857Sobrien/// code completion.
2213104834Sobrienvoid
221499461SobrienSema::AddOverloadCandidate(FunctionDecl *Function,
221599461Sobrien                           Expr **Args, unsigned NumArgs,
221699461Sobrien                           OverloadCandidateSet& CandidateSet,
221799461Sobrien                           bool SuppressUserConversions,
221899461Sobrien                           bool ForceRValue,
2219130561Sobrien                           bool PartialOverloading) {
222099461Sobrien  const FunctionProtoType* Proto
222199461Sobrien    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
2222104834Sobrien  assert(Proto && "Functions without a prototype cannot be overloaded");
222399461Sobrien  assert(!isa<CXXConversionDecl>(Function) &&
222499461Sobrien         "Use AddConversionCandidate for conversion functions");
222589857Sobrien  assert(!Function->getDescribedFunctionTemplate() &&
222699461Sobrien         "Use AddTemplateOverloadCandidate for function templates");
222799461Sobrien
222899461Sobrien  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
222999461Sobrien    if (!isa<CXXConstructorDecl>(Method)) {
223099461Sobrien      // If we get here, it's because we're calling a member function
223199461Sobrien      // that is named without a member access expression (e.g.,
223299461Sobrien      // "this->f") that was either written explicitly or created
223399461Sobrien      // implicitly. This can happen with a qualified call to a member
2234218822Sdim      // function, e.g., X::f(). We use a NULL object as the implied
223589857Sobrien      // object argument (C++ [over.call.func]p3).
223699461Sobrien      AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
223799461Sobrien                         SuppressUserConversions, ForceRValue);
223899461Sobrien      return;
223999461Sobrien    }
224089857Sobrien    // We treat a constructor like a non-member function, since its object
224199461Sobrien    // argument doesn't participate in overload resolution.
224299461Sobrien  }
224399461Sobrien
224499461Sobrien  if (!CandidateSet.isNewCandidate(Function))
224599461Sobrien    return;
224689857Sobrien
224799461Sobrien  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
224899461Sobrien    // C++ [class.copy]p3:
224999461Sobrien    //   A member function template is never instantiated to perform the copy
225089857Sobrien    //   of a class object to an object of its class type.
225199461Sobrien    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
225299461Sobrien    if (NumArgs == 1 &&
225399461Sobrien        Constructor->isCopyConstructorLikeSpecialization() &&
225499461Sobrien        Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2255130561Sobrien      return;
2256218822Sdim  }
2257218822Sdim
2258218822Sdim  // Add this candidate
225999461Sobrien  CandidateSet.push_back(OverloadCandidate());
226089857Sobrien  OverloadCandidate& Candidate = CandidateSet.back();
226199461Sobrien  Candidate.Function = Function;
2262130561Sobrien  Candidate.Viable = true;
2263130561Sobrien  Candidate.IsSurrogate = false;
2264130561Sobrien  Candidate.IgnoreObjectArgument = false;
226599461Sobrien
226699461Sobrien  unsigned NumArgsInProto = Proto->getNumArgs();
226799461Sobrien
226899461Sobrien  // (C++ 13.3.2p2): A candidate function having fewer than m
226999461Sobrien  // parameters is viable only if it has an ellipsis in its parameter
2270104834Sobrien  // list (8.3.5).
227199461Sobrien  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
227289857Sobrien      !Proto->isVariadic()) {
227399461Sobrien    Candidate.Viable = false;
227499461Sobrien    return;
227589857Sobrien  }
227689857Sobrien
227789857Sobrien  // (C++ 13.3.2p2): A candidate function having more than m parameters
227899461Sobrien  // is viable only if the (m+1)st parameter has a default argument
2279130561Sobrien  // (8.3.6). For the purposes of overload resolution, the
2280130561Sobrien  // parameter list is truncated on the right, so that there are
2281130561Sobrien  // exactly m parameters.
228299461Sobrien  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
228399461Sobrien  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
228499461Sobrien    // Not enough arguments.
228599461Sobrien    Candidate.Viable = false;
228699461Sobrien    return;
2287104834Sobrien  }
228899461Sobrien
228999461Sobrien  // Determine the implicit conversion sequences for each of the
229099461Sobrien  // arguments.
229199461Sobrien  Candidate.Conversions.resize(NumArgs);
229299461Sobrien  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
229399461Sobrien    if (ArgIdx < NumArgsInProto) {
229499461Sobrien      // (C++ 13.3.2p3): for F to be a viable function, there shall
229599461Sobrien      // exist for each argument an implicit conversion sequence
229699461Sobrien      // (13.3.3.1) that converts that argument to the corresponding
229799461Sobrien      // parameter of F.
229899461Sobrien      QualType ParamType = Proto->getArgType(ArgIdx);
2299130561Sobrien      Candidate.Conversions[ArgIdx]
2300130561Sobrien        = TryCopyInitialization(Args[ArgIdx], ParamType,
2301130561Sobrien                                SuppressUserConversions, ForceRValue,
230299461Sobrien                                /*InOverloadResolution=*/true);
230399461Sobrien      if (Candidate.Conversions[ArgIdx].ConversionKind
230499461Sobrien            == ImplicitConversionSequence::BadConversion) {
230599461Sobrien      // 13.3.3.1-p10 If several different sequences of conversions exist that
230699461Sobrien      // each convert the argument to the parameter type, the implicit conversion
230799461Sobrien      // sequence associated with the parameter is defined to be the unique conversion
230899461Sobrien      // sequence designated the ambiguous conversion sequence. For the purpose of
2309104834Sobrien      // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
231099461Sobrien      // conversion sequence is treated as a user-defined sequence that is
231199461Sobrien      // indistinguishable from any other user-defined conversion sequence
231299461Sobrien        if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
231399461Sobrien          Candidate.Conversions[ArgIdx].ConversionKind =
231499461Sobrien            ImplicitConversionSequence::UserDefinedConversion;
231599461Sobrien          // Set the conversion function to one of them. As due to ambiguity,
231699461Sobrien          // they carry the same weight and is needed for overload resolution
231799461Sobrien          // later.
231899461Sobrien          Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
231999461Sobrien            Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
232099461Sobrien        }
232199461Sobrien        else {
2322130561Sobrien          Candidate.Viable = false;
2323130561Sobrien          break;
2324130561Sobrien        }
232599461Sobrien      }
232699461Sobrien    } else {
232799461Sobrien      // (C++ 13.3.2p2): For the purposes of overload resolution, any
232899461Sobrien      // argument for which there is no corresponding parameter is
232999461Sobrien      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
233099461Sobrien      Candidate.Conversions[ArgIdx].ConversionKind
233199461Sobrien        = ImplicitConversionSequence::EllipsisConversion;
2332104834Sobrien    }
233399461Sobrien  }
233499461Sobrien}
233599461Sobrien
233699461Sobrien/// \brief Add all of the function declarations in the given function set to
233799461Sobrien/// the overload canddiate set.
233899461Sobrienvoid Sema::AddFunctionCandidates(const FunctionSet &Functions,
233999461Sobrien                                 Expr **Args, unsigned NumArgs,
234099461Sobrien                                 OverloadCandidateSet& CandidateSet,
234199461Sobrien                                 bool SuppressUserConversions) {
234299461Sobrien  for (FunctionSet::const_iterator F = Functions.begin(),
234399461Sobrien                                FEnd = Functions.end();
234499461Sobrien       F != FEnd; ++F) {
234599461Sobrien    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
234699461Sobrien      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
234799461Sobrien        AddMethodCandidate(cast<CXXMethodDecl>(FD),
2348130561Sobrien                           Args[0], Args + 1, NumArgs - 1,
2349130561Sobrien                           CandidateSet, SuppressUserConversions);
2350130561Sobrien      else
235199461Sobrien        AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
235299461Sobrien                             SuppressUserConversions);
235399461Sobrien    } else {
235499461Sobrien      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
235599461Sobrien      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
235699461Sobrien          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
235799461Sobrien        AddMethodTemplateCandidate(FunTmpl,
235899461Sobrien                                   /*FIXME: explicit args */false, 0, 0,
2359104834Sobrien                                   Args[0], Args + 1, NumArgs - 1,
236099461Sobrien                                   CandidateSet,
236199461Sobrien                                   SuppressUserConversions);
236299461Sobrien      else
236399461Sobrien        AddTemplateOverloadCandidate(FunTmpl,
236499461Sobrien                                     /*FIXME: explicit args */false, 0, 0,
236599461Sobrien                                     Args, NumArgs, CandidateSet,
236699461Sobrien                                     SuppressUserConversions);
236799461Sobrien    }
236899461Sobrien  }
236999461Sobrien}
237099461Sobrien
237199461Sobrien/// AddMethodCandidate - Adds a named decl (which is some kind of
2372130561Sobrien/// method) as a method candidate to the given overload set.
2373130561Sobrienvoid Sema::AddMethodCandidate(NamedDecl *Decl, Expr *Object,
2374130561Sobrien                              Expr **Args, unsigned NumArgs,
237599461Sobrien                              OverloadCandidateSet& CandidateSet,
237699461Sobrien                              bool SuppressUserConversions, bool ForceRValue) {
237799461Sobrien
237899461Sobrien  // FIXME: use this
237999461Sobrien  //DeclContext *ActingContext = Decl->getDeclContext();
2380104834Sobrien
238199461Sobrien  if (isa<UsingShadowDecl>(Decl))
238299461Sobrien    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
238399461Sobrien
238499461Sobrien  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
238599461Sobrien    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
238699461Sobrien           "Expected a member function template");
238799461Sobrien    AddMethodTemplateCandidate(TD, false, 0, 0,
238899461Sobrien                               Object, Args, NumArgs,
238999461Sobrien                               CandidateSet,
239099461Sobrien                               SuppressUserConversions,
239199461Sobrien                               ForceRValue);
239299461Sobrien  } else {
2393130561Sobrien    AddMethodCandidate(cast<CXXMethodDecl>(Decl), Object, Args, NumArgs,
2394130561Sobrien                       CandidateSet, SuppressUserConversions, ForceRValue);
2395130561Sobrien  }
2396130561Sobrien}
2397130561Sobrien
2398130561Sobrien/// AddMethodCandidate - Adds the given C++ member function to the set
2399130561Sobrien/// of candidate functions, using the given function call arguments
2400130561Sobrien/// and the object argument (@c Object). For example, in a call
2401218822Sdim/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2402218822Sdim/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2403218822Sdim/// allow user-defined conversions via constructors or conversion
2404218822Sdim/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2405130561Sobrien/// a slightly hacky way to implement the overloading rules for elidable copy
2406130561Sobrien/// initialization in C++0x (C++0x 12.8p15).
2407130561Sobrienvoid
2408130561SobrienSema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2409130561Sobrien                         Expr **Args, unsigned NumArgs,
2410130561Sobrien                         OverloadCandidateSet& CandidateSet,
2411218822Sdim                         bool SuppressUserConversions, bool ForceRValue) {
2412218822Sdim  const FunctionProtoType* Proto
2413218822Sdim    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
2414130561Sobrien  assert(Proto && "Methods without a prototype cannot be overloaded");
2415130561Sobrien  assert(!isa<CXXConversionDecl>(Method) &&
2416130561Sobrien         "Use AddConversionCandidate for conversion functions");
2417130561Sobrien  assert(!isa<CXXConstructorDecl>(Method) &&
2418130561Sobrien         "Use AddOverloadCandidate for constructors");
2419130561Sobrien
2420130561Sobrien  if (!CandidateSet.isNewCandidate(Method))
2421130561Sobrien    return;
2422130561Sobrien
2423130561Sobrien  // Add this candidate
2424130561Sobrien  CandidateSet.push_back(OverloadCandidate());
2425130561Sobrien  OverloadCandidate& Candidate = CandidateSet.back();
2426130561Sobrien  Candidate.Function = Method;
2427130561Sobrien  Candidate.IsSurrogate = false;
2428218822Sdim  Candidate.IgnoreObjectArgument = false;
2429218822Sdim
2430218822Sdim  unsigned NumArgsInProto = Proto->getNumArgs();
2431218822Sdim
2432218822Sdim  // (C++ 13.3.2p2): A candidate function having fewer than m
2433218822Sdim  // parameters is viable only if it has an ellipsis in its parameter
2434218822Sdim  // list (8.3.5).
2435130561Sobrien  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2436130561Sobrien    Candidate.Viable = false;
2437218822Sdim    return;
2438218822Sdim  }
2439218822Sdim
2440218822Sdim  // (C++ 13.3.2p2): A candidate function having more than m parameters
2441218822Sdim  // is viable only if the (m+1)st parameter has a default argument
2442218822Sdim  // (8.3.6). For the purposes of overload resolution, the
2443218822Sdim  // parameter list is truncated on the right, so that there are
2444218822Sdim  // exactly m parameters.
2445218822Sdim  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2446218822Sdim  if (NumArgs < MinRequiredArgs) {
2447218822Sdim    // Not enough arguments.
2448104834Sobrien    Candidate.Viable = false;
2449104834Sobrien    return;
245089857Sobrien  }
2451130561Sobrien
2452130561Sobrien  Candidate.Viable = true;
245389857Sobrien  Candidate.Conversions.resize(NumArgs + 1);
2454104834Sobrien
2455104834Sobrien  if (Method->isStatic() || !Object)
2456104834Sobrien    // The implicit object argument is ignored.
245789857Sobrien    Candidate.IgnoreObjectArgument = true;
2458104834Sobrien  else {
2459104834Sobrien    // Determine the implicit conversion sequence for the object
2460104834Sobrien    // parameter.
2461104834Sobrien    Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2462104834Sobrien    if (Candidate.Conversions[0].ConversionKind
2463104834Sobrien          == ImplicitConversionSequence::BadConversion) {
2464104834Sobrien      Candidate.Viable = false;
2465130561Sobrien      return;
246689857Sobrien    }
246789857Sobrien  }
2468130561Sobrien
2469130561Sobrien  // Determine the implicit conversion sequences for each of the
2470130561Sobrien  // arguments.
2471130561Sobrien  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2472130561Sobrien    if (ArgIdx < NumArgsInProto) {
2473218822Sdim      // (C++ 13.3.2p3): for F to be a viable function, there shall
2474130561Sobrien      // exist for each argument an implicit conversion sequence
2475130561Sobrien      // (13.3.3.1) that converts that argument to the corresponding
2476130561Sobrien      // parameter of F.
2477130561Sobrien      QualType ParamType = Proto->getArgType(ArgIdx);
2478130561Sobrien      Candidate.Conversions[ArgIdx + 1]
2479130561Sobrien        = TryCopyInitialization(Args[ArgIdx], ParamType,
2480130561Sobrien                                SuppressUserConversions, ForceRValue,
2481130561Sobrien                                /*InOverloadResolution=*/true);
2482130561Sobrien      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2483130561Sobrien            == ImplicitConversionSequence::BadConversion) {
2484130561Sobrien        Candidate.Viable = false;
2485130561Sobrien        break;
2486218822Sdim      }
2487130561Sobrien    } else {
2488130561Sobrien      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2489130561Sobrien      // argument for which there is no corresponding parameter is
2490218822Sdim      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2491130561Sobrien      Candidate.Conversions[ArgIdx + 1].ConversionKind
2492130561Sobrien        = ImplicitConversionSequence::EllipsisConversion;
2493130561Sobrien    }
2494130561Sobrien  }
2495130561Sobrien}
2496130561Sobrien
2497130561Sobrien/// \brief Add a C++ member function template as a candidate to the candidate
2498130561Sobrien/// set, using template argument deduction to produce an appropriate member
2499130561Sobrien/// function template specialization.
2500130561Sobrienvoid
2501130561SobrienSema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2502130561Sobrien                                 bool HasExplicitTemplateArgs,
2503130561Sobrien                             const TemplateArgumentLoc *ExplicitTemplateArgs,
2504130561Sobrien                                 unsigned NumExplicitTemplateArgs,
2505130561Sobrien                                 Expr *Object, Expr **Args, unsigned NumArgs,
2506130561Sobrien                                 OverloadCandidateSet& CandidateSet,
2507218822Sdim                                 bool SuppressUserConversions,
2508218822Sdim                                 bool ForceRValue) {
2509218822Sdim  if (!CandidateSet.isNewCandidate(MethodTmpl))
2510218822Sdim    return;
2511218822Sdim
2512218822Sdim  // C++ [over.match.funcs]p7:
2513218822Sdim  //   In each case where a candidate is a function template, candidate
2514218822Sdim  //   function template specializations are generated using template argument
2515218822Sdim  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2516218822Sdim  //   candidate functions in the usual way.113) A given name can refer to one
2517218822Sdim  //   or more function templates and also to a set of overloaded non-template
2518218822Sdim  //   functions. In such a case, the candidate functions generated from each
2519218822Sdim  //   function template are combined with the set of non-template candidate
2520218822Sdim  //   functions.
2521218822Sdim  TemplateDeductionInfo Info(Context);
2522218822Sdim  FunctionDecl *Specialization = 0;
2523218822Sdim  if (TemplateDeductionResult Result
2524218822Sdim      = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2525218822Sdim                                ExplicitTemplateArgs, NumExplicitTemplateArgs,
2526218822Sdim                                Args, NumArgs, Specialization, Info)) {
2527218822Sdim        // FIXME: Record what happened with template argument deduction, so
2528218822Sdim        // that we can give the user a beautiful diagnostic.
2529218822Sdim        (void)Result;
2530218822Sdim        return;
2531218822Sdim      }
2532218822Sdim
2533218822Sdim  // Add the function template specialization produced by template argument
2534218822Sdim  // deduction as a candidate.
2535218822Sdim  assert(Specialization && "Missing member function template specialization?");
2536218822Sdim  assert(isa<CXXMethodDecl>(Specialization) &&
2537218822Sdim         "Specialization is not a member function?");
2538218822Sdim  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2539218822Sdim                     CandidateSet, SuppressUserConversions, ForceRValue);
2540218822Sdim}
2541218822Sdim
2542218822Sdim/// \brief Add a C++ function template specialization as a candidate
2543218822Sdim/// in the candidate set, using template argument deduction to produce
2544218822Sdim/// an appropriate function template specialization.
2545218822Sdimvoid
2546218822SdimSema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2547218822Sdim                                   bool HasExplicitTemplateArgs,
2548218822Sdim                          const TemplateArgumentLoc *ExplicitTemplateArgs,
2549218822Sdim                                   unsigned NumExplicitTemplateArgs,
2550218822Sdim                                   Expr **Args, unsigned NumArgs,
2551218822Sdim                                   OverloadCandidateSet& CandidateSet,
2552218822Sdim                                   bool SuppressUserConversions,
2553218822Sdim                                   bool ForceRValue) {
255489857Sobrien  if (!CandidateSet.isNewCandidate(FunctionTemplate))
255589857Sobrien    return;
2556104834Sobrien
2557130561Sobrien  // C++ [over.match.funcs]p7:
2558130561Sobrien  //   In each case where a candidate is a function template, candidate
255989857Sobrien  //   function template specializations are generated using template argument
256089857Sobrien  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
256189857Sobrien  //   candidate functions in the usual way.113) A given name can refer to one
2562107492Sobrien  //   or more function templates and also to a set of overloaded non-template
256389857Sobrien  //   functions. In such a case, the candidate functions generated from each
256489857Sobrien  //   function template are combined with the set of non-template candidate
256589857Sobrien  //   functions.
256689857Sobrien  TemplateDeductionInfo Info(Context);
256789857Sobrien  FunctionDecl *Specialization = 0;
2568218822Sdim  if (TemplateDeductionResult Result
2569130561Sobrien        = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
257089857Sobrien                                  ExplicitTemplateArgs, NumExplicitTemplateArgs,
2571218822Sdim                                  Args, NumArgs, Specialization, Info)) {
2572130561Sobrien    // FIXME: Record what happened with template argument deduction, so
257389857Sobrien    // that we can give the user a beautiful diagnostic.
2574218822Sdim    (void)Result;
257589857Sobrien    return;
257689857Sobrien  }
2577130561Sobrien
257889857Sobrien  // Add the function template specialization produced by template argument
257989857Sobrien  // deduction as a candidate.
2580130561Sobrien  assert(Specialization && "Missing function template specialization?");
258189857Sobrien  AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2582130561Sobrien                       SuppressUserConversions, ForceRValue);
2583130561Sobrien}
2584130561Sobrien
2585218822Sdim/// AddConversionCandidate - Add a C++ conversion function as a
2586130561Sobrien/// candidate in the candidate set (C++ [over.match.conv],
2587218822Sdim/// C++ [over.match.copy]). From is the expression we're converting from,
2588218822Sdim/// and ToType is the type that we're eventually trying to convert to
2589218822Sdim/// (which may or may not be the same type as the type that the
2590218822Sdim/// conversion function produces).
2591218822Sdimvoid
2592218822SdimSema::AddConversionCandidate(CXXConversionDecl *Conversion,
2593218822Sdim                             Expr *From, QualType ToType,
2594130561Sobrien                             OverloadCandidateSet& CandidateSet) {
2595130561Sobrien  assert(!Conversion->getDescribedFunctionTemplate() &&
2596218822Sdim         "Conversion function templates use AddTemplateConversionCandidate");
2597218822Sdim
2598218822Sdim  if (!CandidateSet.isNewCandidate(Conversion))
2599218822Sdim    return;
2600218822Sdim
2601218822Sdim  // Add this candidate
2602130561Sobrien  CandidateSet.push_back(OverloadCandidate());
2603130561Sobrien  OverloadCandidate& Candidate = CandidateSet.back();
2604130561Sobrien  Candidate.Function = Conversion;
2605130561Sobrien  Candidate.IsSurrogate = false;
2606130561Sobrien  Candidate.IgnoreObjectArgument = false;
2607130561Sobrien  Candidate.FinalConversion.setAsIdentityConversion();
2608130561Sobrien  Candidate.FinalConversion.FromTypePtr
2609130561Sobrien    = Conversion->getConversionType().getAsOpaquePtr();
2610218822Sdim  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2611130561Sobrien
2612218822Sdim  // Determine the implicit conversion sequence for the implicit
2613130561Sobrien  // object parameter.
2614218822Sdim  Candidate.Viable = true;
2615218822Sdim  Candidate.Conversions.resize(1);
2616218822Sdim  Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2617218822Sdim  // Conversion functions to a different type in the base class is visible in
2618218822Sdim  // the derived class.  So, a derived to base conversion should not participate
2619218822Sdim  // in overload resolution.
2620218822Sdim  if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2621218822Sdim    Candidate.Conversions[0].Standard.Second = ICK_Identity;
2622218822Sdim  if (Candidate.Conversions[0].ConversionKind
2623218822Sdim      == ImplicitConversionSequence::BadConversion) {
2624130561Sobrien    Candidate.Viable = false;
2625130561Sobrien    return;
2626130561Sobrien  }
2627130561Sobrien
2628130561Sobrien  // We won't go through a user-define type conversion function to convert a
2629130561Sobrien  // derived to base as such conversions are given Conversion Rank. They only
2630130561Sobrien  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2631130561Sobrien  QualType FromCanon
2632218822Sdim    = Context.getCanonicalType(From->getType().getUnqualifiedType());
2633218822Sdim  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2634218822Sdim  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2635218822Sdim    Candidate.Viable = false;
2636130561Sobrien    return;
2637218822Sdim  }
2638218822Sdim
2639218822Sdim
2640218822Sdim  // To determine what the conversion from the result of calling the
2641218822Sdim  // conversion function to the type we're eventually trying to
2642130561Sobrien  // convert to (ToType), we need to synthesize a call to the
2643130561Sobrien  // conversion function and attempt copy initialization from it. This
2644130561Sobrien  // makes sure that we get the right semantics with respect to
2645218822Sdim  // lvalues/rvalues and the type. Fortunately, we can allocate this
2646218822Sdim  // call on the stack and we don't need its arguments to be
2647218822Sdim  // well-formed.
2648218822Sdim  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2649218822Sdim                            From->getLocStart());
2650218822Sdim  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2651218822Sdim                                CastExpr::CK_FunctionToPointerDecay,
2652218822Sdim                                &ConversionRef, false);
2653218822Sdim
2654218822Sdim  // Note that it is safe to allocate CallExpr on the stack here because
265589857Sobrien  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2656218822Sdim  // allocator).
2657218822Sdim  CallExpr Call(Context, &ConversionFn, 0, 0,
2658218822Sdim                Conversion->getConversionType().getNonReferenceType(),
2659218822Sdim                From->getLocStart());
2660218822Sdim  ImplicitConversionSequence ICS =
2661218822Sdim    TryCopyInitialization(&Call, ToType,
2662218822Sdim                          /*SuppressUserConversions=*/true,
2663218822Sdim                          /*ForceRValue=*/false,
2664218822Sdim                          /*InOverloadResolution=*/false);
2665218822Sdim
2666218822Sdim  switch (ICS.ConversionKind) {
2667218822Sdim  case ImplicitConversionSequence::StandardConversion:
2668218822Sdim    Candidate.FinalConversion = ICS.Standard;
2669218822Sdim    break;
2670218822Sdim
2671218822Sdim  case ImplicitConversionSequence::BadConversion:
2672218822Sdim    Candidate.Viable = false;
2673218822Sdim    break;
2674218822Sdim
2675218822Sdim  default:
2676218822Sdim    assert(false &&
2677218822Sdim           "Can only end up with a standard conversion sequence or failure");
2678218822Sdim  }
2679218822Sdim}
2680218822Sdim
2681218822Sdim/// \brief Adds a conversion function template specialization
2682218822Sdim/// candidate to the overload set, using template argument deduction
2683218822Sdim/// to deduce the template arguments of the conversion function
2684218822Sdim/// template from the type that we are converting to (C++
2685218822Sdim/// [temp.deduct.conv]).
2686218822Sdimvoid
2687218822SdimSema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2688218822Sdim                                     Expr *From, QualType ToType,
2689218822Sdim                                     OverloadCandidateSet &CandidateSet) {
2690218822Sdim  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2691218822Sdim         "Only conversion function templates permitted here");
2692218822Sdim
2693218822Sdim  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2694218822Sdim    return;
2695218822Sdim
2696218822Sdim  TemplateDeductionInfo Info(Context);
2697218822Sdim  CXXConversionDecl *Specialization = 0;
2698218822Sdim  if (TemplateDeductionResult Result
2699218822Sdim        = DeduceTemplateArguments(FunctionTemplate, ToType,
2700218822Sdim                                  Specialization, Info)) {
2701218822Sdim    // FIXME: Record what happened with template argument deduction, so
2702218822Sdim    // that we can give the user a beautiful diagnostic.
2703218822Sdim    (void)Result;
2704218822Sdim    return;
2705218822Sdim  }
2706218822Sdim
2707218822Sdim  // Add the conversion function template specialization produced by
2708218822Sdim  // template argument deduction as a candidate.
2709218822Sdim  assert(Specialization && "Missing function template specialization?");
2710218822Sdim  AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2711218822Sdim}
2712218822Sdim
2713218822Sdim/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2714218822Sdim/// converts the given @c Object to a function pointer via the
2715218822Sdim/// conversion function @c Conversion, and then attempts to call it
2716218822Sdim/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2717218822Sdim/// the type of function that we'll eventually be calling.
2718218822Sdimvoid Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2719218822Sdim                                 const FunctionProtoType *Proto,
2720218822Sdim                                 Expr *Object, Expr **Args, unsigned NumArgs,
2721218822Sdim                                 OverloadCandidateSet& CandidateSet) {
2722218822Sdim  if (!CandidateSet.isNewCandidate(Conversion))
2723218822Sdim    return;
2724218822Sdim
2725218822Sdim  CandidateSet.push_back(OverloadCandidate());
2726218822Sdim  OverloadCandidate& Candidate = CandidateSet.back();
2727218822Sdim  Candidate.Function = 0;
2728218822Sdim  Candidate.Surrogate = Conversion;
2729218822Sdim  Candidate.Viable = true;
2730218822Sdim  Candidate.IsSurrogate = true;
2731218822Sdim  Candidate.IgnoreObjectArgument = false;
2732218822Sdim  Candidate.Conversions.resize(NumArgs + 1);
2733218822Sdim
2734218822Sdim  // Determine the implicit conversion sequence for the implicit
2735218822Sdim  // object parameter.
2736218822Sdim  ImplicitConversionSequence ObjectInit
2737218822Sdim    = TryObjectArgumentInitialization(Object, Conversion);
2738218822Sdim  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2739218822Sdim    Candidate.Viable = false;
2740218822Sdim    return;
2741218822Sdim  }
2742218822Sdim
2743218822Sdim  // The first conversion is actually a user-defined conversion whose
2744218822Sdim  // first conversion is ObjectInit's standard conversion (which is
2745218822Sdim  // effectively a reference binding). Record it as such.
2746218822Sdim  Candidate.Conversions[0].ConversionKind
2747218822Sdim    = ImplicitConversionSequence::UserDefinedConversion;
2748218822Sdim  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2749218822Sdim  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
2750218822Sdim  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2751218822Sdim  Candidate.Conversions[0].UserDefined.After
2752218822Sdim    = Candidate.Conversions[0].UserDefined.Before;
2753218822Sdim  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2754218822Sdim
2755218822Sdim  // Find the
2756218822Sdim  unsigned NumArgsInProto = Proto->getNumArgs();
2757218822Sdim
2758218822Sdim  // (C++ 13.3.2p2): A candidate function having fewer than m
2759218822Sdim  // parameters is viable only if it has an ellipsis in its parameter
2760218822Sdim  // list (8.3.5).
2761218822Sdim  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2762218822Sdim    Candidate.Viable = false;
2763218822Sdim    return;
2764218822Sdim  }
2765218822Sdim
2766218822Sdim  // Function types don't have any default arguments, so just check if
2767218822Sdim  // we have enough arguments.
2768218822Sdim  if (NumArgs < NumArgsInProto) {
2769218822Sdim    // Not enough arguments.
2770218822Sdim    Candidate.Viable = false;
2771218822Sdim    return;
2772218822Sdim  }
2773218822Sdim
2774218822Sdim  // Determine the implicit conversion sequences for each of the
2775218822Sdim  // arguments.
2776218822Sdim  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2777218822Sdim    if (ArgIdx < NumArgsInProto) {
2778218822Sdim      // (C++ 13.3.2p3): for F to be a viable function, there shall
2779218822Sdim      // exist for each argument an implicit conversion sequence
2780218822Sdim      // (13.3.3.1) that converts that argument to the corresponding
2781218822Sdim      // parameter of F.
2782218822Sdim      QualType ParamType = Proto->getArgType(ArgIdx);
2783218822Sdim      Candidate.Conversions[ArgIdx + 1]
2784218822Sdim        = TryCopyInitialization(Args[ArgIdx], ParamType,
2785218822Sdim                                /*SuppressUserConversions=*/false,
2786218822Sdim                                /*ForceRValue=*/false,
2787218822Sdim                                /*InOverloadResolution=*/false);
2788218822Sdim      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2789218822Sdim            == ImplicitConversionSequence::BadConversion) {
2790218822Sdim        Candidate.Viable = false;
2791218822Sdim        break;
2792218822Sdim      }
2793218822Sdim    } else {
2794218822Sdim      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2795218822Sdim      // argument for which there is no corresponding parameter is
2796218822Sdim      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2797218822Sdim      Candidate.Conversions[ArgIdx + 1].ConversionKind
2798218822Sdim        = ImplicitConversionSequence::EllipsisConversion;
2799218822Sdim    }
2800218822Sdim  }
2801218822Sdim}
2802218822Sdim
2803218822Sdim// FIXME: This will eventually be removed, once we've migrated all of the
2804218822Sdim// operator overloading logic over to the scheme used by binary operators, which
2805218822Sdim// works for template instantiation.
2806218822Sdimvoid Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2807218822Sdim                                 SourceLocation OpLoc,
2808218822Sdim                                 Expr **Args, unsigned NumArgs,
2809218822Sdim                                 OverloadCandidateSet& CandidateSet,
2810218822Sdim                                 SourceRange OpRange) {
2811218822Sdim  FunctionSet Functions;
2812218822Sdim
2813218822Sdim  QualType T1 = Args[0]->getType();
2814218822Sdim  QualType T2;
2815218822Sdim  if (NumArgs > 1)
2816218822Sdim    T2 = Args[1]->getType();
2817218822Sdim
2818218822Sdim  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2819218822Sdim  if (S)
2820218822Sdim    LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2821218822Sdim  ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
2822218822Sdim  AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2823218822Sdim  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2824218822Sdim  AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
2825218822Sdim}
2826218822Sdim
2827218822Sdim/// \brief Add overload candidates for overloaded operators that are
2828218822Sdim/// member functions.
2829218822Sdim///
2830218822Sdim/// Add the overloaded operator candidates that are member functions
2831218822Sdim/// for the operator Op that was used in an operator expression such
2832218822Sdim/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2833218822Sdim/// CandidateSet will store the added overload candidates. (C++
2834218822Sdim/// [over.match.oper]).
2835218822Sdimvoid Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2836218822Sdim                                       SourceLocation OpLoc,
2837218822Sdim                                       Expr **Args, unsigned NumArgs,
2838218822Sdim                                       OverloadCandidateSet& CandidateSet,
2839218822Sdim                                       SourceRange OpRange) {
2840218822Sdim  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2841218822Sdim
2842218822Sdim  // C++ [over.match.oper]p3:
2843218822Sdim  //   For a unary operator @ with an operand of a type whose
2844218822Sdim  //   cv-unqualified version is T1, and for a binary operator @ with
2845218822Sdim  //   a left operand of a type whose cv-unqualified version is T1 and
2846218822Sdim  //   a right operand of a type whose cv-unqualified version is T2,
2847218822Sdim  //   three sets of candidate functions, designated member
2848218822Sdim  //   candidates, non-member candidates and built-in candidates, are
2849218822Sdim  //   constructed as follows:
2850218822Sdim  QualType T1 = Args[0]->getType();
2851218822Sdim  QualType T2;
2852218822Sdim  if (NumArgs > 1)
2853218822Sdim    T2 = Args[1]->getType();
2854218822Sdim
2855218822Sdim  //     -- If T1 is a class type, the set of member candidates is the
2856218822Sdim  //        result of the qualified lookup of T1::operator@
2857218822Sdim  //        (13.3.1.1.1); otherwise, the set of member candidates is
2858218822Sdim  //        empty.
2859218822Sdim  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
2860218822Sdim    // Complete the type if it can be completed. Otherwise, we're done.
2861218822Sdim    if (RequireCompleteType(OpLoc, T1, PDiag()))
2862218822Sdim      return;
2863218822Sdim
2864218822Sdim    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2865218822Sdim    LookupQualifiedName(Operators, T1Rec->getDecl());
2866218822Sdim    Operators.suppressDiagnostics();
2867218822Sdim
2868218822Sdim    for (LookupResult::iterator Oper = Operators.begin(),
2869218822Sdim                             OperEnd = Operators.end();
2870218822Sdim         Oper != OperEnd;
2871218822Sdim         ++Oper)
2872218822Sdim      AddMethodCandidate(*Oper, Args[0], Args + 1, NumArgs - 1, CandidateSet,
2873218822Sdim                         /* SuppressUserConversions = */ false);
2874218822Sdim  }
2875218822Sdim}
2876218822Sdim
2877218822Sdim/// AddBuiltinCandidate - Add a candidate for a built-in
2878218822Sdim/// operator. ResultTy and ParamTys are the result and parameter types
2879218822Sdim/// of the built-in candidate, respectively. Args and NumArgs are the
2880218822Sdim/// arguments being passed to the candidate. IsAssignmentOperator
2881218822Sdim/// should be true when this built-in candidate is an assignment
2882218822Sdim/// operator. NumContextualBoolArguments is the number of arguments
2883218822Sdim/// (at the beginning of the argument list) that will be contextually
2884218822Sdim/// converted to bool.
2885218822Sdimvoid Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2886218822Sdim                               Expr **Args, unsigned NumArgs,
2887218822Sdim                               OverloadCandidateSet& CandidateSet,
2888218822Sdim                               bool IsAssignmentOperator,
2889218822Sdim                               unsigned NumContextualBoolArguments) {
2890218822Sdim  // Add this candidate
2891218822Sdim  CandidateSet.push_back(OverloadCandidate());
2892218822Sdim  OverloadCandidate& Candidate = CandidateSet.back();
2893218822Sdim  Candidate.Function = 0;
2894218822Sdim  Candidate.IsSurrogate = false;
2895218822Sdim  Candidate.IgnoreObjectArgument = false;
2896218822Sdim  Candidate.BuiltinTypes.ResultTy = ResultTy;
2897218822Sdim  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2898218822Sdim    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2899218822Sdim
2900218822Sdim  // Determine the implicit conversion sequences for each of the
2901218822Sdim  // arguments.
2902218822Sdim  Candidate.Viable = true;
2903218822Sdim  Candidate.Conversions.resize(NumArgs);
2904218822Sdim  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2905218822Sdim    // C++ [over.match.oper]p4:
2906218822Sdim    //   For the built-in assignment operators, conversions of the
2907218822Sdim    //   left operand are restricted as follows:
2908218822Sdim    //     -- no temporaries are introduced to hold the left operand, and
2909218822Sdim    //     -- no user-defined conversions are applied to the left
2910218822Sdim    //        operand to achieve a type match with the left-most
2911218822Sdim    //        parameter of a built-in candidate.
2912218822Sdim    //
2913218822Sdim    // We block these conversions by turning off user-defined
2914218822Sdim    // conversions, since that is the only way that initialization of
2915218822Sdim    // a reference to a non-class type can occur from something that
2916218822Sdim    // is not of the same type.
2917218822Sdim    if (ArgIdx < NumContextualBoolArguments) {
2918218822Sdim      assert(ParamTys[ArgIdx] == Context.BoolTy &&
2919218822Sdim             "Contextual conversion to bool requires bool type");
2920218822Sdim      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2921218822Sdim    } else {
2922218822Sdim      Candidate.Conversions[ArgIdx]
2923218822Sdim        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2924218822Sdim                                ArgIdx == 0 && IsAssignmentOperator,
2925218822Sdim                                /*ForceRValue=*/false,
2926218822Sdim                                /*InOverloadResolution=*/false);
2927218822Sdim    }
2928218822Sdim    if (Candidate.Conversions[ArgIdx].ConversionKind
2929218822Sdim        == ImplicitConversionSequence::BadConversion) {
2930218822Sdim      Candidate.Viable = false;
2931218822Sdim      break;
2932218822Sdim    }
2933218822Sdim  }
2934218822Sdim}
2935218822Sdim
2936218822Sdim/// BuiltinCandidateTypeSet - A set of types that will be used for the
2937218822Sdim/// candidate operator functions for built-in operators (C++
2938218822Sdim/// [over.built]). The types are separated into pointer types and
2939218822Sdim/// enumeration types.
2940218822Sdimclass BuiltinCandidateTypeSet  {
2941218822Sdim  /// TypeSet - A set of types.
2942218822Sdim  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2943218822Sdim
2944218822Sdim  /// PointerTypes - The set of pointer types that will be used in the
2945218822Sdim  /// built-in candidates.
2946218822Sdim  TypeSet PointerTypes;
2947218822Sdim
2948218822Sdim  /// MemberPointerTypes - The set of member pointer types that will be
2949218822Sdim  /// used in the built-in candidates.
2950218822Sdim  TypeSet MemberPointerTypes;
2951218822Sdim
2952218822Sdim  /// EnumerationTypes - The set of enumeration types that will be
2953218822Sdim  /// used in the built-in candidates.
2954218822Sdim  TypeSet EnumerationTypes;
2955218822Sdim
2956218822Sdim  /// Sema - The semantic analysis instance where we are building the
2957218822Sdim  /// candidate type set.
2958218822Sdim  Sema &SemaRef;
2959218822Sdim
2960218822Sdim  /// Context - The AST context in which we will build the type sets.
2961218822Sdim  ASTContext &Context;
2962218822Sdim
2963218822Sdim  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2964218822Sdim                                               const Qualifiers &VisibleQuals);
2965218822Sdim  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
2966218822Sdim
2967218822Sdimpublic:
2968218822Sdim  /// iterator - Iterates through the types that are part of the set.
2969218822Sdim  typedef TypeSet::iterator iterator;
2970218822Sdim
2971218822Sdim  BuiltinCandidateTypeSet(Sema &SemaRef)
2972218822Sdim    : SemaRef(SemaRef), Context(SemaRef.Context) { }
2973218822Sdim
2974218822Sdim  void AddTypesConvertedFrom(QualType Ty,
2975218822Sdim                             SourceLocation Loc,
2976218822Sdim                             bool AllowUserConversions,
2977218822Sdim                             bool AllowExplicitConversions,
2978218822Sdim                             const Qualifiers &VisibleTypeConversionsQuals);
2979218822Sdim
2980218822Sdim  /// pointer_begin - First pointer type found;
2981218822Sdim  iterator pointer_begin() { return PointerTypes.begin(); }
2982218822Sdim
2983218822Sdim  /// pointer_end - Past the last pointer type found;
2984218822Sdim  iterator pointer_end() { return PointerTypes.end(); }
2985218822Sdim
2986218822Sdim  /// member_pointer_begin - First member pointer type found;
2987218822Sdim  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2988218822Sdim
2989218822Sdim  /// member_pointer_end - Past the last member pointer type found;
2990218822Sdim  iterator member_pointer_end() { return MemberPointerTypes.end(); }
2991218822Sdim
2992218822Sdim  /// enumeration_begin - First enumeration type found;
2993218822Sdim  iterator enumeration_begin() { return EnumerationTypes.begin(); }
2994218822Sdim
2995218822Sdim  /// enumeration_end - Past the last enumeration type found;
2996218822Sdim  iterator enumeration_end() { return EnumerationTypes.end(); }
2997218822Sdim};
2998218822Sdim
2999218822Sdim/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
3000218822Sdim/// the set of pointer types along with any more-qualified variants of
3001218822Sdim/// that type. For example, if @p Ty is "int const *", this routine
3002218822Sdim/// will add "int const *", "int const volatile *", "int const
3003218822Sdim/// restrict *", and "int const volatile restrict *" to the set of
3004218822Sdim/// pointer types. Returns true if the add of @p Ty itself succeeded,
3005218822Sdim/// false otherwise.
3006218822Sdim///
3007218822Sdim/// FIXME: what to do about extended qualifiers?
3008218822Sdimbool
3009218822SdimBuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3010218822Sdim                                             const Qualifiers &VisibleQuals) {
3011218822Sdim
3012218822Sdim  // Insert this type.
3013218822Sdim  if (!PointerTypes.insert(Ty))
3014218822Sdim    return false;
3015218822Sdim
3016218822Sdim  const PointerType *PointerTy = Ty->getAs<PointerType>();
3017218822Sdim  assert(PointerTy && "type was not a pointer type!");
3018218822Sdim
3019218822Sdim  QualType PointeeTy = PointerTy->getPointeeType();
3020218822Sdim  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3021218822Sdim  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
3022218822Sdim    BaseCVR = Array->getElementType().getCVRQualifiers();
3023218822Sdim  bool hasVolatile = VisibleQuals.hasVolatile();
3024218822Sdim  bool hasRestrict = VisibleQuals.hasRestrict();
3025218822Sdim
3026218822Sdim  // Iterate through all strict supersets of BaseCVR.
3027218822Sdim  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3028218822Sdim    if ((CVR | BaseCVR) != CVR) continue;
3029218822Sdim    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3030218822Sdim    // in the types.
3031218822Sdim    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3032218822Sdim    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
3033218822Sdim    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3034218822Sdim    PointerTypes.insert(Context.getPointerType(QPointeeTy));
3035218822Sdim  }
3036218822Sdim
3037218822Sdim  return true;
3038218822Sdim}
3039218822Sdim
3040218822Sdim/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3041218822Sdim/// to the set of pointer types along with any more-qualified variants of
3042218822Sdim/// that type. For example, if @p Ty is "int const *", this routine
3043218822Sdim/// will add "int const *", "int const volatile *", "int const
3044218822Sdim/// restrict *", and "int const volatile restrict *" to the set of
3045218822Sdim/// pointer types. Returns true if the add of @p Ty itself succeeded,
3046218822Sdim/// false otherwise.
3047218822Sdim///
3048218822Sdim/// FIXME: what to do about extended qualifiers?
3049218822Sdimbool
3050218822SdimBuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3051218822Sdim    QualType Ty) {
3052218822Sdim  // Insert this type.
3053218822Sdim  if (!MemberPointerTypes.insert(Ty))
3054218822Sdim    return false;
305589857Sobrien
305689857Sobrien  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
305789857Sobrien  assert(PointerTy && "type was not a member pointer type!");
305889857Sobrien
305989857Sobrien  QualType PointeeTy = PointerTy->getPointeeType();
306089857Sobrien  const Type *ClassTy = PointerTy->getClass();
306189857Sobrien
306289857Sobrien  // Iterate through all strict supersets of the pointee type's CVR
306389857Sobrien  // qualifiers.
306489857Sobrien  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
306589857Sobrien  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
306689857Sobrien    if ((CVR | BaseCVR) != CVR) continue;
306789857Sobrien
306889857Sobrien    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
306989857Sobrien    MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
307089857Sobrien  }
307189857Sobrien
307289857Sobrien  return true;
307389857Sobrien}
307489857Sobrien
307589857Sobrien/// AddTypesConvertedFrom - Add each of the types to which the type @p
307689857Sobrien/// Ty can be implicit converted to the given set of @p Types. We're
307789857Sobrien/// primarily interested in pointer types and enumeration types. We also
307889857Sobrien/// take member pointer types, for the conditional operator.
307989857Sobrien/// AllowUserConversions is true if we should look at the conversion
308089857Sobrien/// functions of a class type, and AllowExplicitConversions if we
308189857Sobrien/// should also include the explicit conversion functions of a class
308289857Sobrien/// type.
308389857Sobrienvoid
308489857SobrienBuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
308589857Sobrien                                               SourceLocation Loc,
308689857Sobrien                                               bool AllowUserConversions,
308789857Sobrien                                               bool AllowExplicitConversions,
308889857Sobrien                                               const Qualifiers &VisibleQuals) {
308989857Sobrien  // Only deal with canonical types.
309089857Sobrien  Ty = Context.getCanonicalType(Ty);
309189857Sobrien
309289857Sobrien  // Look through reference types; they aren't part of the type of an
309389857Sobrien  // expression for the purposes of conversions.
309489857Sobrien  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3095130561Sobrien    Ty = RefTy->getPointeeType();
309689857Sobrien
309789857Sobrien  // We don't care about qualifiers on the type.
309889857Sobrien  Ty = Ty.getLocalUnqualifiedType();
309989857Sobrien
310089857Sobrien  // If we're dealing with an array type, decay to the pointer.
310189857Sobrien  if (Ty->isArrayType())
310289857Sobrien    Ty = SemaRef.Context.getArrayDecayedType(Ty);
310389857Sobrien
310489857Sobrien  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
310589857Sobrien    QualType PointeeTy = PointerTy->getPointeeType();
310689857Sobrien
310789857Sobrien    // Insert our type, and its more-qualified variants, into the set
310889857Sobrien    // of types.
310989857Sobrien    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
311089857Sobrien      return;
311189857Sobrien  } else if (Ty->isMemberPointerType()) {
311289857Sobrien    // Member pointers are far easier, since the pointee can't be converted.
311389857Sobrien    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
311489857Sobrien      return;
311589857Sobrien  } else if (Ty->isEnumeralType()) {
311689857Sobrien    EnumerationTypes.insert(Ty);
311789857Sobrien  } else if (AllowUserConversions) {
311889857Sobrien    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
311989857Sobrien      if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
312089857Sobrien        // No conversion functions in incomplete types.
3121218822Sdim        return;
312289857Sobrien      }
3123218822Sdim
3124218822Sdim      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3125218822Sdim      OverloadedFunctionDecl *Conversions
3126218822Sdim        = ClassDecl->getVisibleConversionFunctions();
312789857Sobrien      for (OverloadedFunctionDecl::function_iterator Func
312889857Sobrien             = Conversions->function_begin();
312989857Sobrien           Func != Conversions->function_end(); ++Func) {
313089857Sobrien        CXXConversionDecl *Conv;
313189857Sobrien        FunctionTemplateDecl *ConvTemplate;
313289857Sobrien        GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
313389857Sobrien
313489857Sobrien        // Skip conversion function templates; they don't tell us anything
313589857Sobrien        // about which builtin types we can convert to.
313689857Sobrien        if (ConvTemplate)
313789857Sobrien          continue;
313889857Sobrien
313989857Sobrien        if (AllowExplicitConversions || !Conv->isExplicit()) {
314089857Sobrien          AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
314189857Sobrien                                VisibleQuals);
314289857Sobrien        }
314389857Sobrien      }
314489857Sobrien    }
314589857Sobrien  }
314689857Sobrien}
3147130561Sobrien
3148130561Sobrien/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3149130561Sobrien/// the volatile- and non-volatile-qualified assignment operators for the
3150130561Sobrien/// given type to the candidate set.
3151130561Sobrienstatic void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3152130561Sobrien                                                   QualType T,
3153130561Sobrien                                                   Expr **Args,
3154130561Sobrien                                                   unsigned NumArgs,
3155130561Sobrien                                    OverloadCandidateSet &CandidateSet) {
3156130561Sobrien  QualType ParamTypes[2];
3157130561Sobrien
3158130561Sobrien  // T& operator=(T&, T)
3159130561Sobrien  ParamTypes[0] = S.Context.getLValueReferenceType(T);
3160130561Sobrien  ParamTypes[1] = T;
3161130561Sobrien  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3162130561Sobrien                        /*IsAssignmentOperator=*/true);
3163130561Sobrien
3164130561Sobrien  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3165130561Sobrien    // volatile T& operator=(volatile T&, T)
3166130561Sobrien    ParamTypes[0]
3167130561Sobrien      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3168130561Sobrien    ParamTypes[1] = T;
3169130561Sobrien    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3170130561Sobrien                          /*IsAssignmentOperator=*/true);
3171130561Sobrien  }
3172130561Sobrien}
3173130561Sobrien
3174130561Sobrien/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3175130561Sobrien/// if any, found in visible type conversion functions found in ArgExpr's type.
3176130561Sobrienstatic  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3177130561Sobrien    Qualifiers VRQuals;
3178130561Sobrien    const RecordType *TyRec;
3179130561Sobrien    if (const MemberPointerType *RHSMPType =
3180130561Sobrien        ArgExpr->getType()->getAs<MemberPointerType>())
3181130561Sobrien      TyRec = cast<RecordType>(RHSMPType->getClass());
3182130561Sobrien    else
3183130561Sobrien      TyRec = ArgExpr->getType()->getAs<RecordType>();
3184130561Sobrien    if (!TyRec) {
3185130561Sobrien      // Just to be safe, assume the worst case.
3186130561Sobrien      VRQuals.addVolatile();
3187130561Sobrien      VRQuals.addRestrict();
3188130561Sobrien      return VRQuals;
3189130561Sobrien    }
319089857Sobrien
3191130561Sobrien    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3192130561Sobrien    OverloadedFunctionDecl *Conversions =
319389857Sobrien      ClassDecl->getVisibleConversionFunctions();
3194130561Sobrien
3195104834Sobrien    for (OverloadedFunctionDecl::function_iterator Func
3196104834Sobrien         = Conversions->function_begin();
3197130561Sobrien         Func != Conversions->function_end(); ++Func) {
319889857Sobrien      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3199130561Sobrien        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3200130561Sobrien        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3201130561Sobrien          CanTy = ResTypeRef->getPointeeType();
3202130561Sobrien        // Need to go down the pointer/mempointer chain and add qualifiers
3203130561Sobrien        // as see them.
3204130561Sobrien        bool done = false;
3205130561Sobrien        while (!done) {
3206130561Sobrien          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3207130561Sobrien            CanTy = ResTypePtr->getPointeeType();
3208130561Sobrien          else if (const MemberPointerType *ResTypeMPtr =
3209130561Sobrien                CanTy->getAs<MemberPointerType>())
3210130561Sobrien            CanTy = ResTypeMPtr->getPointeeType();
3211130561Sobrien          else
3212130561Sobrien            done = true;
3213130561Sobrien          if (CanTy.isVolatileQualified())
3214130561Sobrien            VRQuals.addVolatile();
3215130561Sobrien          if (CanTy.isRestrictQualified())
3216104834Sobrien            VRQuals.addRestrict();
3217104834Sobrien          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3218104834Sobrien            return VRQuals;
321989857Sobrien        }
3220104834Sobrien      }
3221104834Sobrien    }
3222104834Sobrien    return VRQuals;
3223104834Sobrien}
3224104834Sobrien
3225104834Sobrien/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3226104834Sobrien/// operator overloads to the candidate set (C++ [over.built]), based
3227104834Sobrien/// on the operator @p Op and the arguments given. For example, if the
3228104834Sobrien/// operator is a binary '+', this routine might add "int
3229107492Sobrien/// operator+(int, int)" to cover integer addition.
3230107492Sobrienvoid
3231104834SobrienSema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3232104834Sobrien                                   SourceLocation OpLoc,
3233104834Sobrien                                   Expr **Args, unsigned NumArgs,
3234104834Sobrien                                   OverloadCandidateSet& CandidateSet) {
3235218822Sdim  // The set of "promoted arithmetic types", which are the arithmetic
3236218822Sdim  // types are that preserved by promotion (C++ [over.built]p2). Note
3237218822Sdim  // that the first few of these types are the promoted integral
3238218822Sdim  // types; these types need to be first.
3239107492Sobrien  // FIXME: What about complex?
3240104834Sobrien  const unsigned FirstIntegralType = 0;
3241107492Sobrien  const unsigned LastIntegralType = 13;
3242107492Sobrien  const unsigned FirstPromotedIntegralType = 7,
3243104834Sobrien                 LastPromotedIntegralType = 13;
3244107492Sobrien  const unsigned FirstPromotedArithmeticType = 7,
3245104834Sobrien                 LastPromotedArithmeticType = 16;
3246130561Sobrien  const unsigned NumArithmeticTypes = 16;
3247130561Sobrien  QualType ArithmeticTypes[NumArithmeticTypes] = {
3248130561Sobrien    Context.BoolTy, Context.CharTy, Context.WCharTy,
3249130561Sobrien// FIXME:   Context.Char16Ty, Context.Char32Ty,
3250130561Sobrien    Context.SignedCharTy, Context.ShortTy,
3251130561Sobrien    Context.UnsignedCharTy, Context.UnsignedShortTy,
3252130561Sobrien    Context.IntTy, Context.LongTy, Context.LongLongTy,
3253130561Sobrien    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3254130561Sobrien    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3255130561Sobrien  };
3256130561Sobrien  assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3257130561Sobrien         "Invalid first promoted integral type");
3258130561Sobrien  assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3259130561Sobrien           == Context.UnsignedLongLongTy &&
3260130561Sobrien         "Invalid last promoted integral type");
3261130561Sobrien  assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3262130561Sobrien         "Invalid first promoted arithmetic type");
3263104834Sobrien  assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3264104834Sobrien            == Context.LongDoubleTy &&
3265104834Sobrien         "Invalid last promoted arithmetic type");
3266104834Sobrien
3267104834Sobrien  // Find all of the types that the arguments can convert to, but only
3268130561Sobrien  // if the operator we're looking at has built-in operator candidates
3269104834Sobrien  // that make use of these types.
3270130561Sobrien  Qualifiers VisibleTypeConversionsQuals;
3271104834Sobrien  VisibleTypeConversionsQuals.addConst();
3272104834Sobrien  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3273104834Sobrien    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3274104834Sobrien
3275104834Sobrien  BuiltinCandidateTypeSet CandidateTypes(*this);
3276104834Sobrien  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3277104834Sobrien      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3278104834Sobrien      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3279130561Sobrien      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3280130561Sobrien      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3281104834Sobrien      (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3282104834Sobrien    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3283104834Sobrien      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3284104834Sobrien                                           OpLoc,
3285104834Sobrien                                           true,
3286104834Sobrien                                           (Op == OO_Exclaim ||
3287104834Sobrien                                            Op == OO_AmpAmp ||
3288104834Sobrien                                            Op == OO_PipePipe),
3289104834Sobrien                                           VisibleTypeConversionsQuals);
3290104834Sobrien  }
3291104834Sobrien
3292104834Sobrien  bool isComparison = false;
3293104834Sobrien  switch (Op) {
3294104834Sobrien  case OO_None:
3295130561Sobrien  case NUM_OVERLOADED_OPERATORS:
3296130561Sobrien    assert(false && "Expected an overloaded operator");
3297130561Sobrien    break;
3298104834Sobrien
3299104834Sobrien  case OO_Star: // '*' is either unary or binary
3300104834Sobrien    if (NumArgs == 1)
3301104834Sobrien      goto UnaryStar;
3302104834Sobrien    else
3303104834Sobrien      goto BinaryStar;
3304104834Sobrien    break;
3305104834Sobrien
3306104834Sobrien  case OO_Plus: // '+' is either unary or binary
3307104834Sobrien    if (NumArgs == 1)
3308218822Sdim      goto UnaryPlus;
3309104834Sobrien    else
3310104834Sobrien      goto BinaryPlus;
3311104834Sobrien    break;
3312104834Sobrien
3313104834Sobrien  case OO_Minus: // '-' is either unary or binary
3314104834Sobrien    if (NumArgs == 1)
331589857Sobrien      goto UnaryMinus;
331689857Sobrien    else
331789857Sobrien      goto BinaryMinus;
331889857Sobrien    break;
3319218822Sdim
3320218822Sdim  case OO_Amp: // '&' is either unary or binary
3321218822Sdim    if (NumArgs == 1)
3322218822Sdim      goto UnaryAmp;
3323104834Sobrien    else
3324218822Sdim      goto BinaryAmp;
3325218822Sdim
3326218822Sdim  case OO_PlusPlus:
3327218822Sdim  case OO_MinusMinus:
332889857Sobrien    // C++ [over.built]p3:
332989857Sobrien    //
333089857Sobrien    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3331104834Sobrien    //   is either volatile or empty, there exist candidate operator
3332218822Sdim    //   functions of the form
3333104834Sobrien    //
333489857Sobrien    //       VQ T&      operator++(VQ T&);
333589857Sobrien    //       T          operator++(VQ T&, int);
333689857Sobrien    //
3337218822Sdim    // C++ [over.built]p4:
3338130561Sobrien    //
3339218822Sdim    //   For every pair (T, VQ), where T is an arithmetic type other
3340218822Sdim    //   than bool, and VQ is either volatile or empty, there exist
3341218822Sdim    //   candidate operator functions of the form
3342130561Sobrien    //
3343130561Sobrien    //       VQ T&      operator--(VQ T&);
3344218822Sdim    //       T          operator--(VQ T&, int);
3345218822Sdim    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3346218822Sdim         Arith < NumArithmeticTypes; ++Arith) {
3347130561Sobrien      QualType ArithTy = ArithmeticTypes[Arith];
3348130561Sobrien      QualType ParamTypes[2]
3349130561Sobrien        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3350130561Sobrien
3351130561Sobrien      // Non-volatile version.
3352130561Sobrien      if (NumArgs == 1)
3353130561Sobrien        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3354130561Sobrien      else
3355130561Sobrien        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3356130561Sobrien      // heuristic to reduce number of builtin candidates in the set.
3357130561Sobrien      // Add volatile version only if there are conversions to a volatile type.
3358130561Sobrien      if (VisibleTypeConversionsQuals.hasVolatile()) {
3359130561Sobrien        // Volatile version
3360130561Sobrien        ParamTypes[0]
3361130561Sobrien          = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3362130561Sobrien        if (NumArgs == 1)
336389857Sobrien          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
336489857Sobrien        else
336589857Sobrien          AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
336689857Sobrien      }
336789857Sobrien    }
336889857Sobrien
336989857Sobrien    // C++ [over.built]p5:
337089857Sobrien    //
3371104834Sobrien    //   For every pair (T, VQ), where T is a cv-qualified or
3372104834Sobrien    //   cv-unqualified object type, and VQ is either volatile or
3373104834Sobrien    //   empty, there exist candidate operator functions of the form
3374104834Sobrien    //
3375104834Sobrien    //       T*VQ&      operator++(T*VQ&);
3376104834Sobrien    //       T*VQ&      operator--(T*VQ&);
3377104834Sobrien    //       T*         operator++(T*VQ&, int);
3378104834Sobrien    //       T*         operator--(T*VQ&, int);
3379104834Sobrien    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3380104834Sobrien         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3381130561Sobrien      // Skip pointer types that aren't pointers to object types.
3382130561Sobrien      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3383104834Sobrien        continue;
3384104834Sobrien
3385104834Sobrien      QualType ParamTypes[2] = {
3386104834Sobrien        Context.getLValueReferenceType(*Ptr), Context.IntTy
3387104834Sobrien      };
3388104834Sobrien
3389104834Sobrien      // Without volatile
3390104834Sobrien      if (NumArgs == 1)
3391130561Sobrien        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3392130561Sobrien      else
3393104834Sobrien        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3394104834Sobrien
3395130561Sobrien      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3396130561Sobrien          VisibleTypeConversionsQuals.hasVolatile()) {
3397130561Sobrien        // With volatile
3398130561Sobrien        ParamTypes[0]
3399130561Sobrien          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3400130561Sobrien        if (NumArgs == 1)
3401130561Sobrien          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3402104834Sobrien        else
3403130561Sobrien          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3404218822Sdim      }
3405218822Sdim    }
3406218822Sdim    break;
3407130561Sobrien
3408104834Sobrien  UnaryStar:
3409104834Sobrien    // C++ [over.built]p6:
341089857Sobrien    //   For every cv-qualified or cv-unqualified object type T, there
3411130561Sobrien    //   exist candidate operator functions of the form
3412130561Sobrien    //
3413130561Sobrien    //       T&         operator*(T*);
3414130561Sobrien    //
3415130561Sobrien    // C++ [over.built]p7:
3416130561Sobrien    //   For every function type T, there exist candidate operator
341792828Sobrien    //   functions of the form
3418130561Sobrien    //       T&         operator*(T*);
3419130561Sobrien    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
342089857Sobrien         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3421218822Sdim      QualType ParamTy = *Ptr;
3422218822Sdim      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3423218822Sdim      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3424130561Sobrien                          &ParamTy, Args, 1, CandidateSet);
3425130561Sobrien    }
3426130561Sobrien    break;
3427130561Sobrien
3428218822Sdim  UnaryPlus:
3429218822Sdim    // C++ [over.built]p8:
3430218822Sdim    //   For every type T, there exist candidate operator functions of
3431130561Sobrien    //   the form
3432218822Sdim    //
3433130561Sobrien    //       T*         operator+(T*);
3434218822Sdim    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3435218822Sdim         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3436218822Sdim      QualType ParamTy = *Ptr;
3437218822Sdim      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
343889857Sobrien    }
3439218822Sdim
344089857Sobrien    // Fall through
3441218822Sdim
3442218822Sdim  UnaryMinus:
3443104834Sobrien    // C++ [over.built]p9:
3444104834Sobrien    //  For every promoted arithmetic type T, there exist candidate
3445104834Sobrien    //  operator functions of the form
3446104834Sobrien    //
344789857Sobrien    //       T         operator+(T);
344889857Sobrien    //       T         operator-(T);
344989857Sobrien    for (unsigned Arith = FirstPromotedArithmeticType;
345089857Sobrien         Arith < LastPromotedArithmeticType; ++Arith) {
3451218822Sdim      QualType ArithTy = ArithmeticTypes[Arith];
3452218822Sdim      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3453218822Sdim    }
3454218822Sdim    break;
3455218822Sdim
3456218822Sdim  case OO_Tilde:
345789857Sobrien    // C++ [over.built]p10:
345889857Sobrien    //   For every promoted integral type T, there exist candidate
345989857Sobrien    //   operator functions of the form
346089857Sobrien    //
346189857Sobrien    //        T         operator~(T);
3462104834Sobrien    for (unsigned Int = FirstPromotedIntegralType;
3463104834Sobrien         Int < LastPromotedIntegralType; ++Int) {
3464104834Sobrien      QualType IntTy = ArithmeticTypes[Int];
3465104834Sobrien      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3466104834Sobrien    }
3467104834Sobrien    break;
3468104834Sobrien
3469104834Sobrien  case OO_New:
3470104834Sobrien  case OO_Delete:
3471104834Sobrien  case OO_Array_New:
3472104834Sobrien  case OO_Array_Delete:
3473130561Sobrien  case OO_Call:
3474130561Sobrien    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3475130561Sobrien    break;
3476104834Sobrien
3477104834Sobrien  case OO_Comma:
3478104834Sobrien  UnaryAmp:
3479104834Sobrien  case OO_Arrow:
3480104834Sobrien    // C++ [over.match.oper]p3:
3481104834Sobrien    //   -- For the operator ',', the unary operator '&', or the
3482104834Sobrien    //      operator '->', the built-in candidates set is empty.
3483104834Sobrien    break;
3484104834Sobrien
3485104834Sobrien  case OO_EqualEqual:
3486104834Sobrien  case OO_ExclaimEqual:
3487104834Sobrien    // C++ [over.match.oper]p16:
3488104834Sobrien    //   For every pointer to member type T, there exist candidate operator
3489104834Sobrien    //   functions of the form
3490104834Sobrien    //
3491104834Sobrien    //        bool operator==(T,T);
3492104834Sobrien    //        bool operator!=(T,T);
3493104834Sobrien    for (BuiltinCandidateTypeSet::iterator
3494130561Sobrien           MemPtr = CandidateTypes.member_pointer_begin(),
3495104834Sobrien           MemPtrEnd = CandidateTypes.member_pointer_end();
3496104834Sobrien         MemPtr != MemPtrEnd;
3497104834Sobrien         ++MemPtr) {
3498104834Sobrien      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3499104834Sobrien      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3500104834Sobrien    }
3501104834Sobrien
3502104834Sobrien    // Fall through
3503104834Sobrien
3504104834Sobrien  case OO_Less:
3505104834Sobrien  case OO_Greater:
3506104834Sobrien  case OO_LessEqual:
3507104834Sobrien  case OO_GreaterEqual:
3508104834Sobrien    // C++ [over.built]p15:
3509130561Sobrien    //
3510130561Sobrien    //   For every pointer or enumeration type T, there exist
3511130561Sobrien    //   candidate operator functions of the form
3512104834Sobrien    //
3513104834Sobrien    //        bool       operator<(T, T);
3514104834Sobrien    //        bool       operator>(T, T);
3515104834Sobrien    //        bool       operator<=(T, T);
3516104834Sobrien    //        bool       operator>=(T, T);
3517104834Sobrien    //        bool       operator==(T, T);
3518104834Sobrien    //        bool       operator!=(T, T);
3519104834Sobrien    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3520104834Sobrien         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3521104834Sobrien      QualType ParamTypes[2] = { *Ptr, *Ptr };
3522104834Sobrien      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3523104834Sobrien    }
3524104834Sobrien    for (BuiltinCandidateTypeSet::iterator Enum
3525104834Sobrien           = CandidateTypes.enumeration_begin();
3526104834Sobrien         Enum != CandidateTypes.enumeration_end(); ++Enum) {
3527104834Sobrien      QualType ParamTypes[2] = { *Enum, *Enum };
3528104834Sobrien      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3529104834Sobrien    }
3530104834Sobrien
3531104834Sobrien    // Fall through.
3532104834Sobrien    isComparison = true;
3533104834Sobrien
3534104834Sobrien  BinaryPlus:
3535104834Sobrien  BinaryMinus:
3536104834Sobrien    if (!isComparison) {
353789857Sobrien      // We didn't fall through, so we must have OO_Plus or OO_Minus.
353889857Sobrien
353989857Sobrien      // C++ [over.built]p13:
3540130561Sobrien      //
3541130561Sobrien      //   For every cv-qualified or cv-unqualified object type T
3542130561Sobrien      //   there exist candidate operator functions of the form
354389857Sobrien      //
354489857Sobrien      //      T*         operator+(T*, ptrdiff_t);
354589857Sobrien      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
354689857Sobrien      //      T*         operator-(T*, ptrdiff_t);
354789857Sobrien      //      T*         operator+(ptrdiff_t, T*);
354889857Sobrien      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
354989857Sobrien      //
355089857Sobrien      // C++ [over.built]p14:
355189857Sobrien      //
355289857Sobrien      //   For every T, where T is a pointer to object type, there
355389857Sobrien      //   exist candidate operator functions of the form
355489857Sobrien      //
355589857Sobrien      //      ptrdiff_t  operator-(T, T);
355689857Sobrien      for (BuiltinCandidateTypeSet::iterator Ptr
355789857Sobrien             = CandidateTypes.pointer_begin();
355889857Sobrien           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3559218822Sdim        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3560218822Sdim
3561218822Sdim        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3562218822Sdim        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3563218822Sdim
3564218822Sdim        if (Op == OO_Plus) {
3565218822Sdim          // T* operator+(ptrdiff_t, T*);
3566218822Sdim          ParamTypes[0] = ParamTypes[1];
3567218822Sdim          ParamTypes[1] = *Ptr;
3568218822Sdim          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3569218822Sdim        } else {
3570218822Sdim          // ptrdiff_t operator-(T, T);
3571218822Sdim          ParamTypes[1] = *Ptr;
3572218822Sdim          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3573218822Sdim                              Args, 2, CandidateSet);
3574218822Sdim        }
3575218822Sdim      }
3576218822Sdim    }
3577218822Sdim    // Fall through
3578218822Sdim
3579218822Sdim  case OO_Slash:
3580218822Sdim  BinaryStar:
3581218822Sdim  Conditional:
3582218822Sdim    // C++ [over.built]p12:
3583218822Sdim    //
3584218822Sdim    //   For every pair of promoted arithmetic types L and R, there
3585218822Sdim    //   exist candidate operator functions of the form
3586218822Sdim    //
358789857Sobrien    //        LR         operator*(L, R);
358889857Sobrien    //        LR         operator/(L, R);
358989857Sobrien    //        LR         operator+(L, R);
359089857Sobrien    //        LR         operator-(L, R);
359189857Sobrien    //        bool       operator<(L, R);
359289857Sobrien    //        bool       operator>(L, R);
359389857Sobrien    //        bool       operator<=(L, R);
359489857Sobrien    //        bool       operator>=(L, R);
3595130561Sobrien    //        bool       operator==(L, R);
359689857Sobrien    //        bool       operator!=(L, R);
359789857Sobrien    //
359889857Sobrien    //   where LR is the result of the usual arithmetic conversions
359989857Sobrien    //   between types L and R.
3600130561Sobrien    //
360189857Sobrien    // C++ [over.built]p24:
360289857Sobrien    //
360389857Sobrien    //   For every pair of promoted arithmetic types L and R, there exist
3604218822Sdim    //   candidate operator functions of the form
3605218822Sdim    //
360689857Sobrien    //        LR       operator?(bool, L, R);
3607104834Sobrien    //
360889857Sobrien    //   where LR is the result of the usual arithmetic conversions
360989857Sobrien    //   between types L and R.
361089857Sobrien    // Our candidates ignore the first parameter.
3611104834Sobrien    for (unsigned Left = FirstPromotedArithmeticType;
3612218822Sdim         Left < LastPromotedArithmeticType; ++Left) {
3613218822Sdim      for (unsigned Right = FirstPromotedArithmeticType;
3614104834Sobrien           Right < LastPromotedArithmeticType; ++Right) {
3615104834Sobrien        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3616104834Sobrien        QualType Result
3617218822Sdim          = isComparison
3618218822Sdim          ? Context.BoolTy
3619104834Sobrien          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3620104834Sobrien        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3621130561Sobrien      }
3622130561Sobrien    }
3623130561Sobrien    break;
3624130561Sobrien
3625218822Sdim  case OO_Percent:
3626218822Sdim  BinaryAmp:
3627218822Sdim  case OO_Caret:
3628218822Sdim  case OO_Pipe:
3629218822Sdim  case OO_LessLess:
3630218822Sdim  case OO_GreaterGreater:
3631218822Sdim    // C++ [over.built]p17:
3632218822Sdim    //
363389857Sobrien    //   For every pair of promoted integral types L and R, there
363489857Sobrien    //   exist candidate operator functions of the form
363589857Sobrien    //
363689857Sobrien    //      LR         operator%(L, R);
3637104834Sobrien    //      LR         operator&(L, R);
3638104834Sobrien    //      LR         operator^(L, R);
3639104834Sobrien    //      LR         operator|(L, R);
3640130561Sobrien    //      L          operator<<(L, R);
3641104834Sobrien    //      L          operator>>(L, R);
3642104834Sobrien    //
3643104834Sobrien    //   where LR is the result of the usual arithmetic conversions
3644104834Sobrien    //   between types L and R.
3645104834Sobrien    for (unsigned Left = FirstPromotedIntegralType;
3646104834Sobrien         Left < LastPromotedIntegralType; ++Left) {
3647104834Sobrien      for (unsigned Right = FirstPromotedIntegralType;
3648104834Sobrien           Right < LastPromotedIntegralType; ++Right) {
3649130561Sobrien        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3650130561Sobrien        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3651130561Sobrien            ? LandR[0]
3652130561Sobrien            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3653130561Sobrien        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3654130561Sobrien      }
3655130561Sobrien    }
3656130561Sobrien    break;
3657130561Sobrien
3658130561Sobrien  case OO_Equal:
3659130561Sobrien    // C++ [over.built]p20:
3660130561Sobrien    //
3661130561Sobrien    //   For every pair (T, VQ), where T is an enumeration or
3662130561Sobrien    //   pointer to member type and VQ is either volatile or
3663130561Sobrien    //   empty, there exist candidate operator functions of the form
3664130561Sobrien    //
3665130561Sobrien    //        VQ T&      operator=(VQ T&, T);
3666104834Sobrien    for (BuiltinCandidateTypeSet::iterator
3667104834Sobrien           Enum = CandidateTypes.enumeration_begin(),
3668104834Sobrien           EnumEnd = CandidateTypes.enumeration_end();
3669130561Sobrien         Enum != EnumEnd; ++Enum)
3670130561Sobrien      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3671130561Sobrien                                             CandidateSet);
3672130561Sobrien    for (BuiltinCandidateTypeSet::iterator
3673104834Sobrien           MemPtr = CandidateTypes.member_pointer_begin(),
3674104834Sobrien         MemPtrEnd = CandidateTypes.member_pointer_end();
3675104834Sobrien         MemPtr != MemPtrEnd; ++MemPtr)
3676104834Sobrien      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3677104834Sobrien                                             CandidateSet);
3678104834Sobrien      // Fall through.
3679104834Sobrien
3680104834Sobrien  case OO_PlusEqual:
3681104834Sobrien  case OO_MinusEqual:
3682104834Sobrien    // C++ [over.built]p19:
3683104834Sobrien    //
3684104834Sobrien    //   For every pair (T, VQ), where T is any type and VQ is either
3685104834Sobrien    //   volatile or empty, there exist candidate operator functions
3686218822Sdim    //   of the form
3687218822Sdim    //
3688218822Sdim    //        T*VQ&      operator=(T*VQ&, T*);
3689218822Sdim    //
3690218822Sdim    // C++ [over.built]p21:
3691218822Sdim    //
3692218822Sdim    //   For every pair (T, VQ), where T is a cv-qualified or
3693104834Sobrien    //   cv-unqualified object type and VQ is either volatile or
3694104834Sobrien    //   empty, there exist candidate operator functions of the form
3695104834Sobrien    //
3696130561Sobrien    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3697104834Sobrien    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3698218822Sdim    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3699218822Sdim         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3700218822Sdim      QualType ParamTypes[2];
3701218822Sdim      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3702218822Sdim
3703218822Sdim      // non-volatile version
3704218822Sdim      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3705218822Sdim      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3706104834Sobrien                          /*IsAssigmentOperator=*/Op == OO_Equal);
3707218822Sdim
3708218822Sdim      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3709104834Sobrien          VisibleTypeConversionsQuals.hasVolatile()) {
3710104834Sobrien        // volatile version
3711104834Sobrien        ParamTypes[0]
3712104834Sobrien          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3713104834Sobrien        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3714104834Sobrien                            /*IsAssigmentOperator=*/Op == OO_Equal);
3715104834Sobrien      }
3716130561Sobrien    }
3717130561Sobrien    // Fall through.
3718218822Sdim
3719130561Sobrien  case OO_StarEqual:
3720130561Sobrien  case OO_SlashEqual:
3721104834Sobrien    // C++ [over.built]p18:
3722104834Sobrien    //
3723104834Sobrien    //   For every triple (L, VQ, R), where L is an arithmetic type,
3724104834Sobrien    //   VQ is either volatile or empty, and R is a promoted
3725104834Sobrien    //   arithmetic type, there exist candidate operator functions of
3726104834Sobrien    //   the form
3727104834Sobrien    //
3728104834Sobrien    //        VQ L&      operator=(VQ L&, R);
3729104834Sobrien    //        VQ L&      operator*=(VQ L&, R);
3730104834Sobrien    //        VQ L&      operator/=(VQ L&, R);
3731104834Sobrien    //        VQ L&      operator+=(VQ L&, R);
3732218822Sdim    //        VQ L&      operator-=(VQ L&, R);
3733218822Sdim    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3734218822Sdim      for (unsigned Right = FirstPromotedArithmeticType;
3735104834Sobrien           Right < LastPromotedArithmeticType; ++Right) {
3736218822Sdim        QualType ParamTypes[2];
3737104834Sobrien        ParamTypes[1] = ArithmeticTypes[Right];
3738104834Sobrien
3739104834Sobrien        // Add this built-in operator as a candidate (VQ is empty).
3740104834Sobrien        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3741104834Sobrien        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3742104834Sobrien                            /*IsAssigmentOperator=*/Op == OO_Equal);
3743104834Sobrien
3744104834Sobrien        // Add this built-in operator as a candidate (VQ is 'volatile').
3745104834Sobrien        if (VisibleTypeConversionsQuals.hasVolatile()) {
3746104834Sobrien          ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3747130561Sobrien          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3748104834Sobrien          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3749218822Sdim                              /*IsAssigmentOperator=*/Op == OO_Equal);
3750104834Sobrien        }
3751104834Sobrien      }
3752104834Sobrien    }
3753104834Sobrien    break;
3754104834Sobrien
3755104834Sobrien  case OO_PercentEqual:
3756104834Sobrien  case OO_LessLessEqual:
3757104834Sobrien  case OO_GreaterGreaterEqual:
3758104834Sobrien  case OO_AmpEqual:
3759104834Sobrien  case OO_CaretEqual:
3760104834Sobrien  case OO_PipeEqual:
3761130561Sobrien    // C++ [over.built]p22:
3762130561Sobrien    //
3763130561Sobrien    //   For every triple (L, VQ, R), where L is an integral type, VQ
3764104834Sobrien    //   is either volatile or empty, and R is a promoted integral
3765104834Sobrien    //   type, there exist candidate operator functions of the form
3766104834Sobrien    //
3767104834Sobrien    //        VQ L&       operator%=(VQ L&, R);
3768104834Sobrien    //        VQ L&       operator<<=(VQ L&, R);
3769104834Sobrien    //        VQ L&       operator>>=(VQ L&, R);
3770104834Sobrien    //        VQ L&       operator&=(VQ L&, R);
3771104834Sobrien    //        VQ L&       operator^=(VQ L&, R);
3772104834Sobrien    //        VQ L&       operator|=(VQ L&, R);
3773104834Sobrien    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3774104834Sobrien      for (unsigned Right = FirstPromotedIntegralType;
3775104834Sobrien           Right < LastPromotedIntegralType; ++Right) {
3776104834Sobrien        QualType ParamTypes[2];
3777104834Sobrien        ParamTypes[1] = ArithmeticTypes[Right];
3778104834Sobrien
3779104834Sobrien        // Add this built-in operator as a candidate (VQ is empty).
3780104834Sobrien        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3781104834Sobrien        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3782104834Sobrien        if (VisibleTypeConversionsQuals.hasVolatile()) {
3783104834Sobrien          // Add this built-in operator as a candidate (VQ is 'volatile').
3784104834Sobrien          ParamTypes[0] = ArithmeticTypes[Left];
3785104834Sobrien          ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3786104834Sobrien          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3787104834Sobrien          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3788104834Sobrien        }
3789104834Sobrien      }
3790104834Sobrien    }
3791104834Sobrien    break;
3792104834Sobrien
3793104834Sobrien  case OO_Exclaim: {
3794104834Sobrien    // C++ [over.operator]p23:
3795104834Sobrien    //
3796104834Sobrien    //   There also exist candidate operator functions of the form
3797104834Sobrien    //
3798130561Sobrien    //        bool        operator!(bool);
3799104834Sobrien    //        bool        operator&&(bool, bool);     [BELOW]
3800104834Sobrien    //        bool        operator||(bool, bool);     [BELOW]
3801218822Sdim    QualType ParamTy = Context.BoolTy;
3802218822Sdim    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3803104834Sobrien                        /*IsAssignmentOperator=*/false,
3804104834Sobrien                        /*NumContextualBoolArguments=*/1);
3805104834Sobrien    break;
3806104834Sobrien  }
3807104834Sobrien
3808104834Sobrien  case OO_AmpAmp:
3809104834Sobrien  case OO_PipePipe: {
3810104834Sobrien    // C++ [over.operator]p23:
3811104834Sobrien    //
381292828Sobrien    //   There also exist candidate operator functions of the form
381392828Sobrien    //
3814130561Sobrien    //        bool        operator!(bool);            [ABOVE]
3815130561Sobrien    //        bool        operator&&(bool, bool);
381692828Sobrien    //        bool        operator||(bool, bool);
381792828Sobrien    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
381892828Sobrien    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
381992828Sobrien                        /*IsAssignmentOperator=*/false,
382092828Sobrien                        /*NumContextualBoolArguments=*/2);
382192828Sobrien    break;
382292828Sobrien  }
382392828Sobrien
382492828Sobrien  case OO_Subscript:
3825218822Sdim    // C++ [over.built]p13:
3826218822Sdim    //
382792828Sobrien    //   For every cv-qualified or cv-unqualified object type T there
382892828Sobrien    //   exist candidate operator functions of the form
3829130561Sobrien    //
383092828Sobrien    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3831104834Sobrien    //        T&         operator[](T*, ptrdiff_t);
3832218822Sdim    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3833218822Sdim    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3834130561Sobrien    //        T&         operator[](ptrdiff_t, T*);
3835218822Sdim    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3836130561Sobrien         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
383792828Sobrien      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3838218822Sdim      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
3839104834Sobrien      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3840104834Sobrien
3841218822Sdim      // T& operator[](T*, ptrdiff_t)
3842218822Sdim      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3843130561Sobrien
3844130561Sobrien      // T& operator[](ptrdiff_t, T*);
3845130561Sobrien      ParamTypes[0] = ParamTypes[1];
3846104834Sobrien      ParamTypes[1] = *Ptr;
3847218822Sdim      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3848218822Sdim    }
3849218822Sdim    break;
3850218822Sdim
3851218822Sdim  case OO_ArrowStar:
3852218822Sdim    // C++ [over.built]p11:
3853218822Sdim    //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3854218822Sdim    //    C1 is the same type as C2 or is a derived class of C2, T is an object
3855218822Sdim    //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3856218822Sdim    //    there exist candidate operator functions of the form
3857218822Sdim    //    CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3858218822Sdim    //    where CV12 is the union of CV1 and CV2.
3859130561Sobrien    {
386092828Sobrien      for (BuiltinCandidateTypeSet::iterator Ptr =
386192828Sobrien             CandidateTypes.pointer_begin();
3862130561Sobrien           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3863130561Sobrien        QualType C1Ty = (*Ptr);
386489857Sobrien        QualType C1;
3865130561Sobrien        QualifierCollector Q1;
3866130561Sobrien        if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
386789857Sobrien          C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
3868130561Sobrien          if (!isa<RecordType>(C1))
3869130561Sobrien            continue;
3870130561Sobrien          // heuristic to reduce number of builtin candidates in the set.
387189857Sobrien          // Add volatile/restrict version only if there are conversions to a
3872130561Sobrien          // volatile/restrict type.
3873130561Sobrien          if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3874130561Sobrien            continue;
3875130561Sobrien          if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
387689857Sobrien            continue;
3877130561Sobrien        }
3878130561Sobrien        for (BuiltinCandidateTypeSet::iterator
3879130561Sobrien             MemPtr = CandidateTypes.member_pointer_begin(),
3880130561Sobrien             MemPtrEnd = CandidateTypes.member_pointer_end();
388189857Sobrien             MemPtr != MemPtrEnd; ++MemPtr) {
3882130561Sobrien          const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3883130561Sobrien          QualType C2 = QualType(mptr->getClass(), 0);
3884130561Sobrien          C2 = C2.getUnqualifiedType();
3885218822Sdim          if (C1 != C2 && !IsDerivedFrom(C1, C2))
3886130561Sobrien            break;
3887130561Sobrien          QualType ParamTypes[2] = { *Ptr, *MemPtr };
3888130561Sobrien          // build CV12 T&
3889130561Sobrien          QualType T = mptr->getPointeeType();
3890218822Sdim          if (!VisibleTypeConversionsQuals.hasVolatile() &&
3891218822Sdim              T.isVolatileQualified())
3892130561Sobrien            continue;
3893130561Sobrien          if (!VisibleTypeConversionsQuals.hasRestrict() &&
3894130561Sobrien              T.isRestrictQualified())
3895130561Sobrien            continue;
3896130561Sobrien          T = Q1.apply(T);
3897130561Sobrien          QualType ResultTy = Context.getLValueReferenceType(T);
3898130561Sobrien          AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
389989857Sobrien        }
390089857Sobrien      }
390192828Sobrien    }
390289857Sobrien    break;
3903130561Sobrien
3904130561Sobrien  case OO_Conditional:
390589857Sobrien    // Note that we don't consider the first argument, since it has been
390689857Sobrien    // contextually converted to bool long ago. The candidates below are
390789857Sobrien    // therefore added as binary.
390889857Sobrien    //
3909130561Sobrien    // C++ [over.built]p24:
391089857Sobrien    //   For every type T, where T is a pointer or pointer-to-member type,
3911130561Sobrien    //   there exist candidate operator functions of the form
3912130561Sobrien    //
3913130561Sobrien    //        T        operator?(bool, T, T);
3914130561Sobrien    //
3915130561Sobrien    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3916130561Sobrien         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
391789857Sobrien      QualType ParamTypes[2] = { *Ptr, *Ptr };
3918130561Sobrien      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
391989857Sobrien    }
3920130561Sobrien    for (BuiltinCandidateTypeSet::iterator Ptr =
3921130561Sobrien           CandidateTypes.member_pointer_begin(),
392289857Sobrien         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
392389857Sobrien      QualType ParamTypes[2] = { *Ptr, *Ptr };
3924130561Sobrien      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
392589857Sobrien    }
392689857Sobrien    goto Conditional;
3927218822Sdim  }
3928218822Sdim}
3929218822Sdim
3930218822Sdim/// \brief Add function candidates found via argument-dependent lookup
3931218822Sdim/// to the set of overloading candidates.
3932218822Sdim///
3933218822Sdim/// This routine performs argument-dependent name lookup based on the
3934218822Sdim/// given function name (which may also be an operator name) and adds
3935218822Sdim/// all of the overload candidates found by ADL to the overload
3936218822Sdim/// candidate set (C++ [basic.lookup.argdep]).
3937218822Sdimvoid
3938218822SdimSema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3939218822Sdim                                           Expr **Args, unsigned NumArgs,
3940218822Sdim                                           bool HasExplicitTemplateArgs,
3941218822Sdim                            const TemplateArgumentLoc *ExplicitTemplateArgs,
3942218822Sdim                                           unsigned NumExplicitTemplateArgs,
3943218822Sdim                                           OverloadCandidateSet& CandidateSet,
3944218822Sdim                                           bool PartialOverloading) {
3945218822Sdim  FunctionSet Functions;
3946218822Sdim
3947218822Sdim  // FIXME: Should we be trafficking in canonical function decls throughout?
3948218822Sdim
3949218822Sdim  // Record all of the function candidates that we've already
3950218822Sdim  // added to the overload set, so that we don't add those same
3951218822Sdim  // candidates a second time.
3952218822Sdim  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3953218822Sdim                                   CandEnd = CandidateSet.end();
3954218822Sdim       Cand != CandEnd; ++Cand)
3955218822Sdim    if (Cand->Function) {
3956218822Sdim      Functions.insert(Cand->Function);
3957218822Sdim      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3958218822Sdim        Functions.insert(FunTmpl);
3959218822Sdim    }
3960218822Sdim
3961218822Sdim  // FIXME: Pass in the explicit template arguments?
396289857Sobrien  ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
396389857Sobrien
396489857Sobrien  // Erase all of the candidates we already knew about.
3965218822Sdim  // FIXME: This is suboptimal. Is there a better way?
3966218822Sdim  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3967218822Sdim                                   CandEnd = CandidateSet.end();
396889857Sobrien       Cand != CandEnd; ++Cand)
396989857Sobrien    if (Cand->Function) {
397089857Sobrien      Functions.erase(Cand->Function);
397189857Sobrien      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
397289857Sobrien        Functions.erase(FunTmpl);
397389857Sobrien    }
3974130561Sobrien
397589857Sobrien  // For each of the ADL candidates we found, add it to the overload
397689857Sobrien  // set.
397789857Sobrien  for (FunctionSet::iterator Func = Functions.begin(),
397889857Sobrien                          FuncEnd = Functions.end();
397989857Sobrien       Func != FuncEnd; ++Func) {
398089857Sobrien    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
398189857Sobrien      if (HasExplicitTemplateArgs)
3982218822Sdim        continue;
398389857Sobrien
398489857Sobrien      AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
398589857Sobrien                           false, false, PartialOverloading);
398689857Sobrien    } else
398789857Sobrien      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
398889857Sobrien                                   HasExplicitTemplateArgs,
398989857Sobrien                                   ExplicitTemplateArgs,
399089857Sobrien                                   NumExplicitTemplateArgs,
399189857Sobrien                                   Args, NumArgs, CandidateSet);
399289857Sobrien  }
399389857Sobrien}
399489857Sobrien
399589857Sobrien/// isBetterOverloadCandidate - Determines whether the first overload
399689857Sobrien/// candidate is a better candidate than the second (C++ 13.3.3p1).
399789857Sobrienbool
399889857SobrienSema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
399989857Sobrien                                const OverloadCandidate& Cand2) {
400089857Sobrien  // Define viable functions to be better candidates than non-viable
400189857Sobrien  // functions.
400289857Sobrien  if (!Cand2.Viable)
400389857Sobrien    return Cand1.Viable;
400489857Sobrien  else if (!Cand1.Viable)
400589857Sobrien    return false;
400689857Sobrien
400789857Sobrien  // C++ [over.match.best]p1:
4008130561Sobrien  //
400989857Sobrien  //   -- if F is a static member function, ICS1(F) is defined such
4010130561Sobrien  //      that ICS1(F) is neither better nor worse than ICS1(G) for
4011218822Sdim  //      any function G, and, symmetrically, ICS1(G) is neither
4012130561Sobrien  //      better nor worse than ICS1(F).
4013218822Sdim  unsigned StartArg = 0;
4014218822Sdim  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4015218822Sdim    StartArg = 1;
4016218822Sdim
4017130561Sobrien  // C++ [over.match.best]p1:
4018218822Sdim  //   A viable function F1 is defined to be a better function than another
4019218822Sdim  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
4020218822Sdim  //   conversion sequence than ICSi(F2), and then...
4021218822Sdim  unsigned NumArgs = Cand1.Conversions.size();
4022130561Sobrien  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4023130561Sobrien  bool HasBetterConversion = false;
4024130561Sobrien  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
4025130561Sobrien    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4026130561Sobrien                                               Cand2.Conversions[ArgIdx])) {
4027130561Sobrien    case ImplicitConversionSequence::Better:
4028130561Sobrien      // Cand1 has a better conversion sequence.
4029130561Sobrien      HasBetterConversion = true;
4030130561Sobrien      break;
4031130561Sobrien
4032130561Sobrien    case ImplicitConversionSequence::Worse:
4033130561Sobrien      // Cand1 can't be better than Cand2.
4034130561Sobrien      return false;
4035130561Sobrien
4036130561Sobrien    case ImplicitConversionSequence::Indistinguishable:
4037130561Sobrien      // Do nothing.
4038130561Sobrien      break;
4039130561Sobrien    }
4040130561Sobrien  }
4041130561Sobrien
4042130561Sobrien  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
4043130561Sobrien  //       ICSj(F2), or, if not that,
4044130561Sobrien  if (HasBetterConversion)
4045130561Sobrien    return true;
4046130561Sobrien
4047130561Sobrien  //     - F1 is a non-template function and F2 is a function template
4048130561Sobrien  //       specialization, or, if not that,
4049130561Sobrien  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4050130561Sobrien      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4051130561Sobrien    return true;
4052130561Sobrien
4053130561Sobrien  //   -- F1 and F2 are function template specializations, and the function
4054130561Sobrien  //      template for F1 is more specialized than the template for F2
4055130561Sobrien  //      according to the partial ordering rules described in 14.5.5.2, or,
4056130561Sobrien  //      if not that,
4057130561Sobrien  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4058130561Sobrien      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4059130561Sobrien    if (FunctionTemplateDecl *BetterTemplate
4060218822Sdim          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4061130561Sobrien                                       Cand2.Function->getPrimaryTemplate(),
4062218822Sdim                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4063130561Sobrien                                                             : TPOC_Call))
4064218822Sdim      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4065218822Sdim
4066218822Sdim  //   -- the context is an initialization by user-defined conversion
4067130561Sobrien  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
4068130561Sobrien  //      from the return type of F1 to the destination type (i.e.,
4069130561Sobrien  //      the type of the entity being initialized) is a better
4070130561Sobrien  //      conversion sequence than the standard conversion sequence
4071130561Sobrien  //      from the return type of F2 to the destination type.
407289857Sobrien  if (Cand1.Function && Cand2.Function &&
407389857Sobrien      isa<CXXConversionDecl>(Cand1.Function) &&
4074218822Sdim      isa<CXXConversionDecl>(Cand2.Function)) {
4075218822Sdim    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4076104834Sobrien                                               Cand2.FinalConversion)) {
4077218822Sdim    case ImplicitConversionSequence::Better:
4078218822Sdim      // Cand1 has a better conversion sequence.
4079104834Sobrien      return true;
4080218822Sdim
4081104834Sobrien    case ImplicitConversionSequence::Worse:
4082218822Sdim      // Cand1 can't be better than Cand2.
4083104834Sobrien      return false;
4084218822Sdim
4085104834Sobrien    case ImplicitConversionSequence::Indistinguishable:
4086218822Sdim      // Do nothing
4087218822Sdim      break;
4088218822Sdim    }
4089218822Sdim  }
4090218822Sdim
4091218822Sdim  return false;
4092218822Sdim}
4093218822Sdim
4094218822Sdim/// \brief Computes the best viable function (C++ 13.3.3)
4095104834Sobrien/// within an overload candidate set.
4096218822Sdim///
4097218822Sdim/// \param CandidateSet the set of candidate functions.
4098104834Sobrien///
4099104834Sobrien/// \param Loc the location of the function name (or operator symbol) for
4100218822Sdim/// which overload resolution occurs.
4101130561Sobrien///
4102218822Sdim/// \param Best f overload resolution was successful or found a deleted
4103218822Sdim/// function, Best points to the candidate function found.
4104218822Sdim///
4105218822Sdim/// \returns The result of overload resolution.
4106218822SdimSema::OverloadingResult
4107218822SdimSema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4108218822Sdim                         SourceLocation Loc,
4109218822Sdim                         OverloadCandidateSet::iterator& Best) {
4110218822Sdim  // Find the best viable function.
4111218822Sdim  Best = CandidateSet.end();
4112218822Sdim  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4113218822Sdim       Cand != CandidateSet.end(); ++Cand) {
4114218822Sdim    if (Cand->Viable) {
4115218822Sdim      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4116218822Sdim        Best = Cand;
4117218822Sdim    }
4118218822Sdim  }
4119218822Sdim
4120218822Sdim  // If we didn't find any viable functions, abort.
4121218822Sdim  if (Best == CandidateSet.end())
4122218822Sdim    return OR_No_Viable_Function;
4123218822Sdim
4124218822Sdim  // Make sure that this function is better than every other viable
4125218822Sdim  // function. If not, we have an ambiguity.
4126218822Sdim  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4127218822Sdim       Cand != CandidateSet.end(); ++Cand) {
4128218822Sdim    if (Cand->Viable &&
4129218822Sdim        Cand != Best &&
4130218822Sdim        !isBetterOverloadCandidate(*Best, *Cand)) {
4131218822Sdim      Best = CandidateSet.end();
4132218822Sdim      return OR_Ambiguous;
4133218822Sdim    }
4134218822Sdim  }
4135218822Sdim
4136218822Sdim  // Best is the best viable function.
4137218822Sdim  if (Best->Function &&
4138130561Sobrien      (Best->Function->isDeleted() ||
4139130561Sobrien       Best->Function->getAttr<UnavailableAttr>()))
4140130561Sobrien    return OR_Deleted;
4141130561Sobrien
4142130561Sobrien  // C++ [basic.def.odr]p2:
4143130561Sobrien  //   An overloaded function is used if it is selected by overload resolution
4144130561Sobrien  //   when referred to from a potentially-evaluated expression. [Note: this
4145130561Sobrien  //   covers calls to named functions (5.2.2), operator overloading
4146130561Sobrien  //   (clause 13), user-defined conversions (12.3.2), allocation function for
4147218822Sdim  //   placement new (5.3.4), as well as non-default initialization (8.5).
4148218822Sdim  if (Best->Function)
4149130561Sobrien    MarkDeclarationReferenced(Loc, Best->Function);
4150218822Sdim  return OR_Success;
4151130561Sobrien}
4152130561Sobrien
4153130561Sobrien/// PrintOverloadCandidates - When overload resolution fails, prints
4154218822Sdim/// diagnostic messages containing the candidates in the candidate
4155218822Sdim/// set. If OnlyViable is true, only viable candidates will be printed.
4156218822Sdimvoid
4157218822SdimSema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
4158218822Sdim                              bool OnlyViable,
4159218822Sdim                              const char *Opc,
4160218822Sdim                              SourceLocation OpLoc) {
4161218822Sdim  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4162218822Sdim                             LastCand = CandidateSet.end();
4163218822Sdim  bool Reported = false;
4164218822Sdim  for (; Cand != LastCand; ++Cand) {
4165218822Sdim    if (Cand->Viable || !OnlyViable) {
4166218822Sdim      if (Cand->Function) {
4167218822Sdim        if (Cand->Function->isDeleted() ||
4168218822Sdim            Cand->Function->getAttr<UnavailableAttr>()) {
4169218822Sdim          // Deleted or "unavailable" function.
4170218822Sdim          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4171218822Sdim            << Cand->Function->isDeleted();
4172218822Sdim        } else if (FunctionTemplateDecl *FunTmpl
4173218822Sdim                     = Cand->Function->getPrimaryTemplate()) {
4174218822Sdim          // Function template specialization
4175218822Sdim          // FIXME: Give a better reason!
4176218822Sdim          Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4177218822Sdim            << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4178218822Sdim                              *Cand->Function->getTemplateSpecializationArgs());
4179218822Sdim        } else {
4180218822Sdim          // Normal function
4181218822Sdim          bool errReported = false;
4182218822Sdim          if (!Cand->Viable && Cand->Conversions.size() > 0) {
4183218822Sdim            for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4184218822Sdim              const ImplicitConversionSequence &Conversion =
4185218822Sdim                                                        Cand->Conversions[i];
4186218822Sdim              if ((Conversion.ConversionKind !=
4187218822Sdim                   ImplicitConversionSequence::BadConversion) ||
4188218822Sdim                  Conversion.ConversionFunctionSet.size() == 0)
4189218822Sdim                continue;
4190218822Sdim              Diag(Cand->Function->getLocation(),
4191218822Sdim                   diag::err_ovl_candidate_not_viable) << (i+1);
4192218822Sdim              errReported = true;
4193218822Sdim              for (int j = Conversion.ConversionFunctionSet.size()-1;
4194218822Sdim                   j >= 0; j--) {
4195218822Sdim                FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4196218822Sdim                Diag(Func->getLocation(), diag::err_ovl_candidate);
4197218822Sdim              }
4198218822Sdim            }
4199130561Sobrien          }
4200218822Sdim          if (!errReported)
4201218822Sdim            Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
4202218822Sdim        }
4203218822Sdim      } else if (Cand->IsSurrogate) {
4204218822Sdim        // Desugar the type of the surrogate down to a function type,
4205218822Sdim        // retaining as many typedefs as possible while still showing
4206218822Sdim        // the function type (and, therefore, its parameter types).
4207218822Sdim        QualType FnType = Cand->Surrogate->getConversionType();
4208218822Sdim        bool isLValueReference = false;
4209218822Sdim        bool isRValueReference = false;
4210218822Sdim        bool isPointer = false;
4211218822Sdim        if (const LValueReferenceType *FnTypeRef =
4212218822Sdim              FnType->getAs<LValueReferenceType>()) {
4213218822Sdim          FnType = FnTypeRef->getPointeeType();
4214218822Sdim          isLValueReference = true;
4215218822Sdim        } else if (const RValueReferenceType *FnTypeRef =
4216218822Sdim                     FnType->getAs<RValueReferenceType>()) {
4217218822Sdim          FnType = FnTypeRef->getPointeeType();
4218218822Sdim          isRValueReference = true;
4219218822Sdim        }
4220218822Sdim        if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4221218822Sdim          FnType = FnTypePtr->getPointeeType();
4222218822Sdim          isPointer = true;
4223218822Sdim        }
4224218822Sdim        // Desugar down to a function type.
4225218822Sdim        FnType = QualType(FnType->getAs<FunctionType>(), 0);
4226218822Sdim        // Reconstruct the pointer/reference as appropriate.
4227218822Sdim        if (isPointer) FnType = Context.getPointerType(FnType);
4228218822Sdim        if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4229218822Sdim        if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
4230218822Sdim
4231218822Sdim        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
4232218822Sdim          << FnType;
4233218822Sdim      } else if (OnlyViable) {
4234218822Sdim        assert(Cand->Conversions.size() <= 2 &&
4235218822Sdim               "builtin-binary-operator-not-binary");
4236218822Sdim        std::string TypeStr("operator");
4237218822Sdim        TypeStr += Opc;
4238218822Sdim        TypeStr += "(";
4239218822Sdim        TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4240218822Sdim        if (Cand->Conversions.size() == 1) {
4241218822Sdim          TypeStr += ")";
4242218822Sdim          Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4243218822Sdim        }
4244218822Sdim        else {
4245218822Sdim          TypeStr += ", ";
4246218822Sdim          TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4247218822Sdim          TypeStr += ")";
4248218822Sdim          Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4249218822Sdim        }
4250218822Sdim      }
4251218822Sdim      else if (!Cand->Viable && !Reported) {
4252218822Sdim        // Non-viability might be due to ambiguous user-defined conversions,
4253218822Sdim        // needed for built-in operators. Report them as well, but only once
4254218822Sdim        // as we have typically many built-in candidates.
4255218822Sdim        unsigned NoOperands = Cand->Conversions.size();
4256218822Sdim        for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4257218822Sdim          const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4258218822Sdim          if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4259218822Sdim              ICS.ConversionFunctionSet.empty())
4260218822Sdim            continue;
4261218822Sdim          if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4262218822Sdim                         Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4263218822Sdim            QualType FromTy =
4264218822Sdim              QualType(
4265218822Sdim                     static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4266218822Sdim            Diag(OpLoc,diag::note_ambiguous_type_conversion)
4267218822Sdim                  << FromTy << Func->getConversionType();
4268218822Sdim          }
4269218822Sdim          for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4270218822Sdim            FunctionDecl *Func =
4271218822Sdim              Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4272218822Sdim            Diag(Func->getLocation(),diag::err_ovl_candidate);
4273218822Sdim          }
4274218822Sdim        }
4275218822Sdim        Reported = true;
4276218822Sdim      }
4277218822Sdim    }
4278218822Sdim  }
4279218822Sdim}
4280218822Sdim
4281218822Sdim/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4282218822Sdim/// an overloaded function (C++ [over.over]), where @p From is an
4283218822Sdim/// expression with overloaded function type and @p ToType is the type
4284218822Sdim/// we're trying to resolve to. For example:
4285218822Sdim///
4286218822Sdim/// @code
4287218822Sdim/// int f(double);
4288218822Sdim/// int f(int);
4289218822Sdim///
4290218822Sdim/// int (*pfd)(double) = f; // selects f(double)
4291218822Sdim/// @endcode
4292218822Sdim///
4293218822Sdim/// This routine returns the resulting FunctionDecl if it could be
4294218822Sdim/// resolved, and NULL otherwise. When @p Complain is true, this
4295218822Sdim/// routine will emit diagnostics if there is an error.
4296218822SdimFunctionDecl *
4297218822SdimSema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
4298218822Sdim                                         bool Complain) {
4299218822Sdim  QualType FunctionType = ToType;
4300218822Sdim  bool IsMember = false;
4301218822Sdim  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
4302218822Sdim    FunctionType = ToTypePtr->getPointeeType();
4303218822Sdim  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
4304218822Sdim    FunctionType = ToTypeRef->getPointeeType();
4305218822Sdim  else if (const MemberPointerType *MemTypePtr =
4306218822Sdim                    ToType->getAs<MemberPointerType>()) {
4307130561Sobrien    FunctionType = MemTypePtr->getPointeeType();
4308130561Sobrien    IsMember = true;
4309130561Sobrien  }
4310130561Sobrien
4311130561Sobrien  // We only look at pointers or references to functions.
4312130561Sobrien  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
4313130561Sobrien  if (!FunctionType->isFunctionType())
4314130561Sobrien    return 0;
4315130561Sobrien
4316130561Sobrien  // Find the actual overloaded function declaration.
4317130561Sobrien  OverloadedFunctionDecl *Ovl = 0;
4318130561Sobrien
4319130561Sobrien  // C++ [over.over]p1:
4320130561Sobrien  //   [...] [Note: any redundant set of parentheses surrounding the
4321130561Sobrien  //   overloaded function name is ignored (5.1). ]
4322130561Sobrien  Expr *OvlExpr = From->IgnoreParens();
4323130561Sobrien
4324130561Sobrien  // C++ [over.over]p1:
4325130561Sobrien  //   [...] The overloaded function name can be preceded by the &
4326130561Sobrien  //   operator.
4327130561Sobrien  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4328130561Sobrien    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4329130561Sobrien      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4330130561Sobrien  }
4331130561Sobrien
4332130561Sobrien  bool HasExplicitTemplateArgs = false;
4333130561Sobrien  const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
4334130561Sobrien  unsigned NumExplicitTemplateArgs = 0;
4335130561Sobrien
4336130561Sobrien  // Try to dig out the overloaded function.
4337130561Sobrien  FunctionTemplateDecl *FunctionTemplate = 0;
4338130561Sobrien  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
4339130561Sobrien    Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
4340130561Sobrien    FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4341130561Sobrien    HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4342130561Sobrien    ExplicitTemplateArgs = DR->getTemplateArgs();
4343130561Sobrien    NumExplicitTemplateArgs = DR->getNumTemplateArgs();
4344130561Sobrien  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4345130561Sobrien    Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4346130561Sobrien    FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
4347130561Sobrien    HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4348130561Sobrien    ExplicitTemplateArgs = ME->getTemplateArgs();
4349130561Sobrien    NumExplicitTemplateArgs = ME->getNumTemplateArgs();
4350130561Sobrien  } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4351130561Sobrien    TemplateName Name = TIRE->getTemplateName();
4352130561Sobrien    Ovl = Name.getAsOverloadedFunctionDecl();
4353130561Sobrien    FunctionTemplate =
4354130561Sobrien      dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4355130561Sobrien
4356130561Sobrien    HasExplicitTemplateArgs = true;
4357130561Sobrien    ExplicitTemplateArgs = TIRE->getTemplateArgs();
4358130561Sobrien    NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
4359130561Sobrien  }
4360130561Sobrien
4361130561Sobrien  // If there's no overloaded function declaration or function template,
4362130561Sobrien  // we're done.
4363130561Sobrien  if (!Ovl && !FunctionTemplate)
4364130561Sobrien    return 0;
4365130561Sobrien
4366130561Sobrien  OverloadIterator Fun;
4367130561Sobrien  if (Ovl)
4368130561Sobrien    Fun = Ovl;
4369130561Sobrien  else
4370130561Sobrien    Fun = FunctionTemplate;
4371130561Sobrien
4372130561Sobrien  // Look through all of the overloaded functions, searching for one
4373130561Sobrien  // whose type matches exactly.
4374218822Sdim  llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
4375218822Sdim  bool FoundNonTemplateFunction = false;
4376218822Sdim  for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
4377218822Sdim    // C++ [over.over]p3:
4378130561Sobrien    //   Non-member functions and static member functions match
4379130561Sobrien    //   targets of type "pointer-to-function" or "reference-to-function."
4380130561Sobrien    //   Nonstatic member functions match targets of
438189857Sobrien    //   type "pointer-to-member-function."
438289857Sobrien    // Note that according to DR 247, the containing class does not matter.
438389857Sobrien
438489857Sobrien    if (FunctionTemplateDecl *FunctionTemplate
4385130561Sobrien          = dyn_cast<FunctionTemplateDecl>(*Fun)) {
4386130561Sobrien      if (CXXMethodDecl *Method
4387130561Sobrien            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
438889857Sobrien        // Skip non-static function templates when converting to pointer, and
438989857Sobrien        // static when converting to member pointer.
439089857Sobrien        if (Method->isStatic() == IsMember)
439189857Sobrien          continue;
439289857Sobrien      } else if (IsMember)
439389857Sobrien        continue;
439489857Sobrien
4395104834Sobrien      // C++ [over.over]p2:
439689857Sobrien      //   If the name is a function template, template argument deduction is
4397130561Sobrien      //   done (14.8.2.2), and if the argument deduction succeeds, the
4398130561Sobrien      //   resulting template argument list is used to generate a single
439989857Sobrien      //   function template specialization, which is added to the set of
4400130561Sobrien      //   overloaded functions considered.
4401130561Sobrien      // FIXME: We don't really want to build the specialization here, do we?
4402130561Sobrien      FunctionDecl *Specialization = 0;
4403130561Sobrien      TemplateDeductionInfo Info(Context);
4404130561Sobrien      if (TemplateDeductionResult Result
4405130561Sobrien            = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4406130561Sobrien                                      ExplicitTemplateArgs,
4407130561Sobrien                                      NumExplicitTemplateArgs,
4408130561Sobrien                                      FunctionType, Specialization, Info)) {
440989857Sobrien        // FIXME: make a note of the failed deduction for diagnostics.
441089857Sobrien        (void)Result;
441189857Sobrien      } else {
441289857Sobrien        // FIXME: If the match isn't exact, shouldn't we just drop this as
441389857Sobrien        // a candidate? Find a testcase before changing the code.
4414104834Sobrien        assert(FunctionType
4415104834Sobrien                 == Context.getCanonicalType(Specialization->getType()));
441689857Sobrien        Matches.insert(
441789857Sobrien                cast<FunctionDecl>(Specialization->getCanonicalDecl()));
4418104834Sobrien      }
4419104834Sobrien    }
4420104834Sobrien
4421104834Sobrien    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4422104834Sobrien      // Skip non-static functions when converting to pointer, and static
4423104834Sobrien      // when converting to member pointer.
4424104834Sobrien      if (Method->isStatic() == IsMember)
4425104834Sobrien        continue;
4426104834Sobrien
4427104834Sobrien      // If we have explicit template arguments, skip non-templates.
4428104834Sobrien      if (HasExplicitTemplateArgs)
4429104834Sobrien        continue;
4430104834Sobrien    } else if (IsMember)
4431104834Sobrien      continue;
4432104834Sobrien
4433104834Sobrien    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
4434104834Sobrien      if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
443589857Sobrien        Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
4436218822Sdim        FoundNonTemplateFunction = true;
4437130561Sobrien      }
4438104834Sobrien    }
4439130561Sobrien  }
4440218822Sdim
4441218822Sdim  // If there were 0 or 1 matches, we're done.
4442218822Sdim  if (Matches.empty())
4443104834Sobrien    return 0;
4444104834Sobrien  else if (Matches.size() == 1) {
444592828Sobrien    FunctionDecl *Result = *Matches.begin();
444692828Sobrien    MarkDeclarationReferenced(From->getLocStart(), Result);
4447130561Sobrien    return Result;
444892828Sobrien  }
444989857Sobrien
445089857Sobrien  // C++ [over.over]p4:
445189857Sobrien  //   If more than one function is selected, [...]
445289857Sobrien  typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
445389857Sobrien  if (!FoundNonTemplateFunction) {
4454130561Sobrien    //   [...] and any given function template specialization F1 is
4455130561Sobrien    //   eliminated if the set contains a second function template
4456218822Sdim    //   specialization whose function template is more specialized
445789857Sobrien    //   than the function template of F1 according to the partial
445889857Sobrien    //   ordering rules of 14.5.5.2.
445989857Sobrien
446089857Sobrien    // The algorithm specified above is quadratic. We instead use a
446189857Sobrien    // two-pass algorithm (similar to the one used to identify the
4462218822Sdim    // best viable function in an overload set) that identifies the
4463218822Sdim    // best function template (if it exists).
4464218822Sdim    llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4465218822Sdim                                                         Matches.end());
4466218822Sdim    FunctionDecl *Result =
4467218822Sdim        getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
446889857Sobrien                           TPOC_Other, From->getLocStart(),
4469130561Sobrien                           PDiag(),
447089857Sobrien                           PDiag(diag::err_addr_ovl_ambiguous)
447189857Sobrien                               << TemplateMatches[0]->getDeclName(),
4472130561Sobrien                           PDiag(diag::err_ovl_template_candidate));
4473130561Sobrien    MarkDeclarationReferenced(From->getLocStart(), Result);
4474130561Sobrien    return Result;
4475130561Sobrien  }
4476130561Sobrien
4477130561Sobrien  //   [...] any function template specializations in the set are
4478130561Sobrien  //   eliminated if the set also contains a non-template function, [...]
4479130561Sobrien  llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4480130561Sobrien  for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4481130561Sobrien    if ((*M)->getPrimaryTemplate() == 0)
4482130561Sobrien      RemainingMatches.push_back(*M);
4483130561Sobrien
4484130561Sobrien  // [...] After such eliminations, if any, there shall remain exactly one
4485130561Sobrien  // selected function.
4486130561Sobrien  if (RemainingMatches.size() == 1) {
4487130561Sobrien    FunctionDecl *Result = RemainingMatches.front();
4488130561Sobrien    MarkDeclarationReferenced(From->getLocStart(), Result);
4489130561Sobrien    return Result;
4490130561Sobrien  }
4491130561Sobrien
4492130561Sobrien  // FIXME: We should probably return the same thing that BestViableFunction
4493130561Sobrien  // returns (even if we issue the diagnostics here).
4494130561Sobrien  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4495130561Sobrien    << RemainingMatches[0]->getDeclName();
4496130561Sobrien  for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4497130561Sobrien    Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
4498130561Sobrien  return 0;
4499130561Sobrien}
4500130561Sobrien
4501130561Sobrien/// \brief Add a single candidate to the overload set.
4502130561Sobrienstatic void AddOverloadedCallCandidate(Sema &S,
4503130561Sobrien                                       AnyFunctionDecl Callee,
4504130561Sobrien                                       bool &ArgumentDependentLookup,
450589857Sobrien                                       bool HasExplicitTemplateArgs,
450689857Sobrien                             const TemplateArgumentLoc *ExplicitTemplateArgs,
450789857Sobrien                                       unsigned NumExplicitTemplateArgs,
450889857Sobrien                                       Expr **Args, unsigned NumArgs,
450989857Sobrien                                       OverloadCandidateSet &CandidateSet,
451089857Sobrien                                       bool PartialOverloading) {
451189857Sobrien  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4512218822Sdim    assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4513130561Sobrien    S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4514130561Sobrien                           PartialOverloading);
4515130561Sobrien
451689857Sobrien    if (Func->getDeclContext()->isRecord() ||
451789857Sobrien        Func->getDeclContext()->isFunctionOrMethod())
451889857Sobrien      ArgumentDependentLookup = false;
4519130561Sobrien    return;
4520130561Sobrien  }
452189857Sobrien
4522130561Sobrien  FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4523130561Sobrien  S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4524130561Sobrien                                 ExplicitTemplateArgs,
4525130561Sobrien                                 NumExplicitTemplateArgs,
4526130561Sobrien                                 Args, NumArgs, CandidateSet);
4527130561Sobrien
4528130561Sobrien  if (FuncTemplate->getDeclContext()->isRecord())
452989857Sobrien    ArgumentDependentLookup = false;
4530130561Sobrien}
4531130561Sobrien
4532130561Sobrien/// \brief Add the overload candidates named by callee and/or found by argument
4533130561Sobrien/// dependent lookup to the given overload set.
4534130561Sobrienvoid Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4535130561Sobrien                                       DeclarationName &UnqualifiedName,
4536130561Sobrien                                       bool &ArgumentDependentLookup,
4537130561Sobrien                                       bool HasExplicitTemplateArgs,
4538130561Sobrien                             const TemplateArgumentLoc *ExplicitTemplateArgs,
4539130561Sobrien                                       unsigned NumExplicitTemplateArgs,
454089857Sobrien                                       Expr **Args, unsigned NumArgs,
4541130561Sobrien                                       OverloadCandidateSet &CandidateSet,
4542130561Sobrien                                       bool PartialOverloading) {
454389857Sobrien  // Add the functions denoted by Callee to the set of candidate
4544130561Sobrien  // functions. While we're doing so, track whether argument-dependent
4545130561Sobrien  // lookup still applies, per:
4546130561Sobrien  //
4547130561Sobrien  // C++0x [basic.lookup.argdep]p3:
4548130561Sobrien  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
454989857Sobrien  //   and let Y be the lookup set produced by argument dependent
455089857Sobrien  //   lookup (defined as follows). If X contains
455189857Sobrien  //
455289857Sobrien  //     -- a declaration of a class member, or
455389857Sobrien  //
455489857Sobrien  //     -- a block-scope function declaration that is not a
455589857Sobrien  //        using-declaration (FIXME: check for using declaration), or
455689857Sobrien  //
4557104834Sobrien  //     -- a declaration that is neither a function or a function
4558104834Sobrien  //        template
4559104834Sobrien  //
4560104834Sobrien  //   then Y is empty.
456189857Sobrien  if (!Callee) {
456289857Sobrien    // Nothing to do.
456389857Sobrien  } else if (OverloadedFunctionDecl *Ovl
4564104834Sobrien               = dyn_cast<OverloadedFunctionDecl>(Callee)) {
456589857Sobrien    for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4566130561Sobrien                                                FuncEnd = Ovl->function_end();
456789857Sobrien         Func != FuncEnd; ++Func)
4568130561Sobrien      AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4569130561Sobrien                                 HasExplicitTemplateArgs,
4570130561Sobrien                                 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4571130561Sobrien                                 Args, NumArgs, CandidateSet,
457289857Sobrien                                 PartialOverloading);
457389857Sobrien  } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
457489857Sobrien    AddOverloadedCallCandidate(*this,
457589857Sobrien                               AnyFunctionDecl::getFromNamedDecl(Callee),
457689857Sobrien                               ArgumentDependentLookup,
457789857Sobrien                               HasExplicitTemplateArgs,
457889857Sobrien                               ExplicitTemplateArgs, NumExplicitTemplateArgs,
457989857Sobrien                               Args, NumArgs, CandidateSet,
458089857Sobrien                               PartialOverloading);
458189857Sobrien  // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
458289857Sobrien  // checking dynamically.
4583130561Sobrien
4584130561Sobrien  if (Callee)
4585130561Sobrien    UnqualifiedName = Callee->getDeclName();
4586130561Sobrien
4587130561Sobrien  if (ArgumentDependentLookup)
4588130561Sobrien    AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4589130561Sobrien                                         HasExplicitTemplateArgs,
4590130561Sobrien                                         ExplicitTemplateArgs,
4591130561Sobrien                                         NumExplicitTemplateArgs,
4592130561Sobrien                                         CandidateSet,
4593130561Sobrien                                         PartialOverloading);
4594130561Sobrien}
4595130561Sobrien
459689857Sobrien/// ResolveOverloadedCallFn - Given the call expression that calls Fn
459789857Sobrien/// (which eventually refers to the declaration Func) and the call
459889857Sobrien/// arguments Args/NumArgs, attempt to resolve the function call down
459989857Sobrien/// to a specific function. If overload resolution succeeds, returns
460089857Sobrien/// the function declaration produced by overload
460189857Sobrien/// resolution. Otherwise, emits diagnostics, deletes all of the
4602218822Sdim/// arguments and Fn, and returns NULL.
460389857SobrienFunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
460489857Sobrien                                            DeclarationName UnqualifiedName,
460589857Sobrien                                            bool HasExplicitTemplateArgs,
460689857Sobrien                             const TemplateArgumentLoc *ExplicitTemplateArgs,
460789857Sobrien                                            unsigned NumExplicitTemplateArgs,
4608130561Sobrien                                            SourceLocation LParenLoc,
4609130561Sobrien                                            Expr **Args, unsigned NumArgs,
461089857Sobrien                                            SourceLocation *CommaLocs,
461189857Sobrien                                            SourceLocation RParenLoc,
461289857Sobrien                                            bool &ArgumentDependentLookup) {
461389857Sobrien  OverloadCandidateSet CandidateSet;
461489857Sobrien
4615130561Sobrien  // Add the functions denoted by Callee to the set of candidate
4616130561Sobrien  // functions.
461789857Sobrien  AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
461889857Sobrien                              HasExplicitTemplateArgs, ExplicitTemplateArgs,
4619104834Sobrien                              NumExplicitTemplateArgs, Args, NumArgs,
4620104834Sobrien                              CandidateSet);
4621104834Sobrien  OverloadCandidateSet::iterator Best;
4622218822Sdim  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
4623218822Sdim  case OR_Success:
4624218822Sdim    return Best->Function;
4625218822Sdim
4626218822Sdim  case OR_No_Viable_Function:
4627218822Sdim    Diag(Fn->getSourceRange().getBegin(),
4628218822Sdim         diag::err_ovl_no_viable_function_in_call)
4629218822Sdim      << UnqualifiedName << Fn->getSourceRange();
4630218822Sdim    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4631218822Sdim    break;
4632218822Sdim
4633218822Sdim  case OR_Ambiguous:
4634218822Sdim    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
4635218822Sdim      << UnqualifiedName << Fn->getSourceRange();
4636218822Sdim    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4637218822Sdim    break;
4638218822Sdim
4639218822Sdim  case OR_Deleted:
4640104834Sobrien    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4641104834Sobrien      << Best->Function->isDeleted()
464289857Sobrien      << UnqualifiedName
4643218822Sdim      << Fn->getSourceRange();
464489857Sobrien    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
464589857Sobrien    break;
464689857Sobrien  }
4647130561Sobrien
4648130561Sobrien  // Overload resolution failed. Destroy all of the subexpressions and
4649130561Sobrien  // return NULL.
4650218822Sdim  Fn->Destroy(Context);
4651218822Sdim  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4652130561Sobrien    Args[Arg]->Destroy(Context);
4653218822Sdim  return 0;
4654218822Sdim}
4655130561Sobrien
4656130561Sobrien/// \brief Create a unary operation that may resolve to an overloaded
4657130561Sobrien/// operator.
4658218822Sdim///
4659130561Sobrien/// \param OpLoc The location of the operator itself (e.g., '*').
4660130561Sobrien///
4661218822Sdim/// \param OpcIn The UnaryOperator::Opcode that describes this
4662218822Sdim/// operator.
4663218822Sdim///
4664218822Sdim/// \param Functions The set of non-member functions that will be
4665218822Sdim/// considered by overload resolution. The caller needs to build this
4666218822Sdim/// set based on the context using, e.g.,
4667218822Sdim/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4668218822Sdim/// set should not contain any member functions; those will be added
466989857Sobrien/// by CreateOverloadedUnaryOp().
467089857Sobrien///
467189857Sobrien/// \param input The input argument.
4672130561SobrienSema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4673130561Sobrien                                                     unsigned OpcIn,
4674130561Sobrien                                                     FunctionSet &Functions,
4675130561Sobrien                                                     ExprArg input) {
4676130561Sobrien  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4677130561Sobrien  Expr *Input = (Expr *)input.get();
4678130561Sobrien
4679130561Sobrien  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4680130561Sobrien  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4681130561Sobrien  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4682130561Sobrien
4683130561Sobrien  Expr *Args[2] = { Input, 0 };
4684130561Sobrien  unsigned NumArgs = 1;
4685130561Sobrien
4686130561Sobrien  // For post-increment and post-decrement, add the implicit '0' as
4687130561Sobrien  // the second argument, so that we know this is a post-increment or
4688130561Sobrien  // post-decrement.
4689130561Sobrien  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4690130561Sobrien    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4691130561Sobrien    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4692130561Sobrien                                           SourceLocation());
4693130561Sobrien    NumArgs = 2;
4694130561Sobrien  }
4695130561Sobrien
4696130561Sobrien  if (Input->isTypeDependent()) {
4697130561Sobrien    OverloadedFunctionDecl *Overloads
4698130561Sobrien      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4699130561Sobrien    for (FunctionSet::iterator Func = Functions.begin(),
4700130561Sobrien                            FuncEnd = Functions.end();
4701130561Sobrien         Func != FuncEnd; ++Func)
4702130561Sobrien      Overloads->addOverload(*Func);
4703130561Sobrien
4704130561Sobrien    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4705130561Sobrien                                                OpLoc, false, false);
4706130561Sobrien
4707130561Sobrien    input.release();
4708130561Sobrien    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4709218822Sdim                                                   &Args[0], NumArgs,
4710218822Sdim                                                   Context.DependentTy,
4711130561Sobrien                                                   OpLoc));
4712130561Sobrien  }
4713218822Sdim
4714218822Sdim  // Build an empty overload set.
4715218822Sdim  OverloadCandidateSet CandidateSet;
4716130561Sobrien
4717218822Sdim  // Add the candidates from the given function set.
4718218822Sdim  AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4719130561Sobrien
4720130561Sobrien  // Add operator candidates that are member functions.
4721218822Sdim  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4722130561Sobrien
4723130561Sobrien  // Add builtin operator candidates.
4724130561Sobrien  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4725130561Sobrien
4726218822Sdim  // Perform overload resolution.
4727130561Sobrien  OverloadCandidateSet::iterator Best;
4728218822Sdim  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4729130561Sobrien  case OR_Success: {
4730130561Sobrien    // We found a built-in operator or an overloaded operator.
4731130561Sobrien    FunctionDecl *FnDecl = Best->Function;
4732130561Sobrien
4733130561Sobrien    if (FnDecl) {
4734130561Sobrien      // We matched an overloaded operator. Build a call to that
4735130561Sobrien      // operator.
4736130561Sobrien
4737130561Sobrien      // Convert the arguments.
4738130561Sobrien      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4739130561Sobrien        if (PerformObjectArgumentInitialization(Input, Method))
4740130561Sobrien          return ExprError();
4741130561Sobrien      } else {
4742130561Sobrien        // Convert the arguments.
4743130561Sobrien        if (PerformCopyInitialization(Input,
4744130561Sobrien                                      FnDecl->getParamDecl(0)->getType(),
4745130561Sobrien                                      "passing"))
4746130561Sobrien          return ExprError();
4747130561Sobrien      }
474889857Sobrien
4749104834Sobrien      // Determine the result type
4750104834Sobrien      QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
4751130561Sobrien
4752104834Sobrien      // Build the actual expression node.
4753218822Sdim      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4754218822Sdim                                               SourceLocation());
4755218822Sdim      UsualUnaryConversions(FnExpr);
4756218822Sdim
4757218822Sdim      input.release();
4758218822Sdim      Args[0] = Input;
4759218822Sdim      ExprOwningPtr<CallExpr> TheCall(this,
4760218822Sdim        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4761218822Sdim                                          Args, NumArgs, ResultTy, OpLoc));
4762218822Sdim
4763218822Sdim      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4764218822Sdim                              FnDecl))
4765104834Sobrien        return ExprError();
4766218822Sdim
4767218822Sdim      return MaybeBindToTemporary(TheCall.release());
4768218822Sdim    } else {
4769218822Sdim      // We matched a built-in operator. Convert the arguments, then
4770218822Sdim      // break out so that we will build the appropriate built-in
4771218822Sdim      // operator node.
4772218822Sdim        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4773104834Sobrien                                      Best->Conversions[0], "passing"))
477489857Sobrien          return ExprError();
477589857Sobrien
4776130561Sobrien        break;
4777130561Sobrien      }
477889857Sobrien    }
477989857Sobrien
478089857Sobrien    case OR_No_Viable_Function:
478189857Sobrien      // No viable function; fall through to handling this as a
478289857Sobrien      // built-in operator, which will produce an error message for us.
478389857Sobrien      break;
478489857Sobrien
478589857Sobrien    case OR_Ambiguous:
478689857Sobrien      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
478789857Sobrien          << UnaryOperator::getOpcodeStr(Opc)
478889857Sobrien          << Input->getSourceRange();
478989857Sobrien      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
479089857Sobrien                              UnaryOperator::getOpcodeStr(Opc), OpLoc);
479189857Sobrien      return ExprError();
479289857Sobrien
479389857Sobrien    case OR_Deleted:
479489857Sobrien      Diag(OpLoc, diag::err_ovl_deleted_oper)
479589857Sobrien        << Best->Function->isDeleted()
479689857Sobrien        << UnaryOperator::getOpcodeStr(Opc)
479789857Sobrien        << Input->getSourceRange();
4798130561Sobrien      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4799130561Sobrien      return ExprError();
4800218822Sdim    }
4801130561Sobrien
480289857Sobrien  // Either we found no viable overloaded operator or we matched a
4803104834Sobrien  // built-in operator. In either case, fall through to trying to
480489857Sobrien  // build a built-in operation.
480589857Sobrien  input.release();
480689857Sobrien  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
480789857Sobrien}
480889857Sobrien
480989857Sobrien/// \brief Create a binary operation that may resolve to an overloaded
481089857Sobrien/// operator.
481189857Sobrien///
481289857Sobrien/// \param OpLoc The location of the operator itself (e.g., '+').
481389857Sobrien///
481489857Sobrien/// \param OpcIn The BinaryOperator::Opcode that describes this
481589857Sobrien/// operator.
481689857Sobrien///
481789857Sobrien/// \param Functions The set of non-member functions that will be
4818130561Sobrien/// considered by overload resolution. The caller needs to build this
481989857Sobrien/// set based on the context using, e.g.,
482089857Sobrien/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
482189857Sobrien/// set should not contain any member functions; those will be added
482289857Sobrien/// by CreateOverloadedBinOp().
482389857Sobrien///
482489857Sobrien/// \param LHS Left-hand argument.
482589857Sobrien/// \param RHS Right-hand argument.
482689857SobrienSema::OwningExprResult
4827130561SobrienSema::CreateOverloadedBinOp(SourceLocation OpLoc,
482889857Sobrien                            unsigned OpcIn,
4829130561Sobrien                            FunctionSet &Functions,
483089857Sobrien                            Expr *LHS, Expr *RHS) {
483189857Sobrien  Expr *Args[2] = { LHS, RHS };
483289857Sobrien  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
4833218822Sdim
4834130561Sobrien  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4835130561Sobrien  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
483689857Sobrien  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
483789857Sobrien
4838218822Sdim  // If either side is type-dependent, create an appropriate dependent
483989857Sobrien  // expression.
484089857Sobrien  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
484189857Sobrien    if (Functions.empty()) {
484289857Sobrien      // If there are no functions to store, just build a dependent
484389857Sobrien      // BinaryOperator or CompoundAssignment.
484489857Sobrien      if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
484589857Sobrien        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
484689857Sobrien                                                  Context.DependentTy, OpLoc));
484789857Sobrien
484889857Sobrien      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
484989857Sobrien                                                        Context.DependentTy,
485089857Sobrien                                                        Context.DependentTy,
485189857Sobrien                                                        Context.DependentTy,
485289857Sobrien                                                        OpLoc));
485389857Sobrien    }
485489857Sobrien
485589857Sobrien    OverloadedFunctionDecl *Overloads
4856130561Sobrien      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
485789857Sobrien    for (FunctionSet::iterator Func = Functions.begin(),
4858218822Sdim                            FuncEnd = Functions.end();
485989857Sobrien         Func != FuncEnd; ++Func)
486089857Sobrien      Overloads->addOverload(*Func);
486189857Sobrien
486289857Sobrien    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4863218822Sdim                                                OpLoc, false, false);
4864218822Sdim
486589857Sobrien    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
486689857Sobrien                                                   Args, 2,
486789857Sobrien                                                   Context.DependentTy,
486889857Sobrien                                                   OpLoc));
486989857Sobrien  }
487089857Sobrien
487189857Sobrien  // If this is the .* operator, which is not overloadable, just
487289857Sobrien  // create a built-in binary operator.
487389857Sobrien  if (Opc == BinaryOperator::PtrMemD)
487489857Sobrien    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4875218822Sdim
4876218822Sdim  // If this is one of the assignment operators, we only perform
4877218822Sdim  // overload resolution if the left-hand side is a class or
4878218822Sdim  // enumeration type (C++ [expr.ass]p3).
4879218822Sdim  if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
488089857Sobrien      !Args[0]->getType()->isOverloadableType())
488189857Sobrien    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4882130561Sobrien
488389857Sobrien  // Build an empty overload set.
488489857Sobrien  OverloadCandidateSet CandidateSet;
488589857Sobrien
488689857Sobrien  // Add the candidates from the given function set.
488789857Sobrien  AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
488889857Sobrien
488989857Sobrien  // Add operator candidates that are member functions.
489089857Sobrien  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
489189857Sobrien
489289857Sobrien  // Add builtin operator candidates.
489389857Sobrien  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
489489857Sobrien
489589857Sobrien  // Perform overload resolution.
489689857Sobrien  OverloadCandidateSet::iterator Best;
489789857Sobrien  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
489889857Sobrien    case OR_Success: {
489989857Sobrien      // We found a built-in operator or an overloaded operator.
4900218822Sdim      FunctionDecl *FnDecl = Best->Function;
4901218822Sdim
490289857Sobrien      if (FnDecl) {
490389857Sobrien        // We matched an overloaded operator. Build a call to that
490489857Sobrien        // operator.
4905130561Sobrien
490689857Sobrien        // Convert the arguments.
4907218822Sdim        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4908218822Sdim          if (PerformObjectArgumentInitialization(Args[0], Method) ||
490989857Sobrien              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
491089857Sobrien                                        "passing"))
491189857Sobrien            return ExprError();
491289857Sobrien        } else {
491389857Sobrien          // Convert the arguments.
4914130561Sobrien          if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
491589857Sobrien                                        "passing") ||
4916130561Sobrien              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
491789857Sobrien                                        "passing"))
491889857Sobrien            return ExprError();
491989857Sobrien        }
492089857Sobrien
492189857Sobrien        // Determine the result type
492289857Sobrien        QualType ResultTy
492389857Sobrien          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
492489857Sobrien        ResultTy = ResultTy.getNonReferenceType();
4925130561Sobrien
492689857Sobrien        // Build the actual expression node.
492789857Sobrien        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
492889857Sobrien                                                 OpLoc);
492989857Sobrien        UsualUnaryConversions(FnExpr);
493089857Sobrien
493192828Sobrien        ExprOwningPtr<CXXOperatorCallExpr>
493289857Sobrien          TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
493389857Sobrien                                                          Args, 2, ResultTy,
493489857Sobrien                                                          OpLoc));
4935130561Sobrien
493689857Sobrien        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
493789857Sobrien                                FnDecl))
4938218822Sdim          return ExprError();
4939218822Sdim
4940218822Sdim        return MaybeBindToTemporary(TheCall.release());
4941218822Sdim      } else {
4942218822Sdim        // We matched a built-in operator. Convert the arguments, then
4943218822Sdim        // break out so that we will build the appropriate built-in
4944218822Sdim        // operator node.
4945218822Sdim        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
4946218822Sdim                                      Best->Conversions[0], "passing") ||
4947218822Sdim            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
4948218822Sdim                                      Best->Conversions[1], "passing"))
4949218822Sdim          return ExprError();
4950218822Sdim
4951218822Sdim        break;
4952218822Sdim      }
4953218822Sdim    }
4954218822Sdim
4955218822Sdim    case OR_No_Viable_Function: {
4956218822Sdim      // C++ [over.match.oper]p9:
4957218822Sdim      //   If the operator is the operator , [...] and there are no
4958218822Sdim      //   viable functions, then the operator is assumed to be the
4959218822Sdim      //   built-in operator and interpreted according to clause 5.
4960218822Sdim      if (Opc == BinaryOperator::Comma)
4961218822Sdim        break;
4962218822Sdim
4963218822Sdim      // For class as left operand for assignment or compound assigment operator
4964218822Sdim      // do not fall through to handling in built-in, but report that no overloaded
4965218822Sdim      // assignment operator found
4966218822Sdim      OwningExprResult Result = ExprError();
4967218822Sdim      if (Args[0]->getType()->isRecordType() &&
4968218822Sdim          Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4969218822Sdim        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
4970218822Sdim             << BinaryOperator::getOpcodeStr(Opc)
4971218822Sdim             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4972218822Sdim      } else {
4973218822Sdim        // No viable function; try to create a built-in operation, which will
4974218822Sdim        // produce an error. Then, show the non-viable candidates.
4975218822Sdim        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4976218822Sdim      }
4977218822Sdim      assert(Result.isInvalid() &&
4978218822Sdim             "C++ binary operator overloading is missing candidates!");
4979218822Sdim      if (Result.isInvalid())
4980218822Sdim        PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4981218822Sdim                                BinaryOperator::getOpcodeStr(Opc), OpLoc);
4982218822Sdim      return move(Result);
4983218822Sdim    }
4984218822Sdim
4985218822Sdim    case OR_Ambiguous:
4986218822Sdim      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4987218822Sdim          << BinaryOperator::getOpcodeStr(Opc)
4988218822Sdim          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4989218822Sdim      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4990218822Sdim                              BinaryOperator::getOpcodeStr(Opc), OpLoc);
4991218822Sdim      return ExprError();
4992218822Sdim
4993218822Sdim    case OR_Deleted:
4994218822Sdim      Diag(OpLoc, diag::err_ovl_deleted_oper)
4995218822Sdim        << Best->Function->isDeleted()
4996218822Sdim        << BinaryOperator::getOpcodeStr(Opc)
4997218822Sdim        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4998218822Sdim      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4999218822Sdim      return ExprError();
5000218822Sdim    }
5001218822Sdim
5002218822Sdim  // We matched a built-in operator; build it.
5003218822Sdim  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5004218822Sdim}
5005218822Sdim
5006218822SdimAction::OwningExprResult
5007218822SdimSema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5008218822Sdim                                         SourceLocation RLoc,
5009218822Sdim                                         ExprArg Base, ExprArg Idx) {
5010218822Sdim  Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5011218822Sdim                    static_cast<Expr*>(Idx.get()) };
5012218822Sdim  DeclarationName OpName =
5013218822Sdim      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5014218822Sdim
5015218822Sdim  // If either side is type-dependent, create an appropriate dependent
5016218822Sdim  // expression.
5017218822Sdim  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5018218822Sdim
5019218822Sdim    OverloadedFunctionDecl *Overloads
5020218822Sdim      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
5021218822Sdim
5022218822Sdim    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
5023218822Sdim                                                LLoc, false, false);
5024218822Sdim
5025218822Sdim    Base.release();
5026218822Sdim    Idx.release();
5027218822Sdim    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5028218822Sdim                                                   Args, 2,
5029218822Sdim                                                   Context.DependentTy,
5030218822Sdim                                                   RLoc));
5031218822Sdim  }
5032218822Sdim
5033218822Sdim  // Build an empty overload set.
5034218822Sdim  OverloadCandidateSet CandidateSet;
5035218822Sdim
5036218822Sdim  // Subscript can only be overloaded as a member function.
5037218822Sdim
5038218822Sdim  // Add operator candidates that are member functions.
5039218822Sdim  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5040218822Sdim
5041218822Sdim  // Add builtin operator candidates.
5042218822Sdim  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5043218822Sdim
5044218822Sdim  // Perform overload resolution.
5045218822Sdim  OverloadCandidateSet::iterator Best;
5046218822Sdim  switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5047218822Sdim    case OR_Success: {
5048218822Sdim      // We found a built-in operator or an overloaded operator.
5049218822Sdim      FunctionDecl *FnDecl = Best->Function;
5050218822Sdim
5051218822Sdim      if (FnDecl) {
5052218822Sdim        // We matched an overloaded operator. Build a call to that
5053218822Sdim        // operator.
5054218822Sdim
5055218822Sdim        // Convert the arguments.
5056218822Sdim        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5057218822Sdim        if (PerformObjectArgumentInitialization(Args[0], Method) ||
5058218822Sdim            PerformCopyInitialization(Args[1],
5059218822Sdim                                      FnDecl->getParamDecl(0)->getType(),
5060218822Sdim                                      "passing"))
5061218822Sdim          return ExprError();
5062218822Sdim
5063218822Sdim        // Determine the result type
5064218822Sdim        QualType ResultTy
5065218822Sdim          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5066218822Sdim        ResultTy = ResultTy.getNonReferenceType();
5067218822Sdim
5068218822Sdim        // Build the actual expression node.
5069218822Sdim        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5070218822Sdim                                                 LLoc);
5071218822Sdim        UsualUnaryConversions(FnExpr);
5072218822Sdim
5073218822Sdim        Base.release();
5074218822Sdim        Idx.release();
5075218822Sdim        ExprOwningPtr<CXXOperatorCallExpr>
5076218822Sdim          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5077218822Sdim                                                          FnExpr, Args, 2,
5078218822Sdim                                                          ResultTy, RLoc));
5079218822Sdim
5080218822Sdim        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5081218822Sdim                                FnDecl))
5082218822Sdim          return ExprError();
5083218822Sdim
5084218822Sdim        return MaybeBindToTemporary(TheCall.release());
5085218822Sdim      } else {
5086218822Sdim        // We matched a built-in operator. Convert the arguments, then
5087218822Sdim        // break out so that we will build the appropriate built-in
5088218822Sdim        // operator node.
5089218822Sdim        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5090218822Sdim                                      Best->Conversions[0], "passing") ||
5091218822Sdim            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5092218822Sdim                                      Best->Conversions[1], "passing"))
5093218822Sdim          return ExprError();
5094218822Sdim
5095218822Sdim        break;
5096218822Sdim      }
5097218822Sdim    }
5098218822Sdim
5099218822Sdim    case OR_No_Viable_Function: {
5100218822Sdim      // No viable function; try to create a built-in operation, which will
5101218822Sdim      // produce an error. Then, show the non-viable candidates.
5102218822Sdim      OwningExprResult Result =
5103218822Sdim          CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5104218822Sdim      assert(Result.isInvalid() &&
510589857Sobrien             "C++ subscript operator overloading is missing candidates!");
510689857Sobrien      if (Result.isInvalid())
510789857Sobrien        PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
510889857Sobrien                                "[]", LLoc);
5109130561Sobrien      return move(Result);
5110218822Sdim    }
5111130561Sobrien
5112130561Sobrien    case OR_Ambiguous:
5113130561Sobrien      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
511489857Sobrien          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5115218822Sdim      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5116104834Sobrien                              "[]", LLoc);
5117218822Sdim      return ExprError();
5118218822Sdim
5119218822Sdim    case OR_Deleted:
5120218822Sdim      Diag(LLoc, diag::err_ovl_deleted_oper)
5121218822Sdim        << Best->Function->isDeleted() << "[]"
5122218822Sdim        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5123218822Sdim      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5124218822Sdim      return ExprError();
5125218822Sdim    }
5126218822Sdim
5127218822Sdim  // We matched a built-in operator; build it.
5128218822Sdim  Base.release();
5129218822Sdim  Idx.release();
5130218822Sdim  return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5131218822Sdim                                         Owned(Args[1]), RLoc);
5132218822Sdim}
5133218822Sdim
5134218822Sdim/// BuildCallToMemberFunction - Build a call to a member
5135218822Sdim/// function. MemExpr is the expression that refers to the member
5136218822Sdim/// function (and includes the object parameter), Args/NumArgs are the
5137218822Sdim/// arguments to the function call (not including the object
5138218822Sdim/// parameter). The caller needs to validate that the member
5139218822Sdim/// expression refers to a member function or an overloaded member
5140218822Sdim/// function.
5141218822SdimSema::ExprResult
5142218822SdimSema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5143218822Sdim                                SourceLocation LParenLoc, Expr **Args,
5144218822Sdim                                unsigned NumArgs, SourceLocation *CommaLocs,
5145218822Sdim                                SourceLocation RParenLoc) {
5146218822Sdim  // Dig out the member expression. This holds both the object
5147218822Sdim  // argument and the member function we're referring to.
5148218822Sdim  MemberExpr *MemExpr = 0;
5149218822Sdim  if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5150218822Sdim    MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5151218822Sdim  else
5152218822Sdim    MemExpr = dyn_cast<MemberExpr>(MemExprE);
5153218822Sdim  assert(MemExpr && "Building member call without member expression");
5154218822Sdim
5155218822Sdim  // Extract the object argument.
5156218822Sdim  Expr *ObjectArg = MemExpr->getBase();
5157218822Sdim
5158218822Sdim  CXXMethodDecl *Method = 0;
5159218822Sdim  if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5160218822Sdim      isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
5161218822Sdim    // Add overload candidates
5162218822Sdim    OverloadCandidateSet CandidateSet;
516389857Sobrien    DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
516489857Sobrien
5165130561Sobrien    for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5166218822Sdim         Func != FuncEnd; ++Func) {
516789857Sobrien      if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5168130561Sobrien        // If explicit template arguments were provided, we can't call a
516989857Sobrien        // non-template member function.
517089857Sobrien        if (MemExpr->hasExplicitTemplateArgumentList())
517189857Sobrien          continue;
517289857Sobrien
517389857Sobrien        AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
517489857Sobrien                           /*SuppressUserConversions=*/false);
517589857Sobrien      } else
517689857Sobrien        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
517789857Sobrien                                   MemExpr->hasExplicitTemplateArgumentList(),
517889857Sobrien                                   MemExpr->getTemplateArgs(),
517989857Sobrien                                   MemExpr->getNumTemplateArgs(),
5180218822Sdim                                   ObjectArg, Args, NumArgs,
5181218822Sdim                                   CandidateSet,
5182218822Sdim                                   /*SuppressUsedConversions=*/false);
5183218822Sdim    }
5184218822Sdim
5185218822Sdim    OverloadCandidateSet::iterator Best;
518689857Sobrien    switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
5187104834Sobrien    case OR_Success:
5188104834Sobrien      Method = cast<CXXMethodDecl>(Best->Function);
5189218822Sdim      break;
5190218822Sdim
5191218822Sdim    case OR_No_Viable_Function:
5192218822Sdim      Diag(MemExpr->getSourceRange().getBegin(),
5193218822Sdim           diag::err_ovl_no_viable_member_function_in_call)
5194218822Sdim        << DeclName << MemExprE->getSourceRange();
5195218822Sdim      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5196218822Sdim      // FIXME: Leaking incoming expressions!
5197104834Sobrien      return true;
5198218822Sdim
5199218822Sdim    case OR_Ambiguous:
5200218822Sdim      Diag(MemExpr->getSourceRange().getBegin(),
5201218822Sdim           diag::err_ovl_ambiguous_member_call)
5202218822Sdim        << DeclName << MemExprE->getSourceRange();
5203218822Sdim      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5204218822Sdim      // FIXME: Leaking incoming expressions!
5205218822Sdim      return true;
5206218822Sdim
5207218822Sdim    case OR_Deleted:
5208218822Sdim      Diag(MemExpr->getSourceRange().getBegin(),
5209218822Sdim           diag::err_ovl_deleted_member_call)
5210104834Sobrien        << Best->Function->isDeleted()
5211104834Sobrien        << DeclName << MemExprE->getSourceRange();
5212104834Sobrien      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
521389857Sobrien      // FIXME: Leaking incoming expressions!
5214104834Sobrien      return true;
5215104834Sobrien    }
521689857Sobrien
521789857Sobrien    FixOverloadedFunctionReference(MemExpr, Method);
521889857Sobrien  } else {
521989857Sobrien    Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
522089857Sobrien  }
522189857Sobrien
522289857Sobrien  assert(Method && "Member call to something that isn't a method?");
522389857Sobrien  ExprOwningPtr<CXXMemberCallExpr>
5224104834Sobrien    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
5225104834Sobrien                                                  NumArgs,
5226104834Sobrien                                  Method->getResultType().getNonReferenceType(),
5227218822Sdim                                  RParenLoc));
5228104834Sobrien
5229218822Sdim  // Check for a valid return type.
5230218822Sdim  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5231218822Sdim                          TheCall.get(), Method))
5232218822Sdim    return true;
5233218822Sdim
5234218822Sdim  // Convert the object argument (for a non-static member function call).
523589857Sobrien  if (!Method->isStatic() &&
523689857Sobrien      PerformObjectArgumentInitialization(ObjectArg, Method))
5237104834Sobrien    return true;
523889857Sobrien  MemExpr->setBase(ObjectArg);
523989857Sobrien
524089857Sobrien  // Convert the rest of the arguments
524189857Sobrien  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
524289857Sobrien  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
5243130561Sobrien                              RParenLoc))
5244130561Sobrien    return true;
5245130561Sobrien
524689857Sobrien  if (CheckFunctionCall(Method, TheCall.get()))
5247130561Sobrien    return true;
524889857Sobrien
524989857Sobrien  return MaybeBindToTemporary(TheCall.release()).release();
5250130561Sobrien}
525189857Sobrien
525289857Sobrien/// BuildCallToObjectOfClassType - Build a call to an object of class
5253130561Sobrien/// type (C++ [over.call.object]), which can end up invoking an
5254130561Sobrien/// overloaded function call operator (@c operator()) or performing a
5255130561Sobrien/// user-defined conversion on the object argument.
525689857SobrienSema::ExprResult
525789857SobrienSema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
5258130561Sobrien                                   SourceLocation LParenLoc,
525989857Sobrien                                   Expr **Args, unsigned NumArgs,
526089857Sobrien                                   SourceLocation *CommaLocs,
5261130561Sobrien                                   SourceLocation RParenLoc) {
526289857Sobrien  assert(Object->getType()->isRecordType() && "Requires object type argument");
526389857Sobrien  const RecordType *Record = Object->getType()->getAs<RecordType>();
526489857Sobrien
526589857Sobrien  // C++ [over.call.object]p1:
526689857Sobrien  //  If the primary-expression E in the function call syntax
5267130561Sobrien  //  evaluates to a class object of type "cv T", then the set of
5268130561Sobrien  //  candidate functions includes at least the function call
5269130561Sobrien  //  operators of T. The function call operators of T are obtained by
527089857Sobrien  //  ordinary lookup of the name operator() in the context of
527189857Sobrien  //  (E).operator().
5272130561Sobrien  OverloadCandidateSet CandidateSet;
5273130561Sobrien  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
5274130561Sobrien
5275130561Sobrien  if (RequireCompleteType(LParenLoc, Object->getType(),
5276130561Sobrien                          PartialDiagnostic(diag::err_incomplete_object_call)
5277130561Sobrien                          << Object->getSourceRange()))
5278130561Sobrien    return true;
5279130561Sobrien
5280218822Sdim  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5281218822Sdim  LookupQualifiedName(R, Record->getDecl());
5282218822Sdim  R.suppressDiagnostics();
5283130561Sobrien
5284130561Sobrien  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5285130561Sobrien       Oper != OperEnd; ++Oper) {
5286130561Sobrien    AddMethodCandidate(*Oper, Object, Args, NumArgs, CandidateSet,
5287130561Sobrien                       /*SuppressUserConversions=*/ false);
5288130561Sobrien  }
5289130561Sobrien
5290130561Sobrien  // C++ [over.call.object]p2:
5291130561Sobrien  //   In addition, for each conversion function declared in T of the
5292130561Sobrien  //   form
5293130561Sobrien  //
529489857Sobrien  //        operator conversion-type-id () cv-qualifier;
529589857Sobrien  //
5296130561Sobrien  //   where cv-qualifier is the same cv-qualification as, or a
5297130561Sobrien  //   greater cv-qualification than, cv, and where conversion-type-id
5298130561Sobrien  //   denotes the type "pointer to function of (P1,...,Pn) returning
5299130561Sobrien  //   R", or the type "reference to pointer to function of
5300130561Sobrien  //   (P1,...,Pn) returning R", or the type "reference to function
5301130561Sobrien  //   of (P1,...,Pn) returning R", a surrogate call function [...]
5302130561Sobrien  //   is also considered as a candidate function. Similarly,
5303130561Sobrien  //   surrogate call functions are added to the set of candidate
5304130561Sobrien  //   functions for each conversion function declared in an
5305130561Sobrien  //   accessible base class provided the function is not hidden
5306130561Sobrien  //   within T by another intervening declaration.
5307130561Sobrien  // FIXME: Look in base classes for more conversion operators!
5308130561Sobrien  OverloadedFunctionDecl *Conversions
5309130561Sobrien    = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5310130561Sobrien  for (OverloadedFunctionDecl::function_iterator
5311130561Sobrien         Func = Conversions->function_begin(),
5312130561Sobrien         FuncEnd = Conversions->function_end();
5313130561Sobrien       Func != FuncEnd; ++Func) {
5314130561Sobrien    CXXConversionDecl *Conv;
5315130561Sobrien    FunctionTemplateDecl *ConvTemplate;
5316130561Sobrien    GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
5317130561Sobrien
5318130561Sobrien    // Skip over templated conversion functions; they aren't
5319130561Sobrien    // surrogates.
5320130561Sobrien    if (ConvTemplate)
5321130561Sobrien      continue;
5322130561Sobrien
5323130561Sobrien    // Strip the reference type (if any) and then the pointer type (if
5324130561Sobrien    // any) to get down to what might be a function type.
532589857Sobrien    QualType ConvType = Conv->getConversionType().getNonReferenceType();
532689857Sobrien    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
532789857Sobrien      ConvType = ConvPtrType->getPointeeType();
532889857Sobrien
532989857Sobrien    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
533089857Sobrien      AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
5331130561Sobrien  }
5332130561Sobrien
5333130561Sobrien  // Perform overload resolution.
5334130561Sobrien  OverloadCandidateSet::iterator Best;
5335130561Sobrien  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
5336130561Sobrien  case OR_Success:
5337130561Sobrien    // Overload resolution succeeded; we'll build the appropriate call
5338130561Sobrien    // below.
5339130561Sobrien    break;
5340130561Sobrien
5341130561Sobrien  case OR_No_Viable_Function:
5342130561Sobrien    Diag(Object->getSourceRange().getBegin(),
5343130561Sobrien         diag::err_ovl_no_viable_object_call)
5344130561Sobrien      << Object->getType() << Object->getSourceRange();
5345130561Sobrien    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5346130561Sobrien    break;
5347130561Sobrien
5348130561Sobrien  case OR_Ambiguous:
5349130561Sobrien    Diag(Object->getSourceRange().getBegin(),
535089857Sobrien         diag::err_ovl_ambiguous_object_call)
535189857Sobrien      << Object->getType() << Object->getSourceRange();
535289857Sobrien    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
535389857Sobrien    break;
535489857Sobrien
535589857Sobrien  case OR_Deleted:
535689857Sobrien    Diag(Object->getSourceRange().getBegin(),
5357104834Sobrien         diag::err_ovl_deleted_object_call)
5358104834Sobrien      << Best->Function->isDeleted()
5359104834Sobrien      << Object->getType() << Object->getSourceRange();
536089857Sobrien    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5361130561Sobrien    break;
536289857Sobrien  }
5363130561Sobrien
536489857Sobrien  if (Best == CandidateSet.end()) {
5365130561Sobrien    // We had an error; delete all of the subexpressions and return
5366130561Sobrien    // the error.
5367130561Sobrien    Object->Destroy(Context);
5368218822Sdim    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5369130561Sobrien      Args[ArgIdx]->Destroy(Context);
537089857Sobrien    return true;
537189857Sobrien  }
537289857Sobrien
537389857Sobrien  if (Best->Function == 0) {
537489857Sobrien    // Since there is no function declaration, this is one of the
537589857Sobrien    // surrogate candidates. Dig out the conversion function.
537689857Sobrien    CXXConversionDecl *Conv
5377130561Sobrien      = cast<CXXConversionDecl>(
537889857Sobrien                         Best->Conversions[0].UserDefined.ConversionFunction);
537989857Sobrien
5380218822Sdim    // We selected one of the surrogate functions that converts the
5381218822Sdim    // object parameter to a function pointer. Perform the conversion
5382218822Sdim    // on the object argument, then let ActOnCallExpr finish the job.
5383218822Sdim
5384218822Sdim    // Create an implicit member expr to refer to the conversion operator.
5385218822Sdim    // and then call it.
5386218822Sdim    CXXMemberCallExpr *CE =
5387218822Sdim    BuildCXXMemberCallExpr(Object, Conv);
5388218822Sdim
5389218822Sdim    return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
5390218822Sdim                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5391218822Sdim                         CommaLocs, RParenLoc).release();
5392218822Sdim  }
5393218822Sdim
5394218822Sdim  // We found an overloaded operator(). Build a CXXOperatorCallExpr
5395218822Sdim  // that calls this method, using Object for the implicit object
5396218822Sdim  // parameter and passing along the remaining arguments.
5397218822Sdim  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5398218822Sdim  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
5399218822Sdim
5400218822Sdim  unsigned NumArgsInProto = Proto->getNumArgs();
5401218822Sdim  unsigned NumArgsToCheck = NumArgs;
5402218822Sdim
5403218822Sdim  // Build the full argument list for the method call (the
5404218822Sdim  // implicit object parameter is placed at the beginning of the
5405218822Sdim  // list).
5406218822Sdim  Expr **MethodArgs;
5407218822Sdim  if (NumArgs < NumArgsInProto) {
5408218822Sdim    NumArgsToCheck = NumArgsInProto;
5409218822Sdim    MethodArgs = new Expr*[NumArgsInProto + 1];
5410218822Sdim  } else {
5411218822Sdim    MethodArgs = new Expr*[NumArgs + 1];
5412218822Sdim  }
5413218822Sdim  MethodArgs[0] = Object;
5414218822Sdim  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5415218822Sdim    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
5416218822Sdim
5417218822Sdim  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
5418218822Sdim                                          SourceLocation());
5419218822Sdim  UsualUnaryConversions(NewFn);
5420218822Sdim
5421218822Sdim  // Once we've built TheCall, all of the expressions are properly
5422218822Sdim  // owned.
5423218822Sdim  QualType ResultTy = Method->getResultType().getNonReferenceType();
5424218822Sdim  ExprOwningPtr<CXXOperatorCallExpr>
5425218822Sdim    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
5426218822Sdim                                                    MethodArgs, NumArgs + 1,
5427218822Sdim                                                    ResultTy, RParenLoc));
5428218822Sdim  delete [] MethodArgs;
5429218822Sdim
5430218822Sdim  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5431218822Sdim                          Method))
5432218822Sdim    return true;
5433218822Sdim
5434218822Sdim  // We may have default arguments. If so, we need to allocate more
5435218822Sdim  // slots in the call for them.
5436218822Sdim  if (NumArgs < NumArgsInProto)
5437218822Sdim    TheCall->setNumArgs(Context, NumArgsInProto + 1);
5438218822Sdim  else if (NumArgs > NumArgsInProto)
5439218822Sdim    NumArgsToCheck = NumArgsInProto;
5440218822Sdim
5441218822Sdim  bool IsError = false;
5442218822Sdim
5443218822Sdim  // Initialize the implicit object parameter.
5444218822Sdim  IsError |= PerformObjectArgumentInitialization(Object, Method);
5445218822Sdim  TheCall->setArg(0, Object);
5446218822Sdim
5447218822Sdim
5448218822Sdim  // Check the argument types.
5449218822Sdim  for (unsigned i = 0; i != NumArgsToCheck; i++) {
5450218822Sdim    Expr *Arg;
5451218822Sdim    if (i < NumArgs) {
5452218822Sdim      Arg = Args[i];
5453218822Sdim
5454218822Sdim      // Pass the argument.
5455218822Sdim      QualType ProtoArgType = Proto->getArgType(i);
5456218822Sdim      IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
5457218822Sdim    } else {
5458218822Sdim      OwningExprResult DefArg
5459218822Sdim        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5460218822Sdim      if (DefArg.isInvalid()) {
5461218822Sdim        IsError = true;
5462218822Sdim        break;
5463218822Sdim      }
5464218822Sdim
5465218822Sdim      Arg = DefArg.takeAs<Expr>();
5466218822Sdim    }
5467218822Sdim
5468218822Sdim    TheCall->setArg(i + 1, Arg);
5469218822Sdim  }
5470218822Sdim
5471218822Sdim  // If this is a variadic call, handle args passed through "...".
5472218822Sdim  if (Proto->isVariadic()) {
5473218822Sdim    // Promote the arguments (C99 6.5.2.2p7).
5474218822Sdim    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5475218822Sdim      Expr *Arg = Args[i];
5476218822Sdim      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
5477218822Sdim      TheCall->setArg(i + 1, Arg);
5478218822Sdim    }
5479218822Sdim  }
5480218822Sdim
5481218822Sdim  if (IsError) return true;
5482218822Sdim
5483218822Sdim  if (CheckFunctionCall(Method, TheCall.get()))
5484218822Sdim    return true;
5485218822Sdim
5486218822Sdim  return MaybeBindToTemporary(TheCall.release()).release();
5487218822Sdim}
5488218822Sdim
5489218822Sdim/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
5490218822Sdim///  (if one exists), where @c Base is an expression of class type and
5491218822Sdim/// @c Member is the name of the member we're trying to find.
5492218822SdimSema::OwningExprResult
5493218822SdimSema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5494218822Sdim  Expr *Base = static_cast<Expr *>(BaseIn.get());
5495218822Sdim  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
5496218822Sdim
5497218822Sdim  // C++ [over.ref]p1:
5498218822Sdim  //
5499218822Sdim  //   [...] An expression x->m is interpreted as (x.operator->())->m
5500218822Sdim  //   for a class object x of type T if T::operator->() exists and if
5501218822Sdim  //   the operator is selected as the best match function by the
5502218822Sdim  //   overload resolution mechanism (13.3).
5503218822Sdim  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5504218822Sdim  OverloadCandidateSet CandidateSet;
5505218822Sdim  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
5506218822Sdim
5507218822Sdim  if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5508218822Sdim                          PDiag(diag::err_typecheck_incomplete_tag)
5509218822Sdim                            << Base->getSourceRange()))
5510218822Sdim    return ExprError();
5511218822Sdim
5512218822Sdim  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5513218822Sdim  LookupQualifiedName(R, BaseRecord->getDecl());
5514218822Sdim  R.suppressDiagnostics();
5515218822Sdim
5516218822Sdim  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5517218822Sdim       Oper != OperEnd; ++Oper)
5518218822Sdim    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
5519218822Sdim                       /*SuppressUserConversions=*/false);
5520218822Sdim
5521218822Sdim  // Perform overload resolution.
5522218822Sdim  OverloadCandidateSet::iterator Best;
5523218822Sdim  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5524218822Sdim  case OR_Success:
5525218822Sdim    // Overload resolution succeeded; we'll build the call below.
5526218822Sdim    break;
5527218822Sdim
5528218822Sdim  case OR_No_Viable_Function:
5529218822Sdim    if (CandidateSet.empty())
5530218822Sdim      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5531218822Sdim        << Base->getType() << Base->getSourceRange();
5532218822Sdim    else
5533218822Sdim      Diag(OpLoc, diag::err_ovl_no_viable_oper)
5534218822Sdim        << "operator->" << Base->getSourceRange();
5535218822Sdim    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5536218822Sdim    return ExprError();
5537218822Sdim
5538218822Sdim  case OR_Ambiguous:
5539218822Sdim    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5540218822Sdim      << "->" << Base->getSourceRange();
5541218822Sdim    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5542218822Sdim    return ExprError();
5543218822Sdim
5544218822Sdim  case OR_Deleted:
5545218822Sdim    Diag(OpLoc,  diag::err_ovl_deleted_oper)
5546218822Sdim      << Best->Function->isDeleted()
5547218822Sdim      << "->" << Base->getSourceRange();
5548218822Sdim    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5549218822Sdim    return ExprError();
5550218822Sdim  }
5551218822Sdim
5552218822Sdim  // Convert the object parameter.
5553218822Sdim  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5554218822Sdim  if (PerformObjectArgumentInitialization(Base, Method))
5555218822Sdim    return ExprError();
5556218822Sdim
5557218822Sdim  // No concerns about early exits now.
5558218822Sdim  BaseIn.release();
5559218822Sdim
5560218822Sdim  // Build the operator call.
5561218822Sdim  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5562218822Sdim                                           SourceLocation());
5563218822Sdim  UsualUnaryConversions(FnExpr);
5564218822Sdim
5565218822Sdim  QualType ResultTy = Method->getResultType().getNonReferenceType();
5566218822Sdim  ExprOwningPtr<CXXOperatorCallExpr>
5567218822Sdim    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5568218822Sdim                                                    &Base, 1, ResultTy, OpLoc));
5569218822Sdim
5570218822Sdim  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5571218822Sdim                          Method))
5572218822Sdim          return ExprError();
5573218822Sdim  return move(TheCall);
5574218822Sdim}
5575218822Sdim
5576218822Sdim/// FixOverloadedFunctionReference - E is an expression that refers to
5577218822Sdim/// a C++ overloaded function (possibly with some parentheses and
5578218822Sdim/// perhaps a '&' around it). We have resolved the overloaded function
5579218822Sdim/// to the function declaration Fn, so patch up the expression E to
5580218822Sdim/// refer (possibly indirectly) to Fn. Returns the new expr.
5581218822SdimExpr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5582218822Sdim  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5583218822Sdim    Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5584218822Sdim    PE->setSubExpr(NewExpr);
5585218822Sdim    PE->setType(NewExpr->getType());
5586218822Sdim  } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5587218822Sdim    Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5588218822Sdim    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5589218822Sdim                               NewExpr->getType()) &&
5590218822Sdim           "Implicit cast type cannot be determined from overload");
5591218822Sdim    ICE->setSubExpr(NewExpr);
5592218822Sdim  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
5593218822Sdim    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
5594218822Sdim           "Can only take the address of an overloaded function");
5595218822Sdim    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5596218822Sdim      if (Method->isStatic()) {
5597218822Sdim        // Do nothing: static member functions aren't any different
5598218822Sdim        // from non-member functions.
5599218822Sdim      } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5600218822Sdim        if (DRE->getQualifier()) {
5601218822Sdim          // We have taken the address of a pointer to member
5602218822Sdim          // function. Perform the computation here so that we get the
5603218822Sdim          // appropriate pointer to member type.
5604218822Sdim          DRE->setDecl(Fn);
560589857Sobrien          DRE->setType(Fn->getType());
560689857Sobrien          QualType ClassType
560789857Sobrien            = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5608218822Sdim          E->setType(Context.getMemberPointerType(Fn->getType(),
5609130561Sobrien                                                  ClassType.getTypePtr()));
5610130561Sobrien          return E;
561189857Sobrien        }
561289857Sobrien      }
561389857Sobrien      // FIXME: TemplateIdRefExpr referring to a member function template
5614130561Sobrien      // specialization!
5615130561Sobrien    }
5616130561Sobrien    Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5617130561Sobrien    UnOp->setSubExpr(NewExpr);
561889857Sobrien    UnOp->setType(Context.getPointerType(NewExpr->getType()));
5619130561Sobrien
5620130561Sobrien    return UnOp;
5621130561Sobrien  } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
562289857Sobrien    assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
5623130561Sobrien            isa<FunctionTemplateDecl>(DR->getDecl()) ||
5624130561Sobrien            isa<FunctionDecl>(DR->getDecl())) &&
562594536Sobrien           "Expected function or function template");
5626130561Sobrien    DR->setDecl(Fn);
562789857Sobrien    E->setType(Fn->getType());
562889857Sobrien  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5629218822Sdim    MemExpr->setMemberDecl(Fn);
5630218822Sdim    E->setType(Fn->getType());
5631218822Sdim  } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
5632218822Sdim    E = DeclRefExpr::Create(Context,
5633218822Sdim                            TID->getQualifier(), TID->getQualifierRange(),
5634218822Sdim                            Fn, TID->getTemplateNameLoc(),
5635218822Sdim                            true,
5636218822Sdim                            TID->getLAngleLoc(),
5637218822Sdim                            TID->getTemplateArgs(),
5638218822Sdim                            TID->getNumTemplateArgs(),
5639218822Sdim                            TID->getRAngleLoc(),
5640218822Sdim                            Fn->getType(),
5641218822Sdim                            /*FIXME?*/false, /*FIXME?*/false);
5642218822Sdim
5643218822Sdim    // FIXME: Don't destroy TID here, since we need its template arguments
5644218822Sdim    // to survive.
5645218822Sdim    // TID->Destroy(Context);
5646218822Sdim  } else if (isa<UnresolvedFunctionNameExpr>(E)) {
564789857Sobrien    return DeclRefExpr::Create(Context,
564889857Sobrien                               /*Qualifier=*/0,
5649130561Sobrien                               /*QualifierRange=*/SourceRange(),
5650130561Sobrien                               Fn, E->getLocStart(),
565189857Sobrien                               Fn->getType(), false, false);
5652130561Sobrien  } else {
5653130561Sobrien    assert(false && "Invalid reference to overloaded function");
5654130561Sobrien  }
5655130561Sobrien
5656130561Sobrien  return E;
5657130561Sobrien}
5658130561Sobrien
565989857Sobrien} // end namespace clang
5660130561Sobrien