]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaOverload.cpp
Update clang to r86025.
[FreeBSD/FreeBSD.git] / lib / Sema / SemaOverload.cpp
1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Sema.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/Compiler.h"
26 #include <algorithm>
27 #include <cstdio>
28
29 namespace clang {
30
31 /// GetConversionCategory - Retrieve the implicit conversion
32 /// category corresponding to the given implicit conversion kind.
33 ImplicitConversionCategory
34 GetConversionCategory(ImplicitConversionKind Kind) {
35   static const ImplicitConversionCategory
36     Category[(int)ICK_Num_Conversion_Kinds] = {
37     ICC_Identity,
38     ICC_Lvalue_Transformation,
39     ICC_Lvalue_Transformation,
40     ICC_Lvalue_Transformation,
41     ICC_Qualification_Adjustment,
42     ICC_Promotion,
43     ICC_Promotion,
44     ICC_Promotion,
45     ICC_Conversion,
46     ICC_Conversion,
47     ICC_Conversion,
48     ICC_Conversion,
49     ICC_Conversion,
50     ICC_Conversion,
51     ICC_Conversion,
52     ICC_Conversion,
53     ICC_Conversion,
54     ICC_Conversion
55   };
56   return Category[(int)Kind];
57 }
58
59 /// GetConversionRank - Retrieve the implicit conversion rank
60 /// corresponding to the given implicit conversion kind.
61 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62   static const ImplicitConversionRank
63     Rank[(int)ICK_Num_Conversion_Kinds] = {
64     ICR_Exact_Match,
65     ICR_Exact_Match,
66     ICR_Exact_Match,
67     ICR_Exact_Match,
68     ICR_Exact_Match,
69     ICR_Promotion,
70     ICR_Promotion,
71     ICR_Promotion,
72     ICR_Conversion,
73     ICR_Conversion,
74     ICR_Conversion,
75     ICR_Conversion,
76     ICR_Conversion,
77     ICR_Conversion,
78     ICR_Conversion,
79     ICR_Conversion,
80     ICR_Conversion,
81     ICR_Conversion
82   };
83   return Rank[(int)Kind];
84 }
85
86 /// GetImplicitConversionName - Return the name of this kind of
87 /// implicit conversion.
88 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89   static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90     "No conversion",
91     "Lvalue-to-rvalue",
92     "Array-to-pointer",
93     "Function-to-pointer",
94     "Qualification",
95     "Integral promotion",
96     "Floating point promotion",
97     "Complex promotion",
98     "Integral conversion",
99     "Floating conversion",
100     "Complex conversion",
101     "Floating-integral conversion",
102     "Complex-real conversion",
103     "Pointer conversion",
104     "Pointer-to-member conversion",
105     "Boolean conversion",
106     "Compatible-types conversion",
107     "Derived-to-base conversion"
108   };
109   return Name[Kind];
110 }
111
112 /// StandardConversionSequence - Set the standard conversion
113 /// sequence to the identity conversion.
114 void StandardConversionSequence::setAsIdentityConversion() {
115   First = ICK_Identity;
116   Second = ICK_Identity;
117   Third = ICK_Identity;
118   Deprecated = false;
119   ReferenceBinding = false;
120   DirectBinding = false;
121   RRefBinding = false;
122   CopyConstructor = 0;
123 }
124
125 /// getRank - Retrieve the rank of this standard conversion sequence
126 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127 /// implicit conversions.
128 ImplicitConversionRank StandardConversionSequence::getRank() const {
129   ImplicitConversionRank Rank = ICR_Exact_Match;
130   if  (GetConversionRank(First) > Rank)
131     Rank = GetConversionRank(First);
132   if  (GetConversionRank(Second) > Rank)
133     Rank = GetConversionRank(Second);
134   if  (GetConversionRank(Third) > Rank)
135     Rank = GetConversionRank(Third);
136   return Rank;
137 }
138
139 /// isPointerConversionToBool - Determines whether this conversion is
140 /// a conversion of a pointer or pointer-to-member to bool. This is
141 /// used as part of the ranking of standard conversion sequences
142 /// (C++ 13.3.3.2p4).
143 bool StandardConversionSequence::isPointerConversionToBool() const {
144   QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145   QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147   // Note that FromType has not necessarily been transformed by the
148   // array-to-pointer or function-to-pointer implicit conversions, so
149   // check for their presence as well as checking whether FromType is
150   // a pointer.
151   if (ToType->isBooleanType() &&
152       (FromType->isPointerType() || FromType->isBlockPointerType() ||
153        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154     return true;
155
156   return false;
157 }
158
159 /// isPointerConversionToVoidPointer - Determines whether this
160 /// conversion is a conversion of a pointer to a void pointer. This is
161 /// used as part of the ranking of standard conversion sequences (C++
162 /// 13.3.3.2p4).
163 bool
164 StandardConversionSequence::
165 isPointerConversionToVoidPointer(ASTContext& Context) const {
166   QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167   QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169   // Note that FromType has not necessarily been transformed by the
170   // array-to-pointer implicit conversion, so check for its presence
171   // and redo the conversion to get a pointer.
172   if (First == ICK_Array_To_Pointer)
173     FromType = Context.getArrayDecayedType(FromType);
174
175   if (Second == ICK_Pointer_Conversion)
176     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
177       return ToPtrType->getPointeeType()->isVoidType();
178
179   return false;
180 }
181
182 /// DebugPrint - Print this standard conversion sequence to standard
183 /// error. Useful for debugging overloading issues.
184 void StandardConversionSequence::DebugPrint() const {
185   bool PrintedSomething = false;
186   if (First != ICK_Identity) {
187     fprintf(stderr, "%s", GetImplicitConversionName(First));
188     PrintedSomething = true;
189   }
190
191   if (Second != ICK_Identity) {
192     if (PrintedSomething) {
193       fprintf(stderr, " -> ");
194     }
195     fprintf(stderr, "%s", GetImplicitConversionName(Second));
196
197     if (CopyConstructor) {
198       fprintf(stderr, " (by copy constructor)");
199     } else if (DirectBinding) {
200       fprintf(stderr, " (direct reference binding)");
201     } else if (ReferenceBinding) {
202       fprintf(stderr, " (reference binding)");
203     }
204     PrintedSomething = true;
205   }
206
207   if (Third != ICK_Identity) {
208     if (PrintedSomething) {
209       fprintf(stderr, " -> ");
210     }
211     fprintf(stderr, "%s", GetImplicitConversionName(Third));
212     PrintedSomething = true;
213   }
214
215   if (!PrintedSomething) {
216     fprintf(stderr, "No conversions required");
217   }
218 }
219
220 /// DebugPrint - Print this user-defined conversion sequence to standard
221 /// error. Useful for debugging overloading issues.
222 void UserDefinedConversionSequence::DebugPrint() const {
223   if (Before.First || Before.Second || Before.Third) {
224     Before.DebugPrint();
225     fprintf(stderr, " -> ");
226   }
227   fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
228   if (After.First || After.Second || After.Third) {
229     fprintf(stderr, " -> ");
230     After.DebugPrint();
231   }
232 }
233
234 /// DebugPrint - Print this implicit conversion sequence to standard
235 /// error. Useful for debugging overloading issues.
236 void ImplicitConversionSequence::DebugPrint() const {
237   switch (ConversionKind) {
238   case StandardConversion:
239     fprintf(stderr, "Standard conversion: ");
240     Standard.DebugPrint();
241     break;
242   case UserDefinedConversion:
243     fprintf(stderr, "User-defined conversion: ");
244     UserDefined.DebugPrint();
245     break;
246   case EllipsisConversion:
247     fprintf(stderr, "Ellipsis conversion");
248     break;
249   case BadConversion:
250     fprintf(stderr, "Bad conversion");
251     break;
252   }
253
254   fprintf(stderr, "\n");
255 }
256
257 // IsOverload - Determine whether the given New declaration is an
258 // overload of the Old declaration. This routine returns false if New
259 // and Old cannot be overloaded, e.g., if they are functions with the
260 // same signature (C++ 1.3.10) or if the Old declaration isn't a
261 // function (or overload set). When it does return false and Old is an
262 // OverloadedFunctionDecl, MatchedDecl will be set to point to the
263 // FunctionDecl that New cannot be overloaded with.
264 //
265 // Example: Given the following input:
266 //
267 //   void f(int, float); // #1
268 //   void f(int, int); // #2
269 //   int f(int, int); // #3
270 //
271 // When we process #1, there is no previous declaration of "f",
272 // so IsOverload will not be used.
273 //
274 // When we process #2, Old is a FunctionDecl for #1.  By comparing the
275 // parameter types, we see that #1 and #2 are overloaded (since they
276 // have different signatures), so this routine returns false;
277 // MatchedDecl is unchanged.
278 //
279 // When we process #3, Old is an OverloadedFunctionDecl containing #1
280 // and #2. We compare the signatures of #3 to #1 (they're overloaded,
281 // so we do nothing) and then #3 to #2. Since the signatures of #3 and
282 // #2 are identical (return types of functions are not part of the
283 // signature), IsOverload returns false and MatchedDecl will be set to
284 // point to the FunctionDecl for #2.
285 bool
286 Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287                  OverloadedFunctionDecl::function_iterator& MatchedDecl) {
288   if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289     // Is this new function an overload of every function in the
290     // overload set?
291     OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292                                            FuncEnd = Ovl->function_end();
293     for (; Func != FuncEnd; ++Func) {
294       if (!IsOverload(New, *Func, MatchedDecl)) {
295         MatchedDecl = Func;
296         return false;
297       }
298     }
299
300     // This function overloads every function in the overload set.
301     return true;
302   } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303     return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304   else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
305     FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
306     FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
308     // C++ [temp.fct]p2:
309     //   A function template can be overloaded with other function templates
310     //   and with normal (non-template) functions.
311     if ((OldTemplate == 0) != (NewTemplate == 0))
312       return true;
313
314     // Is the function New an overload of the function Old?
315     QualType OldQType = Context.getCanonicalType(Old->getType());
316     QualType NewQType = Context.getCanonicalType(New->getType());
317
318     // Compare the signatures (C++ 1.3.10) of the two functions to
319     // determine whether they are overloads. If we find any mismatch
320     // in the signature, they are overloads.
321
322     // If either of these functions is a K&R-style function (no
323     // prototype), then we consider them to have matching signatures.
324     if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325         isa<FunctionNoProtoType>(NewQType.getTypePtr()))
326       return false;
327
328     FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329     FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
330
331     // The signature of a function includes the types of its
332     // parameters (C++ 1.3.10), which includes the presence or absence
333     // of the ellipsis; see C++ DR 357).
334     if (OldQType != NewQType &&
335         (OldType->getNumArgs() != NewType->getNumArgs() ||
336          OldType->isVariadic() != NewType->isVariadic() ||
337          !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338                      NewType->arg_type_begin())))
339       return true;
340
341     // C++ [temp.over.link]p4:
342     //   The signature of a function template consists of its function
343     //   signature, its return type and its template parameter list. The names
344     //   of the template parameters are significant only for establishing the
345     //   relationship between the template parameters and the rest of the
346     //   signature.
347     //
348     // We check the return type and template parameter lists for function
349     // templates first; the remaining checks follow.
350     if (NewTemplate &&
351         (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352                                          OldTemplate->getTemplateParameters(),
353                                          false, false, SourceLocation()) ||
354          OldType->getResultType() != NewType->getResultType()))
355       return true;
356
357     // If the function is a class member, its signature includes the
358     // cv-qualifiers (if any) on the function itself.
359     //
360     // As part of this, also check whether one of the member functions
361     // is static, in which case they are not overloads (C++
362     // 13.1p2). While not part of the definition of the signature,
363     // this check is important to determine whether these functions
364     // can be overloaded.
365     CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366     CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
367     if (OldMethod && NewMethod &&
368         !OldMethod->isStatic() && !NewMethod->isStatic() &&
369         OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
370       return true;
371
372     // The signatures match; this is not an overload.
373     return false;
374   } else {
375     // (C++ 13p1):
376     //   Only function declarations can be overloaded; object and type
377     //   declarations cannot be overloaded.
378     return false;
379   }
380 }
381
382 /// TryImplicitConversion - Attempt to perform an implicit conversion
383 /// from the given expression (Expr) to the given type (ToType). This
384 /// function returns an implicit conversion sequence that can be used
385 /// to perform the initialization. Given
386 ///
387 ///   void f(float f);
388 ///   void g(int i) { f(i); }
389 ///
390 /// this routine would produce an implicit conversion sequence to
391 /// describe the initialization of f from i, which will be a standard
392 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
393 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
394 //
395 /// Note that this routine only determines how the conversion can be
396 /// performed; it does not actually perform the conversion. As such,
397 /// it will not produce any diagnostics if no conversion is available,
398 /// but will instead return an implicit conversion sequence of kind
399 /// "BadConversion".
400 ///
401 /// If @p SuppressUserConversions, then user-defined conversions are
402 /// not permitted.
403 /// If @p AllowExplicit, then explicit user-defined conversions are
404 /// permitted.
405 /// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406 /// no matter its actual lvalueness.
407 /// If @p UserCast, the implicit conversion is being done for a user-specified
408 /// cast.
409 ImplicitConversionSequence
410 Sema::TryImplicitConversion(Expr* From, QualType ToType,
411                             bool SuppressUserConversions,
412                             bool AllowExplicit, bool ForceRValue,
413                             bool InOverloadResolution,
414                             bool UserCast) {
415   ImplicitConversionSequence ICS;
416   OverloadCandidateSet Conversions;
417   OverloadingResult UserDefResult = OR_Success;
418   if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
419     ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
420   else if (getLangOptions().CPlusPlus &&
421            (UserDefResult = IsUserDefinedConversion(From, ToType, 
422                                    ICS.UserDefined,
423                                    Conversions,
424                                    !SuppressUserConversions, AllowExplicit,
425                                    ForceRValue, UserCast)) == OR_Success) {
426     ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
427     // C++ [over.ics.user]p4:
428     //   A conversion of an expression of class type to the same class
429     //   type is given Exact Match rank, and a conversion of an
430     //   expression of class type to a base class of that type is
431     //   given Conversion rank, in spite of the fact that a copy
432     //   constructor (i.e., a user-defined conversion function) is
433     //   called for those cases.
434     if (CXXConstructorDecl *Constructor
435           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
436       QualType FromCanon
437         = Context.getCanonicalType(From->getType().getUnqualifiedType());
438       QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
439       if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
440         // Turn this into a "standard" conversion sequence, so that it
441         // gets ranked with standard conversion sequences.
442         ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
443         ICS.Standard.setAsIdentityConversion();
444         ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
445         ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
446         ICS.Standard.CopyConstructor = Constructor;
447         if (ToCanon != FromCanon)
448           ICS.Standard.Second = ICK_Derived_To_Base;
449       }
450     }
451
452     // C++ [over.best.ics]p4:
453     //   However, when considering the argument of a user-defined
454     //   conversion function that is a candidate by 13.3.1.3 when
455     //   invoked for the copying of the temporary in the second step
456     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
457     //   13.3.1.6 in all cases, only standard conversion sequences and
458     //   ellipsis conversion sequences are allowed.
459     if (SuppressUserConversions &&
460         ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
461       ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
462   } else {
463     ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
464     if (UserDefResult == OR_Ambiguous) {
465       for (OverloadCandidateSet::iterator Cand = Conversions.begin();
466            Cand != Conversions.end(); ++Cand)
467         if (Cand->Viable)
468           ICS.ConversionFunctionSet.push_back(Cand->Function);
469     }
470   }
471
472   return ICS;
473 }
474
475 /// IsStandardConversion - Determines whether there is a standard
476 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
477 /// expression From to the type ToType. Standard conversion sequences
478 /// only consider non-class types; for conversions that involve class
479 /// types, use TryImplicitConversion. If a conversion exists, SCS will
480 /// contain the standard conversion sequence required to perform this
481 /// conversion and this routine will return true. Otherwise, this
482 /// routine will return false and the value of SCS is unspecified.
483 bool
484 Sema::IsStandardConversion(Expr* From, QualType ToType,
485                            bool InOverloadResolution,
486                            StandardConversionSequence &SCS) {
487   QualType FromType = From->getType();
488
489   // Standard conversions (C++ [conv])
490   SCS.setAsIdentityConversion();
491   SCS.Deprecated = false;
492   SCS.IncompatibleObjC = false;
493   SCS.FromTypePtr = FromType.getAsOpaquePtr();
494   SCS.CopyConstructor = 0;
495
496   // There are no standard conversions for class types in C++, so
497   // abort early. When overloading in C, however, we do permit
498   if (FromType->isRecordType() || ToType->isRecordType()) {
499     if (getLangOptions().CPlusPlus)
500       return false;
501
502     // When we're overloading in C, we allow, as standard conversions,
503   }
504
505   // The first conversion can be an lvalue-to-rvalue conversion,
506   // array-to-pointer conversion, or function-to-pointer conversion
507   // (C++ 4p1).
508
509   // Lvalue-to-rvalue conversion (C++ 4.1):
510   //   An lvalue (3.10) of a non-function, non-array type T can be
511   //   converted to an rvalue.
512   Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
513   if (argIsLvalue == Expr::LV_Valid &&
514       !FromType->isFunctionType() && !FromType->isArrayType() &&
515       Context.getCanonicalType(FromType) != Context.OverloadTy) {
516     SCS.First = ICK_Lvalue_To_Rvalue;
517
518     // If T is a non-class type, the type of the rvalue is the
519     // cv-unqualified version of T. Otherwise, the type of the rvalue
520     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
521     // just strip the qualifiers because they don't matter.
522
523     // FIXME: Doesn't see through to qualifiers behind a typedef!
524     FromType = FromType.getUnqualifiedType();
525   } else if (FromType->isArrayType()) {
526     // Array-to-pointer conversion (C++ 4.2)
527     SCS.First = ICK_Array_To_Pointer;
528
529     // An lvalue or rvalue of type "array of N T" or "array of unknown
530     // bound of T" can be converted to an rvalue of type "pointer to
531     // T" (C++ 4.2p1).
532     FromType = Context.getArrayDecayedType(FromType);
533
534     if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
535       // This conversion is deprecated. (C++ D.4).
536       SCS.Deprecated = true;
537
538       // For the purpose of ranking in overload resolution
539       // (13.3.3.1.1), this conversion is considered an
540       // array-to-pointer conversion followed by a qualification
541       // conversion (4.4). (C++ 4.2p2)
542       SCS.Second = ICK_Identity;
543       SCS.Third = ICK_Qualification;
544       SCS.ToTypePtr = ToType.getAsOpaquePtr();
545       return true;
546     }
547   } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
548     // Function-to-pointer conversion (C++ 4.3).
549     SCS.First = ICK_Function_To_Pointer;
550
551     // An lvalue of function type T can be converted to an rvalue of
552     // type "pointer to T." The result is a pointer to the
553     // function. (C++ 4.3p1).
554     FromType = Context.getPointerType(FromType);
555   } else if (FunctionDecl *Fn
556              = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
557     // Address of overloaded function (C++ [over.over]).
558     SCS.First = ICK_Function_To_Pointer;
559
560     // We were able to resolve the address of the overloaded function,
561     // so we can convert to the type of that function.
562     FromType = Fn->getType();
563     if (ToType->isLValueReferenceType())
564       FromType = Context.getLValueReferenceType(FromType);
565     else if (ToType->isRValueReferenceType())
566       FromType = Context.getRValueReferenceType(FromType);
567     else if (ToType->isMemberPointerType()) {
568       // Resolve address only succeeds if both sides are member pointers,
569       // but it doesn't have to be the same class. See DR 247.
570       // Note that this means that the type of &Derived::fn can be
571       // Ret (Base::*)(Args) if the fn overload actually found is from the
572       // base class, even if it was brought into the derived class via a
573       // using declaration. The standard isn't clear on this issue at all.
574       CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
575       FromType = Context.getMemberPointerType(FromType,
576                     Context.getTypeDeclType(M->getParent()).getTypePtr());
577     } else
578       FromType = Context.getPointerType(FromType);
579   } else {
580     // We don't require any conversions for the first step.
581     SCS.First = ICK_Identity;
582   }
583
584   // The second conversion can be an integral promotion, floating
585   // point promotion, integral conversion, floating point conversion,
586   // floating-integral conversion, pointer conversion,
587   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
588   // For overloading in C, this can also be a "compatible-type"
589   // conversion.
590   bool IncompatibleObjC = false;
591   if (Context.hasSameUnqualifiedType(FromType, ToType)) {
592     // The unqualified versions of the types are the same: there's no
593     // conversion to do.
594     SCS.Second = ICK_Identity;
595   } else if (IsIntegralPromotion(From, FromType, ToType)) {
596     // Integral promotion (C++ 4.5).
597     SCS.Second = ICK_Integral_Promotion;
598     FromType = ToType.getUnqualifiedType();
599   } else if (IsFloatingPointPromotion(FromType, ToType)) {
600     // Floating point promotion (C++ 4.6).
601     SCS.Second = ICK_Floating_Promotion;
602     FromType = ToType.getUnqualifiedType();
603   } else if (IsComplexPromotion(FromType, ToType)) {
604     // Complex promotion (Clang extension)
605     SCS.Second = ICK_Complex_Promotion;
606     FromType = ToType.getUnqualifiedType();
607   } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
608            (ToType->isIntegralType() && !ToType->isEnumeralType())) {
609     // Integral conversions (C++ 4.7).
610     // FIXME: isIntegralType shouldn't be true for enums in C++.
611     SCS.Second = ICK_Integral_Conversion;
612     FromType = ToType.getUnqualifiedType();
613   } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
614     // Floating point conversions (C++ 4.8).
615     SCS.Second = ICK_Floating_Conversion;
616     FromType = ToType.getUnqualifiedType();
617   } else if (FromType->isComplexType() && ToType->isComplexType()) {
618     // Complex conversions (C99 6.3.1.6)
619     SCS.Second = ICK_Complex_Conversion;
620     FromType = ToType.getUnqualifiedType();
621   } else if ((FromType->isFloatingType() &&
622               ToType->isIntegralType() && (!ToType->isBooleanType() &&
623                                            !ToType->isEnumeralType())) ||
624              ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
625               ToType->isFloatingType())) {
626     // Floating-integral conversions (C++ 4.9).
627     // FIXME: isIntegralType shouldn't be true for enums in C++.
628     SCS.Second = ICK_Floating_Integral;
629     FromType = ToType.getUnqualifiedType();
630   } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631              (ToType->isComplexType() && FromType->isArithmeticType())) {
632     // Complex-real conversions (C99 6.3.1.7)
633     SCS.Second = ICK_Complex_Real;
634     FromType = ToType.getUnqualifiedType();
635   } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
636                                  FromType, IncompatibleObjC)) {
637     // Pointer conversions (C++ 4.10).
638     SCS.Second = ICK_Pointer_Conversion;
639     SCS.IncompatibleObjC = IncompatibleObjC;
640   } else if (IsMemberPointerConversion(From, FromType, ToType, 
641                                        InOverloadResolution, FromType)) {
642     // Pointer to member conversions (4.11).
643     SCS.Second = ICK_Pointer_Member;
644   } else if (ToType->isBooleanType() &&
645              (FromType->isArithmeticType() ||
646               FromType->isEnumeralType() ||
647               FromType->isPointerType() ||
648               FromType->isBlockPointerType() ||
649               FromType->isMemberPointerType() ||
650               FromType->isNullPtrType())) {
651     // Boolean conversions (C++ 4.12).
652     SCS.Second = ICK_Boolean_Conversion;
653     FromType = Context.BoolTy;
654   } else if (!getLangOptions().CPlusPlus &&
655              Context.typesAreCompatible(ToType, FromType)) {
656     // Compatible conversions (Clang extension for C function overloading)
657     SCS.Second = ICK_Compatible_Conversion;
658   } else {
659     // No second conversion required.
660     SCS.Second = ICK_Identity;
661   }
662
663   QualType CanonFrom;
664   QualType CanonTo;
665   // The third conversion can be a qualification conversion (C++ 4p1).
666   if (IsQualificationConversion(FromType, ToType)) {
667     SCS.Third = ICK_Qualification;
668     FromType = ToType;
669     CanonFrom = Context.getCanonicalType(FromType);
670     CanonTo = Context.getCanonicalType(ToType);
671   } else {
672     // No conversion required
673     SCS.Third = ICK_Identity;
674
675     // C++ [over.best.ics]p6:
676     //   [...] Any difference in top-level cv-qualification is
677     //   subsumed by the initialization itself and does not constitute
678     //   a conversion. [...]
679     CanonFrom = Context.getCanonicalType(FromType);
680     CanonTo = Context.getCanonicalType(ToType);
681     if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
682         CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
683       FromType = ToType;
684       CanonFrom = CanonTo;
685     }
686   }
687
688   // If we have not converted the argument type to the parameter type,
689   // this is a bad conversion sequence.
690   if (CanonFrom != CanonTo)
691     return false;
692
693   SCS.ToTypePtr = FromType.getAsOpaquePtr();
694   return true;
695 }
696
697 /// IsIntegralPromotion - Determines whether the conversion from the
698 /// expression From (whose potentially-adjusted type is FromType) to
699 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
700 /// sets PromotedType to the promoted type.
701 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
702   const BuiltinType *To = ToType->getAs<BuiltinType>();
703   // All integers are built-in.
704   if (!To) {
705     return false;
706   }
707
708   // An rvalue of type char, signed char, unsigned char, short int, or
709   // unsigned short int can be converted to an rvalue of type int if
710   // int can represent all the values of the source type; otherwise,
711   // the source rvalue can be converted to an rvalue of type unsigned
712   // int (C++ 4.5p1).
713   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
714     if (// We can promote any signed, promotable integer type to an int
715         (FromType->isSignedIntegerType() ||
716          // We can promote any unsigned integer type whose size is
717          // less than int to an int.
718          (!FromType->isSignedIntegerType() &&
719           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
720       return To->getKind() == BuiltinType::Int;
721     }
722
723     return To->getKind() == BuiltinType::UInt;
724   }
725
726   // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
727   // can be converted to an rvalue of the first of the following types
728   // that can represent all the values of its underlying type: int,
729   // unsigned int, long, or unsigned long (C++ 4.5p2).
730   if ((FromType->isEnumeralType() || FromType->isWideCharType())
731       && ToType->isIntegerType()) {
732     // Determine whether the type we're converting from is signed or
733     // unsigned.
734     bool FromIsSigned;
735     uint64_t FromSize = Context.getTypeSize(FromType);
736     if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
737       QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
738       FromIsSigned = UnderlyingType->isSignedIntegerType();
739     } else {
740       // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
741       FromIsSigned = true;
742     }
743
744     // The types we'll try to promote to, in the appropriate
745     // order. Try each of these types.
746     QualType PromoteTypes[6] = {
747       Context.IntTy, Context.UnsignedIntTy,
748       Context.LongTy, Context.UnsignedLongTy ,
749       Context.LongLongTy, Context.UnsignedLongLongTy
750     };
751     for (int Idx = 0; Idx < 6; ++Idx) {
752       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
753       if (FromSize < ToSize ||
754           (FromSize == ToSize &&
755            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
756         // We found the type that we can promote to. If this is the
757         // type we wanted, we have a promotion. Otherwise, no
758         // promotion.
759         return Context.getCanonicalType(ToType).getUnqualifiedType()
760           == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
761       }
762     }
763   }
764
765   // An rvalue for an integral bit-field (9.6) can be converted to an
766   // rvalue of type int if int can represent all the values of the
767   // bit-field; otherwise, it can be converted to unsigned int if
768   // unsigned int can represent all the values of the bit-field. If
769   // the bit-field is larger yet, no integral promotion applies to
770   // it. If the bit-field has an enumerated type, it is treated as any
771   // other value of that type for promotion purposes (C++ 4.5p3).
772   // FIXME: We should delay checking of bit-fields until we actually perform the
773   // conversion.
774   using llvm::APSInt;
775   if (From)
776     if (FieldDecl *MemberDecl = From->getBitField()) {
777       APSInt BitWidth;
778       if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
779           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
780         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
781         ToSize = Context.getTypeSize(ToType);
782
783         // Are we promoting to an int from a bitfield that fits in an int?
784         if (BitWidth < ToSize ||
785             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
786           return To->getKind() == BuiltinType::Int;
787         }
788
789         // Are we promoting to an unsigned int from an unsigned bitfield
790         // that fits into an unsigned int?
791         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
792           return To->getKind() == BuiltinType::UInt;
793         }
794
795         return false;
796       }
797     }
798
799   // An rvalue of type bool can be converted to an rvalue of type int,
800   // with false becoming zero and true becoming one (C++ 4.5p4).
801   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
802     return true;
803   }
804
805   return false;
806 }
807
808 /// IsFloatingPointPromotion - Determines whether the conversion from
809 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
810 /// returns true and sets PromotedType to the promoted type.
811 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
812   /// An rvalue of type float can be converted to an rvalue of type
813   /// double. (C++ 4.6p1).
814   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
815     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
816       if (FromBuiltin->getKind() == BuiltinType::Float &&
817           ToBuiltin->getKind() == BuiltinType::Double)
818         return true;
819
820       // C99 6.3.1.5p1:
821       //   When a float is promoted to double or long double, or a
822       //   double is promoted to long double [...].
823       if (!getLangOptions().CPlusPlus &&
824           (FromBuiltin->getKind() == BuiltinType::Float ||
825            FromBuiltin->getKind() == BuiltinType::Double) &&
826           (ToBuiltin->getKind() == BuiltinType::LongDouble))
827         return true;
828     }
829
830   return false;
831 }
832
833 /// \brief Determine if a conversion is a complex promotion.
834 ///
835 /// A complex promotion is defined as a complex -> complex conversion
836 /// where the conversion between the underlying real types is a
837 /// floating-point or integral promotion.
838 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
839   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
840   if (!FromComplex)
841     return false;
842
843   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
844   if (!ToComplex)
845     return false;
846
847   return IsFloatingPointPromotion(FromComplex->getElementType(),
848                                   ToComplex->getElementType()) ||
849     IsIntegralPromotion(0, FromComplex->getElementType(),
850                         ToComplex->getElementType());
851 }
852
853 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
854 /// the pointer type FromPtr to a pointer to type ToPointee, with the
855 /// same type qualifiers as FromPtr has on its pointee type. ToType,
856 /// if non-empty, will be a pointer to ToType that may or may not have
857 /// the right set of qualifiers on its pointee.
858 static QualType
859 BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
860                                    QualType ToPointee, QualType ToType,
861                                    ASTContext &Context) {
862   QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
863   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
864   Qualifiers Quals = CanonFromPointee.getQualifiers();
865
866   // Exact qualifier match -> return the pointer type we're converting to.
867   if (CanonToPointee.getQualifiers() == Quals) {
868     // ToType is exactly what we need. Return it.
869     if (!ToType.isNull())
870       return ToType;
871
872     // Build a pointer to ToPointee. It has the right qualifiers
873     // already.
874     return Context.getPointerType(ToPointee);
875   }
876
877   // Just build a canonical type that has the right qualifiers.
878   return Context.getPointerType(
879          Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
880 }
881
882 static bool isNullPointerConstantForConversion(Expr *Expr,
883                                                bool InOverloadResolution,
884                                                ASTContext &Context) {
885   // Handle value-dependent integral null pointer constants correctly.
886   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
887   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
888       Expr->getType()->isIntegralType())
889     return !InOverloadResolution;
890
891   return Expr->isNullPointerConstant(Context,
892                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
893                                         : Expr::NPC_ValueDependentIsNull);
894 }
895
896 /// IsPointerConversion - Determines whether the conversion of the
897 /// expression From, which has the (possibly adjusted) type FromType,
898 /// can be converted to the type ToType via a pointer conversion (C++
899 /// 4.10). If so, returns true and places the converted type (that
900 /// might differ from ToType in its cv-qualifiers at some level) into
901 /// ConvertedType.
902 ///
903 /// This routine also supports conversions to and from block pointers
904 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
905 /// pointers to interfaces. FIXME: Once we've determined the
906 /// appropriate overloading rules for Objective-C, we may want to
907 /// split the Objective-C checks into a different routine; however,
908 /// GCC seems to consider all of these conversions to be pointer
909 /// conversions, so for now they live here. IncompatibleObjC will be
910 /// set if the conversion is an allowed Objective-C conversion that
911 /// should result in a warning.
912 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
913                                bool InOverloadResolution,
914                                QualType& ConvertedType,
915                                bool &IncompatibleObjC) {
916   IncompatibleObjC = false;
917   if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
918     return true;
919
920   // Conversion from a null pointer constant to any Objective-C pointer type.
921   if (ToType->isObjCObjectPointerType() &&
922       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
923     ConvertedType = ToType;
924     return true;
925   }
926
927   // Blocks: Block pointers can be converted to void*.
928   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
929       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
930     ConvertedType = ToType;
931     return true;
932   }
933   // Blocks: A null pointer constant can be converted to a block
934   // pointer type.
935   if (ToType->isBlockPointerType() &&
936       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
937     ConvertedType = ToType;
938     return true;
939   }
940
941   // If the left-hand-side is nullptr_t, the right side can be a null
942   // pointer constant.
943   if (ToType->isNullPtrType() &&
944       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
945     ConvertedType = ToType;
946     return true;
947   }
948
949   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
950   if (!ToTypePtr)
951     return false;
952
953   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
954   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
955     ConvertedType = ToType;
956     return true;
957   }
958
959   // Beyond this point, both types need to be pointers.
960   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
961   if (!FromTypePtr)
962     return false;
963
964   QualType FromPointeeType = FromTypePtr->getPointeeType();
965   QualType ToPointeeType = ToTypePtr->getPointeeType();
966
967   // An rvalue of type "pointer to cv T," where T is an object type,
968   // can be converted to an rvalue of type "pointer to cv void" (C++
969   // 4.10p2).
970   if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
971     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
972                                                        ToPointeeType,
973                                                        ToType, Context);
974     return true;
975   }
976
977   // When we're overloading in C, we allow a special kind of pointer
978   // conversion for compatible-but-not-identical pointee types.
979   if (!getLangOptions().CPlusPlus &&
980       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
981     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
982                                                        ToPointeeType,
983                                                        ToType, Context);
984     return true;
985   }
986
987   // C++ [conv.ptr]p3:
988   //
989   //   An rvalue of type "pointer to cv D," where D is a class type,
990   //   can be converted to an rvalue of type "pointer to cv B," where
991   //   B is a base class (clause 10) of D. If B is an inaccessible
992   //   (clause 11) or ambiguous (10.2) base class of D, a program that
993   //   necessitates this conversion is ill-formed. The result of the
994   //   conversion is a pointer to the base class sub-object of the
995   //   derived class object. The null pointer value is converted to
996   //   the null pointer value of the destination type.
997   //
998   // Note that we do not check for ambiguity or inaccessibility
999   // here. That is handled by CheckPointerConversion.
1000   if (getLangOptions().CPlusPlus &&
1001       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1002       !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1003       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1004     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1005                                                        ToPointeeType,
1006                                                        ToType, Context);
1007     return true;
1008   }
1009
1010   return false;
1011 }
1012
1013 /// isObjCPointerConversion - Determines whether this is an
1014 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1015 /// with the same arguments and return values.
1016 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1017                                    QualType& ConvertedType,
1018                                    bool &IncompatibleObjC) {
1019   if (!getLangOptions().ObjC1)
1020     return false;
1021
1022   // First, we handle all conversions on ObjC object pointer types.
1023   const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
1024   const ObjCObjectPointerType *FromObjCPtr =
1025     FromType->getAs<ObjCObjectPointerType>();
1026
1027   if (ToObjCPtr && FromObjCPtr) {
1028     // Objective C++: We're able to convert between "id" or "Class" and a
1029     // pointer to any interface (in both directions).
1030     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1031       ConvertedType = ToType;
1032       return true;
1033     }
1034     // Conversions with Objective-C's id<...>.
1035     if ((FromObjCPtr->isObjCQualifiedIdType() ||
1036          ToObjCPtr->isObjCQualifiedIdType()) &&
1037         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1038                                                   /*compare=*/false)) {
1039       ConvertedType = ToType;
1040       return true;
1041     }
1042     // Objective C++: We're able to convert from a pointer to an
1043     // interface to a pointer to a different interface.
1044     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1045       ConvertedType = ToType;
1046       return true;
1047     }
1048
1049     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1050       // Okay: this is some kind of implicit downcast of Objective-C
1051       // interfaces, which is permitted. However, we're going to
1052       // complain about it.
1053       IncompatibleObjC = true;
1054       ConvertedType = FromType;
1055       return true;
1056     }
1057   }
1058   // Beyond this point, both types need to be C pointers or block pointers.
1059   QualType ToPointeeType;
1060   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1061     ToPointeeType = ToCPtr->getPointeeType();
1062   else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
1063     ToPointeeType = ToBlockPtr->getPointeeType();
1064   else
1065     return false;
1066
1067   QualType FromPointeeType;
1068   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1069     FromPointeeType = FromCPtr->getPointeeType();
1070   else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1071     FromPointeeType = FromBlockPtr->getPointeeType();
1072   else
1073     return false;
1074
1075   // If we have pointers to pointers, recursively check whether this
1076   // is an Objective-C conversion.
1077   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1078       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1079                               IncompatibleObjC)) {
1080     // We always complain about this conversion.
1081     IncompatibleObjC = true;
1082     ConvertedType = ToType;
1083     return true;
1084   }
1085   // If we have pointers to functions or blocks, check whether the only
1086   // differences in the argument and result types are in Objective-C
1087   // pointer conversions. If so, we permit the conversion (but
1088   // complain about it).
1089   const FunctionProtoType *FromFunctionType
1090     = FromPointeeType->getAs<FunctionProtoType>();
1091   const FunctionProtoType *ToFunctionType
1092     = ToPointeeType->getAs<FunctionProtoType>();
1093   if (FromFunctionType && ToFunctionType) {
1094     // If the function types are exactly the same, this isn't an
1095     // Objective-C pointer conversion.
1096     if (Context.getCanonicalType(FromPointeeType)
1097           == Context.getCanonicalType(ToPointeeType))
1098       return false;
1099
1100     // Perform the quick checks that will tell us whether these
1101     // function types are obviously different.
1102     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1103         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1104         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1105       return false;
1106
1107     bool HasObjCConversion = false;
1108     if (Context.getCanonicalType(FromFunctionType->getResultType())
1109           == Context.getCanonicalType(ToFunctionType->getResultType())) {
1110       // Okay, the types match exactly. Nothing to do.
1111     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1112                                        ToFunctionType->getResultType(),
1113                                        ConvertedType, IncompatibleObjC)) {
1114       // Okay, we have an Objective-C pointer conversion.
1115       HasObjCConversion = true;
1116     } else {
1117       // Function types are too different. Abort.
1118       return false;
1119     }
1120
1121     // Check argument types.
1122     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1123          ArgIdx != NumArgs; ++ArgIdx) {
1124       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1125       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1126       if (Context.getCanonicalType(FromArgType)
1127             == Context.getCanonicalType(ToArgType)) {
1128         // Okay, the types match exactly. Nothing to do.
1129       } else if (isObjCPointerConversion(FromArgType, ToArgType,
1130                                          ConvertedType, IncompatibleObjC)) {
1131         // Okay, we have an Objective-C pointer conversion.
1132         HasObjCConversion = true;
1133       } else {
1134         // Argument types are too different. Abort.
1135         return false;
1136       }
1137     }
1138
1139     if (HasObjCConversion) {
1140       // We had an Objective-C conversion. Allow this pointer
1141       // conversion, but complain about it.
1142       ConvertedType = ToType;
1143       IncompatibleObjC = true;
1144       return true;
1145     }
1146   }
1147
1148   return false;
1149 }
1150
1151 /// CheckPointerConversion - Check the pointer conversion from the
1152 /// expression From to the type ToType. This routine checks for
1153 /// ambiguous or inaccessible derived-to-base pointer
1154 /// conversions for which IsPointerConversion has already returned
1155 /// true. It returns true and produces a diagnostic if there was an
1156 /// error, or returns false otherwise.
1157 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1158                                   CastExpr::CastKind &Kind) {
1159   QualType FromType = From->getType();
1160
1161   if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1162     if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1163       QualType FromPointeeType = FromPtrType->getPointeeType(),
1164                ToPointeeType   = ToPtrType->getPointeeType();
1165
1166       if (FromPointeeType->isRecordType() &&
1167           ToPointeeType->isRecordType()) {
1168         // We must have a derived-to-base conversion. Check an
1169         // ambiguous or inaccessible conversion.
1170         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1171                                          From->getExprLoc(),
1172                                          From->getSourceRange()))
1173           return true;
1174         
1175         // The conversion was successful.
1176         Kind = CastExpr::CK_DerivedToBase;
1177       }
1178     }
1179   if (const ObjCObjectPointerType *FromPtrType =
1180         FromType->getAs<ObjCObjectPointerType>())
1181     if (const ObjCObjectPointerType *ToPtrType =
1182           ToType->getAs<ObjCObjectPointerType>()) {
1183       // Objective-C++ conversions are always okay.
1184       // FIXME: We should have a different class of conversions for the
1185       // Objective-C++ implicit conversions.
1186       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1187         return false;
1188
1189   }
1190   return false;
1191 }
1192
1193 /// IsMemberPointerConversion - Determines whether the conversion of the
1194 /// expression From, which has the (possibly adjusted) type FromType, can be
1195 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
1196 /// If so, returns true and places the converted type (that might differ from
1197 /// ToType in its cv-qualifiers at some level) into ConvertedType.
1198 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1199                                      QualType ToType, 
1200                                      bool InOverloadResolution,
1201                                      QualType &ConvertedType) {
1202   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1203   if (!ToTypePtr)
1204     return false;
1205
1206   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1207   if (From->isNullPointerConstant(Context,
1208                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1209                                         : Expr::NPC_ValueDependentIsNull)) {
1210     ConvertedType = ToType;
1211     return true;
1212   }
1213
1214   // Otherwise, both types have to be member pointers.
1215   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1216   if (!FromTypePtr)
1217     return false;
1218
1219   // A pointer to member of B can be converted to a pointer to member of D,
1220   // where D is derived from B (C++ 4.11p2).
1221   QualType FromClass(FromTypePtr->getClass(), 0);
1222   QualType ToClass(ToTypePtr->getClass(), 0);
1223   // FIXME: What happens when these are dependent? Is this function even called?
1224
1225   if (IsDerivedFrom(ToClass, FromClass)) {
1226     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1227                                                  ToClass.getTypePtr());
1228     return true;
1229   }
1230
1231   return false;
1232 }
1233
1234 /// CheckMemberPointerConversion - Check the member pointer conversion from the
1235 /// expression From to the type ToType. This routine checks for ambiguous or
1236 /// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1237 /// for which IsMemberPointerConversion has already returned true. It returns
1238 /// true and produces a diagnostic if there was an error, or returns false
1239 /// otherwise.
1240 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1241                                         CastExpr::CastKind &Kind) {
1242   QualType FromType = From->getType();
1243   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1244   if (!FromPtrType) {
1245     // This must be a null pointer to member pointer conversion
1246     assert(From->isNullPointerConstant(Context, 
1247                                        Expr::NPC_ValueDependentIsNull) &&
1248            "Expr must be null pointer constant!");
1249     Kind = CastExpr::CK_NullToMemberPointer;
1250     return false;
1251   }
1252
1253   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1254   assert(ToPtrType && "No member pointer cast has a target type "
1255                       "that is not a member pointer.");
1256
1257   QualType FromClass = QualType(FromPtrType->getClass(), 0);
1258   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1259
1260   // FIXME: What about dependent types?
1261   assert(FromClass->isRecordType() && "Pointer into non-class.");
1262   assert(ToClass->isRecordType() && "Pointer into non-class.");
1263
1264   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1265                      /*DetectVirtual=*/true);
1266   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1267   assert(DerivationOkay &&
1268          "Should not have been called if derivation isn't OK.");
1269   (void)DerivationOkay;
1270
1271   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1272                                   getUnqualifiedType())) {
1273     // Derivation is ambiguous. Redo the check to find the exact paths.
1274     Paths.clear();
1275     Paths.setRecordingPaths(true);
1276     bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1277     assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1278     (void)StillOkay;
1279
1280     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1281     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1282       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1283     return true;
1284   }
1285
1286   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1287     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1288       << FromClass << ToClass << QualType(VBase, 0)
1289       << From->getSourceRange();
1290     return true;
1291   }
1292
1293   // Must be a base to derived member conversion.
1294   Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1295   return false;
1296 }
1297
1298 /// IsQualificationConversion - Determines whether the conversion from
1299 /// an rvalue of type FromType to ToType is a qualification conversion
1300 /// (C++ 4.4).
1301 bool
1302 Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
1303   FromType = Context.getCanonicalType(FromType);
1304   ToType = Context.getCanonicalType(ToType);
1305
1306   // If FromType and ToType are the same type, this is not a
1307   // qualification conversion.
1308   if (FromType == ToType)
1309     return false;
1310
1311   // (C++ 4.4p4):
1312   //   A conversion can add cv-qualifiers at levels other than the first
1313   //   in multi-level pointers, subject to the following rules: [...]
1314   bool PreviousToQualsIncludeConst = true;
1315   bool UnwrappedAnyPointer = false;
1316   while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1317     // Within each iteration of the loop, we check the qualifiers to
1318     // determine if this still looks like a qualification
1319     // conversion. Then, if all is well, we unwrap one more level of
1320     // pointers or pointers-to-members and do it all again
1321     // until there are no more pointers or pointers-to-members left to
1322     // unwrap.
1323     UnwrappedAnyPointer = true;
1324
1325     //   -- for every j > 0, if const is in cv 1,j then const is in cv
1326     //      2,j, and similarly for volatile.
1327     if (!ToType.isAtLeastAsQualifiedAs(FromType))
1328       return false;
1329
1330     //   -- if the cv 1,j and cv 2,j are different, then const is in
1331     //      every cv for 0 < k < j.
1332     if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1333         && !PreviousToQualsIncludeConst)
1334       return false;
1335
1336     // Keep track of whether all prior cv-qualifiers in the "to" type
1337     // include const.
1338     PreviousToQualsIncludeConst
1339       = PreviousToQualsIncludeConst && ToType.isConstQualified();
1340   }
1341
1342   // We are left with FromType and ToType being the pointee types
1343   // after unwrapping the original FromType and ToType the same number
1344   // of types. If we unwrapped any pointers, and if FromType and
1345   // ToType have the same unqualified type (since we checked
1346   // qualifiers above), then this is a qualification conversion.
1347   return UnwrappedAnyPointer &&
1348     FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1349 }
1350
1351 /// \brief Given a function template or function, extract the function template
1352 /// declaration (if any) and the underlying function declaration.
1353 template<typename T>
1354 static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1355                                    FunctionTemplateDecl *&FunctionTemplate) {
1356   FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1357   if (FunctionTemplate)
1358     Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1359   else
1360     Function = cast<T>(Orig);
1361 }
1362
1363 /// Determines whether there is a user-defined conversion sequence
1364 /// (C++ [over.ics.user]) that converts expression From to the type
1365 /// ToType. If such a conversion exists, User will contain the
1366 /// user-defined conversion sequence that performs such a conversion
1367 /// and this routine will return true. Otherwise, this routine returns
1368 /// false and User is unspecified.
1369 ///
1370 /// \param AllowConversionFunctions true if the conversion should
1371 /// consider conversion functions at all. If false, only constructors
1372 /// will be considered.
1373 ///
1374 /// \param AllowExplicit  true if the conversion should consider C++0x
1375 /// "explicit" conversion functions as well as non-explicit conversion
1376 /// functions (C++0x [class.conv.fct]p2).
1377 ///
1378 /// \param ForceRValue  true if the expression should be treated as an rvalue
1379 /// for overload resolution.
1380 /// \param UserCast true if looking for user defined conversion for a static
1381 /// cast.
1382 Sema::OverloadingResult Sema::IsUserDefinedConversion(
1383                                    Expr *From, QualType ToType,
1384                                    UserDefinedConversionSequence& User,
1385                                    OverloadCandidateSet& CandidateSet,
1386                                    bool AllowConversionFunctions,
1387                                    bool AllowExplicit, bool ForceRValue,
1388                                    bool UserCast) {
1389   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1390     if (CXXRecordDecl *ToRecordDecl
1391           = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1392       // C++ [over.match.ctor]p1:
1393       //   When objects of class type are direct-initialized (8.5), or
1394       //   copy-initialized from an expression of the same or a
1395       //   derived class type (8.5), overload resolution selects the
1396       //   constructor. [...] For copy-initialization, the candidate
1397       //   functions are all the converting constructors (12.3.1) of
1398       //   that class. The argument list is the expression-list within
1399       //   the parentheses of the initializer.
1400       DeclarationName ConstructorName
1401         = Context.DeclarationNames.getCXXConstructorName(
1402                           Context.getCanonicalType(ToType).getUnqualifiedType());
1403       DeclContext::lookup_iterator Con, ConEnd;
1404       for (llvm::tie(Con, ConEnd)
1405              = ToRecordDecl->lookup(ConstructorName);
1406            Con != ConEnd; ++Con) {
1407         // Find the constructor (which may be a template).
1408         CXXConstructorDecl *Constructor = 0;
1409         FunctionTemplateDecl *ConstructorTmpl
1410           = dyn_cast<FunctionTemplateDecl>(*Con);
1411         if (ConstructorTmpl)
1412           Constructor
1413             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1414         else
1415           Constructor = cast<CXXConstructorDecl>(*Con);
1416
1417         if (!Constructor->isInvalidDecl() &&
1418             Constructor->isConvertingConstructor(AllowExplicit)) {
1419           if (ConstructorTmpl)
1420             AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1421                                          1, CandidateSet,
1422                                          /*SuppressUserConversions=*/!UserCast,
1423                                          ForceRValue);
1424           else
1425             // Allow one user-defined conversion when user specifies a
1426             // From->ToType conversion via an static cast (c-style, etc).
1427             AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1428                                  /*SuppressUserConversions=*/!UserCast, 
1429                                  ForceRValue);
1430         }
1431       }
1432     }
1433   }
1434
1435   if (!AllowConversionFunctions) {
1436     // Don't allow any conversion functions to enter the overload set.
1437   } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1438                                  PDiag(0)
1439                                    << From->getSourceRange())) {
1440     // No conversion functions from incomplete types.
1441   } else if (const RecordType *FromRecordType
1442                = From->getType()->getAs<RecordType>()) {
1443     if (CXXRecordDecl *FromRecordDecl
1444          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1445       // Add all of the conversion functions as candidates.
1446       OverloadedFunctionDecl *Conversions
1447         = FromRecordDecl->getVisibleConversionFunctions();
1448       for (OverloadedFunctionDecl::function_iterator Func
1449              = Conversions->function_begin();
1450            Func != Conversions->function_end(); ++Func) {
1451         CXXConversionDecl *Conv;
1452         FunctionTemplateDecl *ConvTemplate;
1453         GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1454         if (ConvTemplate)
1455           Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1456         else
1457           Conv = dyn_cast<CXXConversionDecl>(*Func);
1458
1459         if (AllowExplicit || !Conv->isExplicit()) {
1460           if (ConvTemplate)
1461             AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1462                                            CandidateSet);
1463           else
1464             AddConversionCandidate(Conv, From, ToType, CandidateSet);
1465         }
1466       }
1467     }
1468   }
1469
1470   OverloadCandidateSet::iterator Best;
1471   switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1472     case OR_Success:
1473       // Record the standard conversion we used and the conversion function.
1474       if (CXXConstructorDecl *Constructor
1475             = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1476         // C++ [over.ics.user]p1:
1477         //   If the user-defined conversion is specified by a
1478         //   constructor (12.3.1), the initial standard conversion
1479         //   sequence converts the source type to the type required by
1480         //   the argument of the constructor.
1481         //
1482         // FIXME: What about ellipsis conversions?
1483         QualType ThisType = Constructor->getThisType(Context);
1484         User.Before = Best->Conversions[0].Standard;
1485         User.ConversionFunction = Constructor;
1486         User.After.setAsIdentityConversion();
1487         User.After.FromTypePtr
1488           = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
1489         User.After.ToTypePtr = ToType.getAsOpaquePtr();
1490         return OR_Success;
1491       } else if (CXXConversionDecl *Conversion
1492                    = dyn_cast<CXXConversionDecl>(Best->Function)) {
1493         // C++ [over.ics.user]p1:
1494         //
1495         //   [...] If the user-defined conversion is specified by a
1496         //   conversion function (12.3.2), the initial standard
1497         //   conversion sequence converts the source type to the
1498         //   implicit object parameter of the conversion function.
1499         User.Before = Best->Conversions[0].Standard;
1500         User.ConversionFunction = Conversion;
1501
1502         // C++ [over.ics.user]p2:
1503         //   The second standard conversion sequence converts the
1504         //   result of the user-defined conversion to the target type
1505         //   for the sequence. Since an implicit conversion sequence
1506         //   is an initialization, the special rules for
1507         //   initialization by user-defined conversion apply when
1508         //   selecting the best user-defined conversion for a
1509         //   user-defined conversion sequence (see 13.3.3 and
1510         //   13.3.3.1).
1511         User.After = Best->FinalConversion;
1512         return OR_Success;
1513       } else {
1514         assert(false && "Not a constructor or conversion function?");
1515         return OR_No_Viable_Function;
1516       }
1517
1518     case OR_No_Viable_Function:
1519       return OR_No_Viable_Function;
1520     case OR_Deleted:
1521       // No conversion here! We're done.
1522       return OR_Deleted;
1523
1524     case OR_Ambiguous:
1525       return OR_Ambiguous;
1526     }
1527
1528   return OR_No_Viable_Function;
1529 }
1530   
1531 bool
1532 Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1533   ImplicitConversionSequence ICS;
1534   OverloadCandidateSet CandidateSet;
1535   OverloadingResult OvResult = 
1536     IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1537                             CandidateSet, true, false, false);
1538   if (OvResult != OR_Ambiguous)
1539     return false;
1540   Diag(From->getSourceRange().getBegin(),
1541        diag::err_typecheck_ambiguous_condition)
1542   << From->getType() << ToType << From->getSourceRange();
1543     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1544   return true;  
1545 }
1546
1547 /// CompareImplicitConversionSequences - Compare two implicit
1548 /// conversion sequences to determine whether one is better than the
1549 /// other or if they are indistinguishable (C++ 13.3.3.2).
1550 ImplicitConversionSequence::CompareKind
1551 Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1552                                          const ImplicitConversionSequence& ICS2)
1553 {
1554   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1555   // conversion sequences (as defined in 13.3.3.1)
1556   //   -- a standard conversion sequence (13.3.3.1.1) is a better
1557   //      conversion sequence than a user-defined conversion sequence or
1558   //      an ellipsis conversion sequence, and
1559   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1560   //      conversion sequence than an ellipsis conversion sequence
1561   //      (13.3.3.1.3).
1562   //
1563   if (ICS1.ConversionKind < ICS2.ConversionKind)
1564     return ImplicitConversionSequence::Better;
1565   else if (ICS2.ConversionKind < ICS1.ConversionKind)
1566     return ImplicitConversionSequence::Worse;
1567
1568   // Two implicit conversion sequences of the same form are
1569   // indistinguishable conversion sequences unless one of the
1570   // following rules apply: (C++ 13.3.3.2p3):
1571   if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1572     return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1573   else if (ICS1.ConversionKind ==
1574              ImplicitConversionSequence::UserDefinedConversion) {
1575     // User-defined conversion sequence U1 is a better conversion
1576     // sequence than another user-defined conversion sequence U2 if
1577     // they contain the same user-defined conversion function or
1578     // constructor and if the second standard conversion sequence of
1579     // U1 is better than the second standard conversion sequence of
1580     // U2 (C++ 13.3.3.2p3).
1581     if (ICS1.UserDefined.ConversionFunction ==
1582           ICS2.UserDefined.ConversionFunction)
1583       return CompareStandardConversionSequences(ICS1.UserDefined.After,
1584                                                 ICS2.UserDefined.After);
1585   }
1586
1587   return ImplicitConversionSequence::Indistinguishable;
1588 }
1589
1590 /// CompareStandardConversionSequences - Compare two standard
1591 /// conversion sequences to determine whether one is better than the
1592 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
1593 ImplicitConversionSequence::CompareKind
1594 Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1595                                          const StandardConversionSequence& SCS2)
1596 {
1597   // Standard conversion sequence S1 is a better conversion sequence
1598   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1599
1600   //  -- S1 is a proper subsequence of S2 (comparing the conversion
1601   //     sequences in the canonical form defined by 13.3.3.1.1,
1602   //     excluding any Lvalue Transformation; the identity conversion
1603   //     sequence is considered to be a subsequence of any
1604   //     non-identity conversion sequence) or, if not that,
1605   if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1606     // Neither is a proper subsequence of the other. Do nothing.
1607     ;
1608   else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1609            (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1610            (SCS1.Second == ICK_Identity &&
1611             SCS1.Third == ICK_Identity))
1612     // SCS1 is a proper subsequence of SCS2.
1613     return ImplicitConversionSequence::Better;
1614   else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1615            (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1616            (SCS2.Second == ICK_Identity &&
1617             SCS2.Third == ICK_Identity))
1618     // SCS2 is a proper subsequence of SCS1.
1619     return ImplicitConversionSequence::Worse;
1620
1621   //  -- the rank of S1 is better than the rank of S2 (by the rules
1622   //     defined below), or, if not that,
1623   ImplicitConversionRank Rank1 = SCS1.getRank();
1624   ImplicitConversionRank Rank2 = SCS2.getRank();
1625   if (Rank1 < Rank2)
1626     return ImplicitConversionSequence::Better;
1627   else if (Rank2 < Rank1)
1628     return ImplicitConversionSequence::Worse;
1629
1630   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1631   // are indistinguishable unless one of the following rules
1632   // applies:
1633
1634   //   A conversion that is not a conversion of a pointer, or
1635   //   pointer to member, to bool is better than another conversion
1636   //   that is such a conversion.
1637   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1638     return SCS2.isPointerConversionToBool()
1639              ? ImplicitConversionSequence::Better
1640              : ImplicitConversionSequence::Worse;
1641
1642   // C++ [over.ics.rank]p4b2:
1643   //
1644   //   If class B is derived directly or indirectly from class A,
1645   //   conversion of B* to A* is better than conversion of B* to
1646   //   void*, and conversion of A* to void* is better than conversion
1647   //   of B* to void*.
1648   bool SCS1ConvertsToVoid
1649     = SCS1.isPointerConversionToVoidPointer(Context);
1650   bool SCS2ConvertsToVoid
1651     = SCS2.isPointerConversionToVoidPointer(Context);
1652   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1653     // Exactly one of the conversion sequences is a conversion to
1654     // a void pointer; it's the worse conversion.
1655     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1656                               : ImplicitConversionSequence::Worse;
1657   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1658     // Neither conversion sequence converts to a void pointer; compare
1659     // their derived-to-base conversions.
1660     if (ImplicitConversionSequence::CompareKind DerivedCK
1661           = CompareDerivedToBaseConversions(SCS1, SCS2))
1662       return DerivedCK;
1663   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1664     // Both conversion sequences are conversions to void
1665     // pointers. Compare the source types to determine if there's an
1666     // inheritance relationship in their sources.
1667     QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1668     QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1669
1670     // Adjust the types we're converting from via the array-to-pointer
1671     // conversion, if we need to.
1672     if (SCS1.First == ICK_Array_To_Pointer)
1673       FromType1 = Context.getArrayDecayedType(FromType1);
1674     if (SCS2.First == ICK_Array_To_Pointer)
1675       FromType2 = Context.getArrayDecayedType(FromType2);
1676
1677     QualType FromPointee1
1678       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1679     QualType FromPointee2
1680       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1681
1682     if (IsDerivedFrom(FromPointee2, FromPointee1))
1683       return ImplicitConversionSequence::Better;
1684     else if (IsDerivedFrom(FromPointee1, FromPointee2))
1685       return ImplicitConversionSequence::Worse;
1686
1687     // Objective-C++: If one interface is more specific than the
1688     // other, it is the better one.
1689     const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1690     const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1691     if (FromIface1 && FromIface1) {
1692       if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1693         return ImplicitConversionSequence::Better;
1694       else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1695         return ImplicitConversionSequence::Worse;
1696     }
1697   }
1698
1699   // Compare based on qualification conversions (C++ 13.3.3.2p3,
1700   // bullet 3).
1701   if (ImplicitConversionSequence::CompareKind QualCK
1702         = CompareQualificationConversions(SCS1, SCS2))
1703     return QualCK;
1704
1705   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1706     // C++0x [over.ics.rank]p3b4:
1707     //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1708     //      implicit object parameter of a non-static member function declared
1709     //      without a ref-qualifier, and S1 binds an rvalue reference to an
1710     //      rvalue and S2 binds an lvalue reference.
1711     // FIXME: We don't know if we're dealing with the implicit object parameter,
1712     // or if the member function in this case has a ref qualifier.
1713     // (Of course, we don't have ref qualifiers yet.)
1714     if (SCS1.RRefBinding != SCS2.RRefBinding)
1715       return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1716                               : ImplicitConversionSequence::Worse;
1717
1718     // C++ [over.ics.rank]p3b4:
1719     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1720     //      which the references refer are the same type except for
1721     //      top-level cv-qualifiers, and the type to which the reference
1722     //      initialized by S2 refers is more cv-qualified than the type
1723     //      to which the reference initialized by S1 refers.
1724     QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1725     QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1726     T1 = Context.getCanonicalType(T1);
1727     T2 = Context.getCanonicalType(T2);
1728     if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1729       if (T2.isMoreQualifiedThan(T1))
1730         return ImplicitConversionSequence::Better;
1731       else if (T1.isMoreQualifiedThan(T2))
1732         return ImplicitConversionSequence::Worse;
1733     }
1734   }
1735
1736   return ImplicitConversionSequence::Indistinguishable;
1737 }
1738
1739 /// CompareQualificationConversions - Compares two standard conversion
1740 /// sequences to determine whether they can be ranked based on their
1741 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1742 ImplicitConversionSequence::CompareKind
1743 Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1744                                       const StandardConversionSequence& SCS2) {
1745   // C++ 13.3.3.2p3:
1746   //  -- S1 and S2 differ only in their qualification conversion and
1747   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1748   //     cv-qualification signature of type T1 is a proper subset of
1749   //     the cv-qualification signature of type T2, and S1 is not the
1750   //     deprecated string literal array-to-pointer conversion (4.2).
1751   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1752       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1753     return ImplicitConversionSequence::Indistinguishable;
1754
1755   // FIXME: the example in the standard doesn't use a qualification
1756   // conversion (!)
1757   QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1758   QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1759   T1 = Context.getCanonicalType(T1);
1760   T2 = Context.getCanonicalType(T2);
1761
1762   // If the types are the same, we won't learn anything by unwrapped
1763   // them.
1764   if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1765     return ImplicitConversionSequence::Indistinguishable;
1766
1767   ImplicitConversionSequence::CompareKind Result
1768     = ImplicitConversionSequence::Indistinguishable;
1769   while (UnwrapSimilarPointerTypes(T1, T2)) {
1770     // Within each iteration of the loop, we check the qualifiers to
1771     // determine if this still looks like a qualification
1772     // conversion. Then, if all is well, we unwrap one more level of
1773     // pointers or pointers-to-members and do it all again
1774     // until there are no more pointers or pointers-to-members left
1775     // to unwrap. This essentially mimics what
1776     // IsQualificationConversion does, but here we're checking for a
1777     // strict subset of qualifiers.
1778     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1779       // The qualifiers are the same, so this doesn't tell us anything
1780       // about how the sequences rank.
1781       ;
1782     else if (T2.isMoreQualifiedThan(T1)) {
1783       // T1 has fewer qualifiers, so it could be the better sequence.
1784       if (Result == ImplicitConversionSequence::Worse)
1785         // Neither has qualifiers that are a subset of the other's
1786         // qualifiers.
1787         return ImplicitConversionSequence::Indistinguishable;
1788
1789       Result = ImplicitConversionSequence::Better;
1790     } else if (T1.isMoreQualifiedThan(T2)) {
1791       // T2 has fewer qualifiers, so it could be the better sequence.
1792       if (Result == ImplicitConversionSequence::Better)
1793         // Neither has qualifiers that are a subset of the other's
1794         // qualifiers.
1795         return ImplicitConversionSequence::Indistinguishable;
1796
1797       Result = ImplicitConversionSequence::Worse;
1798     } else {
1799       // Qualifiers are disjoint.
1800       return ImplicitConversionSequence::Indistinguishable;
1801     }
1802
1803     // If the types after this point are equivalent, we're done.
1804     if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1805       break;
1806   }
1807
1808   // Check that the winning standard conversion sequence isn't using
1809   // the deprecated string literal array to pointer conversion.
1810   switch (Result) {
1811   case ImplicitConversionSequence::Better:
1812     if (SCS1.Deprecated)
1813       Result = ImplicitConversionSequence::Indistinguishable;
1814     break;
1815
1816   case ImplicitConversionSequence::Indistinguishable:
1817     break;
1818
1819   case ImplicitConversionSequence::Worse:
1820     if (SCS2.Deprecated)
1821       Result = ImplicitConversionSequence::Indistinguishable;
1822     break;
1823   }
1824
1825   return Result;
1826 }
1827
1828 /// CompareDerivedToBaseConversions - Compares two standard conversion
1829 /// sequences to determine whether they can be ranked based on their
1830 /// various kinds of derived-to-base conversions (C++
1831 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
1832 /// conversions between Objective-C interface types.
1833 ImplicitConversionSequence::CompareKind
1834 Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1835                                       const StandardConversionSequence& SCS2) {
1836   QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1837   QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1838   QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1839   QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1840
1841   // Adjust the types we're converting from via the array-to-pointer
1842   // conversion, if we need to.
1843   if (SCS1.First == ICK_Array_To_Pointer)
1844     FromType1 = Context.getArrayDecayedType(FromType1);
1845   if (SCS2.First == ICK_Array_To_Pointer)
1846     FromType2 = Context.getArrayDecayedType(FromType2);
1847
1848   // Canonicalize all of the types.
1849   FromType1 = Context.getCanonicalType(FromType1);
1850   ToType1 = Context.getCanonicalType(ToType1);
1851   FromType2 = Context.getCanonicalType(FromType2);
1852   ToType2 = Context.getCanonicalType(ToType2);
1853
1854   // C++ [over.ics.rank]p4b3:
1855   //
1856   //   If class B is derived directly or indirectly from class A and
1857   //   class C is derived directly or indirectly from B,
1858   //
1859   // For Objective-C, we let A, B, and C also be Objective-C
1860   // interfaces.
1861
1862   // Compare based on pointer conversions.
1863   if (SCS1.Second == ICK_Pointer_Conversion &&
1864       SCS2.Second == ICK_Pointer_Conversion &&
1865       /*FIXME: Remove if Objective-C id conversions get their own rank*/
1866       FromType1->isPointerType() && FromType2->isPointerType() &&
1867       ToType1->isPointerType() && ToType2->isPointerType()) {
1868     QualType FromPointee1
1869       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1870     QualType ToPointee1
1871       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1872     QualType FromPointee2
1873       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1874     QualType ToPointee2
1875       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1876
1877     const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1878     const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1879     const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1880     const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
1881
1882     //   -- conversion of C* to B* is better than conversion of C* to A*,
1883     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1884       if (IsDerivedFrom(ToPointee1, ToPointee2))
1885         return ImplicitConversionSequence::Better;
1886       else if (IsDerivedFrom(ToPointee2, ToPointee1))
1887         return ImplicitConversionSequence::Worse;
1888
1889       if (ToIface1 && ToIface2) {
1890         if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1891           return ImplicitConversionSequence::Better;
1892         else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1893           return ImplicitConversionSequence::Worse;
1894       }
1895     }
1896
1897     //   -- conversion of B* to A* is better than conversion of C* to A*,
1898     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1899       if (IsDerivedFrom(FromPointee2, FromPointee1))
1900         return ImplicitConversionSequence::Better;
1901       else if (IsDerivedFrom(FromPointee1, FromPointee2))
1902         return ImplicitConversionSequence::Worse;
1903
1904       if (FromIface1 && FromIface2) {
1905         if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1906           return ImplicitConversionSequence::Better;
1907         else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1908           return ImplicitConversionSequence::Worse;
1909       }
1910     }
1911   }
1912
1913   // Compare based on reference bindings.
1914   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1915       SCS1.Second == ICK_Derived_To_Base) {
1916     //   -- binding of an expression of type C to a reference of type
1917     //      B& is better than binding an expression of type C to a
1918     //      reference of type A&,
1919     if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1920         ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1921       if (IsDerivedFrom(ToType1, ToType2))
1922         return ImplicitConversionSequence::Better;
1923       else if (IsDerivedFrom(ToType2, ToType1))
1924         return ImplicitConversionSequence::Worse;
1925     }
1926
1927     //   -- binding of an expression of type B to a reference of type
1928     //      A& is better than binding an expression of type C to a
1929     //      reference of type A&,
1930     if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1931         ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1932       if (IsDerivedFrom(FromType2, FromType1))
1933         return ImplicitConversionSequence::Better;
1934       else if (IsDerivedFrom(FromType1, FromType2))
1935         return ImplicitConversionSequence::Worse;
1936     }
1937   }
1938   
1939   // Ranking of member-pointer types.
1940   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1941       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1942       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1943     const MemberPointerType * FromMemPointer1 = 
1944                                         FromType1->getAs<MemberPointerType>();
1945     const MemberPointerType * ToMemPointer1 = 
1946                                           ToType1->getAs<MemberPointerType>();
1947     const MemberPointerType * FromMemPointer2 = 
1948                                           FromType2->getAs<MemberPointerType>();
1949     const MemberPointerType * ToMemPointer2 = 
1950                                           ToType2->getAs<MemberPointerType>();
1951     const Type *FromPointeeType1 = FromMemPointer1->getClass();
1952     const Type *ToPointeeType1 = ToMemPointer1->getClass();
1953     const Type *FromPointeeType2 = FromMemPointer2->getClass();
1954     const Type *ToPointeeType2 = ToMemPointer2->getClass();
1955     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1956     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1957     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1958     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
1959     // conversion of A::* to B::* is better than conversion of A::* to C::*,
1960     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1961       if (IsDerivedFrom(ToPointee1, ToPointee2))
1962         return ImplicitConversionSequence::Worse;
1963       else if (IsDerivedFrom(ToPointee2, ToPointee1))
1964         return ImplicitConversionSequence::Better;
1965     }
1966     // conversion of B::* to C::* is better than conversion of A::* to C::*
1967     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1968       if (IsDerivedFrom(FromPointee1, FromPointee2))
1969         return ImplicitConversionSequence::Better;
1970       else if (IsDerivedFrom(FromPointee2, FromPointee1))
1971         return ImplicitConversionSequence::Worse;
1972     }
1973   }
1974   
1975   if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1976       SCS1.Second == ICK_Derived_To_Base) {
1977     //   -- conversion of C to B is better than conversion of C to A,
1978     if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1979         ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1980       if (IsDerivedFrom(ToType1, ToType2))
1981         return ImplicitConversionSequence::Better;
1982       else if (IsDerivedFrom(ToType2, ToType1))
1983         return ImplicitConversionSequence::Worse;
1984     }
1985
1986     //   -- conversion of B to A is better than conversion of C to A.
1987     if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1988         ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1989       if (IsDerivedFrom(FromType2, FromType1))
1990         return ImplicitConversionSequence::Better;
1991       else if (IsDerivedFrom(FromType1, FromType2))
1992         return ImplicitConversionSequence::Worse;
1993     }
1994   }
1995
1996   return ImplicitConversionSequence::Indistinguishable;
1997 }
1998
1999 /// TryCopyInitialization - Try to copy-initialize a value of type
2000 /// ToType from the expression From. Return the implicit conversion
2001 /// sequence required to pass this argument, which may be a bad
2002 /// conversion sequence (meaning that the argument cannot be passed to
2003 /// a parameter of this type). If @p SuppressUserConversions, then we
2004 /// do not permit any user-defined conversion sequences. If @p ForceRValue,
2005 /// then we treat @p From as an rvalue, even if it is an lvalue.
2006 ImplicitConversionSequence
2007 Sema::TryCopyInitialization(Expr *From, QualType ToType,
2008                             bool SuppressUserConversions, bool ForceRValue,
2009                             bool InOverloadResolution) {
2010   if (ToType->isReferenceType()) {
2011     ImplicitConversionSequence ICS;
2012     CheckReferenceInit(From, ToType,
2013                        /*FIXME:*/From->getLocStart(),
2014                        SuppressUserConversions,
2015                        /*AllowExplicit=*/false,
2016                        ForceRValue,
2017                        &ICS);
2018     return ICS;
2019   } else {
2020     return TryImplicitConversion(From, ToType,
2021                                  SuppressUserConversions,
2022                                  /*AllowExplicit=*/false,
2023                                  ForceRValue,
2024                                  InOverloadResolution);
2025   }
2026 }
2027
2028 /// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2029 /// the expression @p From. Returns true (and emits a diagnostic) if there was
2030 /// an error, returns false if the initialization succeeded. Elidable should
2031 /// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2032 /// differently in C++0x for this case.
2033 bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
2034                                      const char* Flavor, bool Elidable) {
2035   if (!getLangOptions().CPlusPlus) {
2036     // In C, argument passing is the same as performing an assignment.
2037     QualType FromType = From->getType();
2038
2039     AssignConvertType ConvTy =
2040       CheckSingleAssignmentConstraints(ToType, From);
2041     if (ConvTy != Compatible &&
2042         CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2043       ConvTy = Compatible;
2044
2045     return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2046                                     FromType, From, Flavor);
2047   }
2048
2049   if (ToType->isReferenceType())
2050     return CheckReferenceInit(From, ToType,
2051                               /*FIXME:*/From->getLocStart(),
2052                               /*SuppressUserConversions=*/false,
2053                               /*AllowExplicit=*/false,
2054                               /*ForceRValue=*/false);
2055
2056   if (!PerformImplicitConversion(From, ToType, Flavor,
2057                                  /*AllowExplicit=*/false, Elidable))
2058     return false;
2059   if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
2060     return Diag(From->getSourceRange().getBegin(),
2061                 diag::err_typecheck_convert_incompatible)
2062       << ToType << From->getType() << Flavor << From->getSourceRange();
2063   return true;
2064 }
2065
2066 /// TryObjectArgumentInitialization - Try to initialize the object
2067 /// parameter of the given member function (@c Method) from the
2068 /// expression @p From.
2069 ImplicitConversionSequence
2070 Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2071   QualType ClassType = Context.getTypeDeclType(Method->getParent());
2072   QualType ImplicitParamType
2073     = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
2074
2075   // Set up the conversion sequence as a "bad" conversion, to allow us
2076   // to exit early.
2077   ImplicitConversionSequence ICS;
2078   ICS.Standard.setAsIdentityConversion();
2079   ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2080
2081   // We need to have an object of class type.
2082   QualType FromType = From->getType();
2083   if (const PointerType *PT = FromType->getAs<PointerType>())
2084     FromType = PT->getPointeeType();
2085
2086   assert(FromType->isRecordType());
2087
2088   // The implicit object parmeter is has the type "reference to cv X",
2089   // where X is the class of which the function is a member
2090   // (C++ [over.match.funcs]p4). However, when finding an implicit
2091   // conversion sequence for the argument, we are not allowed to
2092   // create temporaries or perform user-defined conversions
2093   // (C++ [over.match.funcs]p5). We perform a simplified version of
2094   // reference binding here, that allows class rvalues to bind to
2095   // non-constant references.
2096
2097   // First check the qualifiers. We don't care about lvalue-vs-rvalue
2098   // with the implicit object parameter (C++ [over.match.funcs]p5).
2099   QualType FromTypeCanon = Context.getCanonicalType(FromType);
2100   if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2101       !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2102     return ICS;
2103
2104   // Check that we have either the same type or a derived type. It
2105   // affects the conversion rank.
2106   QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2107   if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2108     ICS.Standard.Second = ICK_Identity;
2109   else if (IsDerivedFrom(FromType, ClassType))
2110     ICS.Standard.Second = ICK_Derived_To_Base;
2111   else
2112     return ICS;
2113
2114   // Success. Mark this as a reference binding.
2115   ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2116   ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2117   ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2118   ICS.Standard.ReferenceBinding = true;
2119   ICS.Standard.DirectBinding = true;
2120   ICS.Standard.RRefBinding = false;
2121   return ICS;
2122 }
2123
2124 /// PerformObjectArgumentInitialization - Perform initialization of
2125 /// the implicit object parameter for the given Method with the given
2126 /// expression.
2127 bool
2128 Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2129   QualType FromRecordType, DestType;
2130   QualType ImplicitParamRecordType  =
2131     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2132
2133   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2134     FromRecordType = PT->getPointeeType();
2135     DestType = Method->getThisType(Context);
2136   } else {
2137     FromRecordType = From->getType();
2138     DestType = ImplicitParamRecordType;
2139   }
2140
2141   ImplicitConversionSequence ICS
2142     = TryObjectArgumentInitialization(From, Method);
2143   if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2144     return Diag(From->getSourceRange().getBegin(),
2145                 diag::err_implicit_object_parameter_init)
2146        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2147
2148   if (ICS.Standard.Second == ICK_Derived_To_Base &&
2149       CheckDerivedToBaseConversion(FromRecordType,
2150                                    ImplicitParamRecordType,
2151                                    From->getSourceRange().getBegin(),
2152                                    From->getSourceRange()))
2153     return true;
2154
2155   ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2156                     /*isLvalue=*/true);
2157   return false;
2158 }
2159
2160 /// TryContextuallyConvertToBool - Attempt to contextually convert the
2161 /// expression From to bool (C++0x [conv]p3).
2162 ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2163   return TryImplicitConversion(From, Context.BoolTy,
2164                                // FIXME: Are these flags correct?
2165                                /*SuppressUserConversions=*/false,
2166                                /*AllowExplicit=*/true,
2167                                /*ForceRValue=*/false,
2168                                /*InOverloadResolution=*/false);
2169 }
2170
2171 /// PerformContextuallyConvertToBool - Perform a contextual conversion
2172 /// of the expression From to bool (C++0x [conv]p3).
2173 bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2174   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2175   if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2176     return false;
2177   
2178   if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2179     return  Diag(From->getSourceRange().getBegin(),
2180                  diag::err_typecheck_bool_condition)
2181                   << From->getType() << From->getSourceRange();
2182   return true;
2183 }
2184
2185 /// AddOverloadCandidate - Adds the given function to the set of
2186 /// candidate functions, using the given function call arguments.  If
2187 /// @p SuppressUserConversions, then don't allow user-defined
2188 /// conversions via constructors or conversion operators.
2189 /// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2190 /// hacky way to implement the overloading rules for elidable copy
2191 /// initialization in C++0x (C++0x 12.8p15).
2192 ///
2193 /// \para PartialOverloading true if we are performing "partial" overloading
2194 /// based on an incomplete set of function arguments. This feature is used by
2195 /// code completion.
2196 void
2197 Sema::AddOverloadCandidate(FunctionDecl *Function,
2198                            Expr **Args, unsigned NumArgs,
2199                            OverloadCandidateSet& CandidateSet,
2200                            bool SuppressUserConversions,
2201                            bool ForceRValue,
2202                            bool PartialOverloading) {
2203   const FunctionProtoType* Proto
2204     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
2205   assert(Proto && "Functions without a prototype cannot be overloaded");
2206   assert(!isa<CXXConversionDecl>(Function) &&
2207          "Use AddConversionCandidate for conversion functions");
2208   assert(!Function->getDescribedFunctionTemplate() &&
2209          "Use AddTemplateOverloadCandidate for function templates");
2210
2211   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2212     if (!isa<CXXConstructorDecl>(Method)) {
2213       // If we get here, it's because we're calling a member function
2214       // that is named without a member access expression (e.g.,
2215       // "this->f") that was either written explicitly or created
2216       // implicitly. This can happen with a qualified call to a member
2217       // function, e.g., X::f(). We use a NULL object as the implied
2218       // object argument (C++ [over.call.func]p3).
2219       AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2220                          SuppressUserConversions, ForceRValue);
2221       return;
2222     }
2223     // We treat a constructor like a non-member function, since its object
2224     // argument doesn't participate in overload resolution.
2225   }
2226
2227   if (!CandidateSet.isNewCandidate(Function))
2228     return;
2229     
2230   // Add this candidate
2231   CandidateSet.push_back(OverloadCandidate());
2232   OverloadCandidate& Candidate = CandidateSet.back();
2233   Candidate.Function = Function;
2234   Candidate.Viable = true;
2235   Candidate.IsSurrogate = false;
2236   Candidate.IgnoreObjectArgument = false;
2237
2238   unsigned NumArgsInProto = Proto->getNumArgs();
2239
2240   // (C++ 13.3.2p2): A candidate function having fewer than m
2241   // parameters is viable only if it has an ellipsis in its parameter
2242   // list (8.3.5).
2243   if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 
2244       !Proto->isVariadic()) {
2245     Candidate.Viable = false;
2246     return;
2247   }
2248
2249   // (C++ 13.3.2p2): A candidate function having more than m parameters
2250   // is viable only if the (m+1)st parameter has a default argument
2251   // (8.3.6). For the purposes of overload resolution, the
2252   // parameter list is truncated on the right, so that there are
2253   // exactly m parameters.
2254   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2255   if (NumArgs < MinRequiredArgs && !PartialOverloading) {
2256     // Not enough arguments.
2257     Candidate.Viable = false;
2258     return;
2259   }
2260
2261   // Determine the implicit conversion sequences for each of the
2262   // arguments.
2263   Candidate.Conversions.resize(NumArgs);
2264   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2265     if (ArgIdx < NumArgsInProto) {
2266       // (C++ 13.3.2p3): for F to be a viable function, there shall
2267       // exist for each argument an implicit conversion sequence
2268       // (13.3.3.1) that converts that argument to the corresponding
2269       // parameter of F.
2270       QualType ParamType = Proto->getArgType(ArgIdx);
2271       Candidate.Conversions[ArgIdx]
2272         = TryCopyInitialization(Args[ArgIdx], ParamType,
2273                                 SuppressUserConversions, ForceRValue,
2274                                 /*InOverloadResolution=*/true);
2275       if (Candidate.Conversions[ArgIdx].ConversionKind
2276             == ImplicitConversionSequence::BadConversion) {
2277       // 13.3.3.1-p10 If several different sequences of conversions exist that 
2278       // each convert the argument to the parameter type, the implicit conversion 
2279       // sequence associated with the parameter is defined to be the unique conversion 
2280       // sequence designated the ambiguous conversion sequence. For the purpose of 
2281       // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous 
2282       // conversion sequence is treated as a user-defined sequence that is 
2283       // indistinguishable from any other user-defined conversion sequence
2284         if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
2285           Candidate.Conversions[ArgIdx].ConversionKind =
2286             ImplicitConversionSequence::UserDefinedConversion;
2287           // Set the conversion function to one of them. As due to ambiguity,
2288           // they carry the same weight and is needed for overload resolution
2289           // later.
2290           Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2291             Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2292         }
2293         else {
2294           Candidate.Viable = false;
2295           break;
2296         }
2297       }
2298     } else {
2299       // (C++ 13.3.2p2): For the purposes of overload resolution, any
2300       // argument for which there is no corresponding parameter is
2301       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2302       Candidate.Conversions[ArgIdx].ConversionKind
2303         = ImplicitConversionSequence::EllipsisConversion;
2304     }
2305   }
2306 }
2307
2308 /// \brief Add all of the function declarations in the given function set to
2309 /// the overload canddiate set.
2310 void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2311                                  Expr **Args, unsigned NumArgs,
2312                                  OverloadCandidateSet& CandidateSet,
2313                                  bool SuppressUserConversions) {
2314   for (FunctionSet::const_iterator F = Functions.begin(),
2315                                 FEnd = Functions.end();
2316        F != FEnd; ++F) {
2317     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2318       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2319         AddMethodCandidate(cast<CXXMethodDecl>(FD),
2320                            Args[0], Args + 1, NumArgs - 1, 
2321                            CandidateSet, SuppressUserConversions);
2322       else
2323         AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2324                              SuppressUserConversions);
2325     } else {
2326       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2327       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2328           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2329         AddMethodTemplateCandidate(FunTmpl,
2330                                    /*FIXME: explicit args */false, 0, 0,
2331                                    Args[0], Args + 1, NumArgs - 1,
2332                                    CandidateSet,
2333                                    SuppressUserConversions);
2334       else
2335         AddTemplateOverloadCandidate(FunTmpl,
2336                                      /*FIXME: explicit args */false, 0, 0,
2337                                      Args, NumArgs, CandidateSet,
2338                                      SuppressUserConversions);
2339     }
2340   }
2341 }
2342
2343 /// AddMethodCandidate - Adds the given C++ member function to the set
2344 /// of candidate functions, using the given function call arguments
2345 /// and the object argument (@c Object). For example, in a call
2346 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2347 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2348 /// allow user-defined conversions via constructors or conversion
2349 /// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2350 /// a slightly hacky way to implement the overloading rules for elidable copy
2351 /// initialization in C++0x (C++0x 12.8p15).
2352 void
2353 Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2354                          Expr **Args, unsigned NumArgs,
2355                          OverloadCandidateSet& CandidateSet,
2356                          bool SuppressUserConversions, bool ForceRValue) {
2357   const FunctionProtoType* Proto
2358     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
2359   assert(Proto && "Methods without a prototype cannot be overloaded");
2360   assert(!isa<CXXConversionDecl>(Method) &&
2361          "Use AddConversionCandidate for conversion functions");
2362   assert(!isa<CXXConstructorDecl>(Method) &&
2363          "Use AddOverloadCandidate for constructors");
2364
2365   if (!CandidateSet.isNewCandidate(Method))
2366     return;
2367
2368   // Add this candidate
2369   CandidateSet.push_back(OverloadCandidate());
2370   OverloadCandidate& Candidate = CandidateSet.back();
2371   Candidate.Function = Method;
2372   Candidate.IsSurrogate = false;
2373   Candidate.IgnoreObjectArgument = false;
2374
2375   unsigned NumArgsInProto = Proto->getNumArgs();
2376
2377   // (C++ 13.3.2p2): A candidate function having fewer than m
2378   // parameters is viable only if it has an ellipsis in its parameter
2379   // list (8.3.5).
2380   if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2381     Candidate.Viable = false;
2382     return;
2383   }
2384
2385   // (C++ 13.3.2p2): A candidate function having more than m parameters
2386   // is viable only if the (m+1)st parameter has a default argument
2387   // (8.3.6). For the purposes of overload resolution, the
2388   // parameter list is truncated on the right, so that there are
2389   // exactly m parameters.
2390   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2391   if (NumArgs < MinRequiredArgs) {
2392     // Not enough arguments.
2393     Candidate.Viable = false;
2394     return;
2395   }
2396
2397   Candidate.Viable = true;
2398   Candidate.Conversions.resize(NumArgs + 1);
2399
2400   if (Method->isStatic() || !Object)
2401     // The implicit object argument is ignored.
2402     Candidate.IgnoreObjectArgument = true;
2403   else {
2404     // Determine the implicit conversion sequence for the object
2405     // parameter.
2406     Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2407     if (Candidate.Conversions[0].ConversionKind
2408           == ImplicitConversionSequence::BadConversion) {
2409       Candidate.Viable = false;
2410       return;
2411     }
2412   }
2413
2414   // Determine the implicit conversion sequences for each of the
2415   // arguments.
2416   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2417     if (ArgIdx < NumArgsInProto) {
2418       // (C++ 13.3.2p3): for F to be a viable function, there shall
2419       // exist for each argument an implicit conversion sequence
2420       // (13.3.3.1) that converts that argument to the corresponding
2421       // parameter of F.
2422       QualType ParamType = Proto->getArgType(ArgIdx);
2423       Candidate.Conversions[ArgIdx + 1]
2424         = TryCopyInitialization(Args[ArgIdx], ParamType,
2425                                 SuppressUserConversions, ForceRValue,
2426                                 /*InOverloadResolution=*/true);
2427       if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2428             == ImplicitConversionSequence::BadConversion) {
2429         Candidate.Viable = false;
2430         break;
2431       }
2432     } else {
2433       // (C++ 13.3.2p2): For the purposes of overload resolution, any
2434       // argument for which there is no corresponding parameter is
2435       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2436       Candidate.Conversions[ArgIdx + 1].ConversionKind
2437         = ImplicitConversionSequence::EllipsisConversion;
2438     }
2439   }
2440 }
2441
2442 /// \brief Add a C++ member function template as a candidate to the candidate
2443 /// set, using template argument deduction to produce an appropriate member
2444 /// function template specialization.
2445 void
2446 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2447                                  bool HasExplicitTemplateArgs,
2448                              const TemplateArgumentLoc *ExplicitTemplateArgs,
2449                                  unsigned NumExplicitTemplateArgs,
2450                                  Expr *Object, Expr **Args, unsigned NumArgs,
2451                                  OverloadCandidateSet& CandidateSet,
2452                                  bool SuppressUserConversions,
2453                                  bool ForceRValue) {
2454   if (!CandidateSet.isNewCandidate(MethodTmpl))
2455     return;
2456
2457   // C++ [over.match.funcs]p7:
2458   //   In each case where a candidate is a function template, candidate
2459   //   function template specializations are generated using template argument
2460   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2461   //   candidate functions in the usual way.113) A given name can refer to one
2462   //   or more function templates and also to a set of overloaded non-template
2463   //   functions. In such a case, the candidate functions generated from each
2464   //   function template are combined with the set of non-template candidate
2465   //   functions.
2466   TemplateDeductionInfo Info(Context);
2467   FunctionDecl *Specialization = 0;
2468   if (TemplateDeductionResult Result
2469       = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2470                                 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2471                                 Args, NumArgs, Specialization, Info)) {
2472         // FIXME: Record what happened with template argument deduction, so
2473         // that we can give the user a beautiful diagnostic.
2474         (void)Result;
2475         return;
2476       }
2477
2478   // Add the function template specialization produced by template argument
2479   // deduction as a candidate.
2480   assert(Specialization && "Missing member function template specialization?");
2481   assert(isa<CXXMethodDecl>(Specialization) &&
2482          "Specialization is not a member function?");
2483   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2484                      CandidateSet, SuppressUserConversions, ForceRValue);
2485 }
2486
2487 /// \brief Add a C++ function template specialization as a candidate
2488 /// in the candidate set, using template argument deduction to produce
2489 /// an appropriate function template specialization.
2490 void
2491 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2492                                    bool HasExplicitTemplateArgs,
2493                           const TemplateArgumentLoc *ExplicitTemplateArgs,
2494                                    unsigned NumExplicitTemplateArgs,
2495                                    Expr **Args, unsigned NumArgs,
2496                                    OverloadCandidateSet& CandidateSet,
2497                                    bool SuppressUserConversions,
2498                                    bool ForceRValue) {
2499   if (!CandidateSet.isNewCandidate(FunctionTemplate))
2500     return;
2501
2502   // C++ [over.match.funcs]p7:
2503   //   In each case where a candidate is a function template, candidate
2504   //   function template specializations are generated using template argument
2505   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2506   //   candidate functions in the usual way.113) A given name can refer to one
2507   //   or more function templates and also to a set of overloaded non-template
2508   //   functions. In such a case, the candidate functions generated from each
2509   //   function template are combined with the set of non-template candidate
2510   //   functions.
2511   TemplateDeductionInfo Info(Context);
2512   FunctionDecl *Specialization = 0;
2513   if (TemplateDeductionResult Result
2514         = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2515                                   ExplicitTemplateArgs, NumExplicitTemplateArgs,
2516                                   Args, NumArgs, Specialization, Info)) {
2517     // FIXME: Record what happened with template argument deduction, so
2518     // that we can give the user a beautiful diagnostic.
2519     (void)Result;
2520     return;
2521   }
2522
2523   // Add the function template specialization produced by template argument
2524   // deduction as a candidate.
2525   assert(Specialization && "Missing function template specialization?");
2526   AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2527                        SuppressUserConversions, ForceRValue);
2528 }
2529
2530 /// AddConversionCandidate - Add a C++ conversion function as a
2531 /// candidate in the candidate set (C++ [over.match.conv],
2532 /// C++ [over.match.copy]). From is the expression we're converting from,
2533 /// and ToType is the type that we're eventually trying to convert to
2534 /// (which may or may not be the same type as the type that the
2535 /// conversion function produces).
2536 void
2537 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2538                              Expr *From, QualType ToType,
2539                              OverloadCandidateSet& CandidateSet) {
2540   assert(!Conversion->getDescribedFunctionTemplate() &&
2541          "Conversion function templates use AddTemplateConversionCandidate");
2542
2543   if (!CandidateSet.isNewCandidate(Conversion))
2544     return;
2545
2546   // Add this candidate
2547   CandidateSet.push_back(OverloadCandidate());
2548   OverloadCandidate& Candidate = CandidateSet.back();
2549   Candidate.Function = Conversion;
2550   Candidate.IsSurrogate = false;
2551   Candidate.IgnoreObjectArgument = false;
2552   Candidate.FinalConversion.setAsIdentityConversion();
2553   Candidate.FinalConversion.FromTypePtr
2554     = Conversion->getConversionType().getAsOpaquePtr();
2555   Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2556
2557   // Determine the implicit conversion sequence for the implicit
2558   // object parameter.
2559   Candidate.Viable = true;
2560   Candidate.Conversions.resize(1);
2561   Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2562   // Conversion functions to a different type in the base class is visible in 
2563   // the derived class.  So, a derived to base conversion should not participate
2564   // in overload resolution. 
2565   if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2566     Candidate.Conversions[0].Standard.Second = ICK_Identity;
2567   if (Candidate.Conversions[0].ConversionKind
2568       == ImplicitConversionSequence::BadConversion) {
2569     Candidate.Viable = false;
2570     return;
2571   }
2572   
2573   // We won't go through a user-define type conversion function to convert a 
2574   // derived to base as such conversions are given Conversion Rank. They only
2575   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2576   QualType FromCanon
2577     = Context.getCanonicalType(From->getType().getUnqualifiedType());
2578   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2579   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2580     Candidate.Viable = false;
2581     return;
2582   }
2583   
2584
2585   // To determine what the conversion from the result of calling the
2586   // conversion function to the type we're eventually trying to
2587   // convert to (ToType), we need to synthesize a call to the
2588   // conversion function and attempt copy initialization from it. This
2589   // makes sure that we get the right semantics with respect to
2590   // lvalues/rvalues and the type. Fortunately, we can allocate this
2591   // call on the stack and we don't need its arguments to be
2592   // well-formed.
2593   DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2594                             SourceLocation());
2595   ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2596                                 CastExpr::CK_FunctionToPointerDecay,
2597                                 &ConversionRef, false);
2598
2599   // Note that it is safe to allocate CallExpr on the stack here because
2600   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2601   // allocator).
2602   CallExpr Call(Context, &ConversionFn, 0, 0,
2603                 Conversion->getConversionType().getNonReferenceType(),
2604                 SourceLocation());
2605   ImplicitConversionSequence ICS =
2606     TryCopyInitialization(&Call, ToType,
2607                           /*SuppressUserConversions=*/true,
2608                           /*ForceRValue=*/false,
2609                           /*InOverloadResolution=*/false);
2610
2611   switch (ICS.ConversionKind) {
2612   case ImplicitConversionSequence::StandardConversion:
2613     Candidate.FinalConversion = ICS.Standard;
2614     break;
2615
2616   case ImplicitConversionSequence::BadConversion:
2617     Candidate.Viable = false;
2618     break;
2619
2620   default:
2621     assert(false &&
2622            "Can only end up with a standard conversion sequence or failure");
2623   }
2624 }
2625
2626 /// \brief Adds a conversion function template specialization
2627 /// candidate to the overload set, using template argument deduction
2628 /// to deduce the template arguments of the conversion function
2629 /// template from the type that we are converting to (C++
2630 /// [temp.deduct.conv]).
2631 void
2632 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2633                                      Expr *From, QualType ToType,
2634                                      OverloadCandidateSet &CandidateSet) {
2635   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2636          "Only conversion function templates permitted here");
2637
2638   if (!CandidateSet.isNewCandidate(FunctionTemplate))
2639     return;
2640
2641   TemplateDeductionInfo Info(Context);
2642   CXXConversionDecl *Specialization = 0;
2643   if (TemplateDeductionResult Result
2644         = DeduceTemplateArguments(FunctionTemplate, ToType,
2645                                   Specialization, Info)) {
2646     // FIXME: Record what happened with template argument deduction, so
2647     // that we can give the user a beautiful diagnostic.
2648     (void)Result;
2649     return;
2650   }
2651
2652   // Add the conversion function template specialization produced by
2653   // template argument deduction as a candidate.
2654   assert(Specialization && "Missing function template specialization?");
2655   AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2656 }
2657
2658 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2659 /// converts the given @c Object to a function pointer via the
2660 /// conversion function @c Conversion, and then attempts to call it
2661 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
2662 /// the type of function that we'll eventually be calling.
2663 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2664                                  const FunctionProtoType *Proto,
2665                                  Expr *Object, Expr **Args, unsigned NumArgs,
2666                                  OverloadCandidateSet& CandidateSet) {
2667   if (!CandidateSet.isNewCandidate(Conversion))
2668     return;
2669
2670   CandidateSet.push_back(OverloadCandidate());
2671   OverloadCandidate& Candidate = CandidateSet.back();
2672   Candidate.Function = 0;
2673   Candidate.Surrogate = Conversion;
2674   Candidate.Viable = true;
2675   Candidate.IsSurrogate = true;
2676   Candidate.IgnoreObjectArgument = false;
2677   Candidate.Conversions.resize(NumArgs + 1);
2678
2679   // Determine the implicit conversion sequence for the implicit
2680   // object parameter.
2681   ImplicitConversionSequence ObjectInit
2682     = TryObjectArgumentInitialization(Object, Conversion);
2683   if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2684     Candidate.Viable = false;
2685     return;
2686   }
2687
2688   // The first conversion is actually a user-defined conversion whose
2689   // first conversion is ObjectInit's standard conversion (which is
2690   // effectively a reference binding). Record it as such.
2691   Candidate.Conversions[0].ConversionKind
2692     = ImplicitConversionSequence::UserDefinedConversion;
2693   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2694   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2695   Candidate.Conversions[0].UserDefined.After
2696     = Candidate.Conversions[0].UserDefined.Before;
2697   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2698
2699   // Find the
2700   unsigned NumArgsInProto = Proto->getNumArgs();
2701
2702   // (C++ 13.3.2p2): A candidate function having fewer than m
2703   // parameters is viable only if it has an ellipsis in its parameter
2704   // list (8.3.5).
2705   if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2706     Candidate.Viable = false;
2707     return;
2708   }
2709
2710   // Function types don't have any default arguments, so just check if
2711   // we have enough arguments.
2712   if (NumArgs < NumArgsInProto) {
2713     // Not enough arguments.
2714     Candidate.Viable = false;
2715     return;
2716   }
2717
2718   // Determine the implicit conversion sequences for each of the
2719   // arguments.
2720   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2721     if (ArgIdx < NumArgsInProto) {
2722       // (C++ 13.3.2p3): for F to be a viable function, there shall
2723       // exist for each argument an implicit conversion sequence
2724       // (13.3.3.1) that converts that argument to the corresponding
2725       // parameter of F.
2726       QualType ParamType = Proto->getArgType(ArgIdx);
2727       Candidate.Conversions[ArgIdx + 1]
2728         = TryCopyInitialization(Args[ArgIdx], ParamType,
2729                                 /*SuppressUserConversions=*/false,
2730                                 /*ForceRValue=*/false,
2731                                 /*InOverloadResolution=*/false);
2732       if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2733             == ImplicitConversionSequence::BadConversion) {
2734         Candidate.Viable = false;
2735         break;
2736       }
2737     } else {
2738       // (C++ 13.3.2p2): For the purposes of overload resolution, any
2739       // argument for which there is no corresponding parameter is
2740       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2741       Candidate.Conversions[ArgIdx + 1].ConversionKind
2742         = ImplicitConversionSequence::EllipsisConversion;
2743     }
2744   }
2745 }
2746
2747 // FIXME: This will eventually be removed, once we've migrated all of the
2748 // operator overloading logic over to the scheme used by binary operators, which
2749 // works for template instantiation.
2750 void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2751                                  SourceLocation OpLoc,
2752                                  Expr **Args, unsigned NumArgs,
2753                                  OverloadCandidateSet& CandidateSet,
2754                                  SourceRange OpRange) {
2755   FunctionSet Functions;
2756
2757   QualType T1 = Args[0]->getType();
2758   QualType T2;
2759   if (NumArgs > 1)
2760     T2 = Args[1]->getType();
2761
2762   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2763   if (S)
2764     LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2765   ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
2766   AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2767   AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2768   AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
2769 }
2770
2771 /// \brief Add overload candidates for overloaded operators that are
2772 /// member functions.
2773 ///
2774 /// Add the overloaded operator candidates that are member functions
2775 /// for the operator Op that was used in an operator expression such
2776 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
2777 /// CandidateSet will store the added overload candidates. (C++
2778 /// [over.match.oper]).
2779 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2780                                        SourceLocation OpLoc,
2781                                        Expr **Args, unsigned NumArgs,
2782                                        OverloadCandidateSet& CandidateSet,
2783                                        SourceRange OpRange) {
2784   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2785
2786   // C++ [over.match.oper]p3:
2787   //   For a unary operator @ with an operand of a type whose
2788   //   cv-unqualified version is T1, and for a binary operator @ with
2789   //   a left operand of a type whose cv-unqualified version is T1 and
2790   //   a right operand of a type whose cv-unqualified version is T2,
2791   //   three sets of candidate functions, designated member
2792   //   candidates, non-member candidates and built-in candidates, are
2793   //   constructed as follows:
2794   QualType T1 = Args[0]->getType();
2795   QualType T2;
2796   if (NumArgs > 1)
2797     T2 = Args[1]->getType();
2798
2799   //     -- If T1 is a class type, the set of member candidates is the
2800   //        result of the qualified lookup of T1::operator@
2801   //        (13.3.1.1.1); otherwise, the set of member candidates is
2802   //        empty.
2803   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
2804     // Complete the type if it can be completed. Otherwise, we're done.
2805     if (RequireCompleteType(OpLoc, T1, PDiag()))
2806       return;
2807
2808     LookupResult Operators;
2809     LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2810                         LookupOrdinaryName, false);
2811     for (LookupResult::iterator Oper = Operators.begin(),
2812                              OperEnd = Operators.end();
2813          Oper != OperEnd;
2814          ++Oper) {
2815       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Oper)) {
2816         AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2817                            /*SuppressUserConversions=*/false);
2818         continue;
2819       }
2820       
2821       assert(isa<FunctionTemplateDecl>(*Oper) && 
2822              isa<CXXMethodDecl>(cast<FunctionTemplateDecl>(*Oper)
2823                                                         ->getTemplatedDecl()) &&
2824              "Expected a member function template");
2825       AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Oper), false, 0, 0, 
2826                                  Args[0], Args+1, NumArgs - 1, CandidateSet, 
2827                                  /*SuppressUserConversions=*/false);
2828     }
2829   }
2830 }
2831
2832 /// AddBuiltinCandidate - Add a candidate for a built-in
2833 /// operator. ResultTy and ParamTys are the result and parameter types
2834 /// of the built-in candidate, respectively. Args and NumArgs are the
2835 /// arguments being passed to the candidate. IsAssignmentOperator
2836 /// should be true when this built-in candidate is an assignment
2837 /// operator. NumContextualBoolArguments is the number of arguments
2838 /// (at the beginning of the argument list) that will be contextually
2839 /// converted to bool.
2840 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2841                                Expr **Args, unsigned NumArgs,
2842                                OverloadCandidateSet& CandidateSet,
2843                                bool IsAssignmentOperator,
2844                                unsigned NumContextualBoolArguments) {
2845   // Add this candidate
2846   CandidateSet.push_back(OverloadCandidate());
2847   OverloadCandidate& Candidate = CandidateSet.back();
2848   Candidate.Function = 0;
2849   Candidate.IsSurrogate = false;
2850   Candidate.IgnoreObjectArgument = false;
2851   Candidate.BuiltinTypes.ResultTy = ResultTy;
2852   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2853     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2854
2855   // Determine the implicit conversion sequences for each of the
2856   // arguments.
2857   Candidate.Viable = true;
2858   Candidate.Conversions.resize(NumArgs);
2859   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2860     // C++ [over.match.oper]p4:
2861     //   For the built-in assignment operators, conversions of the
2862     //   left operand are restricted as follows:
2863     //     -- no temporaries are introduced to hold the left operand, and
2864     //     -- no user-defined conversions are applied to the left
2865     //        operand to achieve a type match with the left-most
2866     //        parameter of a built-in candidate.
2867     //
2868     // We block these conversions by turning off user-defined
2869     // conversions, since that is the only way that initialization of
2870     // a reference to a non-class type can occur from something that
2871     // is not of the same type.
2872     if (ArgIdx < NumContextualBoolArguments) {
2873       assert(ParamTys[ArgIdx] == Context.BoolTy &&
2874              "Contextual conversion to bool requires bool type");
2875       Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2876     } else {
2877       Candidate.Conversions[ArgIdx]
2878         = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2879                                 ArgIdx == 0 && IsAssignmentOperator,
2880                                 /*ForceRValue=*/false,
2881                                 /*InOverloadResolution=*/false);
2882     }
2883     if (Candidate.Conversions[ArgIdx].ConversionKind
2884         == ImplicitConversionSequence::BadConversion) {
2885       Candidate.Viable = false;
2886       break;
2887     }
2888   }
2889 }
2890
2891 /// BuiltinCandidateTypeSet - A set of types that will be used for the
2892 /// candidate operator functions for built-in operators (C++
2893 /// [over.built]). The types are separated into pointer types and
2894 /// enumeration types.
2895 class BuiltinCandidateTypeSet  {
2896   /// TypeSet - A set of types.
2897   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2898
2899   /// PointerTypes - The set of pointer types that will be used in the
2900   /// built-in candidates.
2901   TypeSet PointerTypes;
2902
2903   /// MemberPointerTypes - The set of member pointer types that will be
2904   /// used in the built-in candidates.
2905   TypeSet MemberPointerTypes;
2906
2907   /// EnumerationTypes - The set of enumeration types that will be
2908   /// used in the built-in candidates.
2909   TypeSet EnumerationTypes;
2910
2911   /// Sema - The semantic analysis instance where we are building the
2912   /// candidate type set.
2913   Sema &SemaRef;
2914
2915   /// Context - The AST context in which we will build the type sets.
2916   ASTContext &Context;
2917
2918   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2919                                                const Qualifiers &VisibleQuals);
2920   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
2921
2922 public:
2923   /// iterator - Iterates through the types that are part of the set.
2924   typedef TypeSet::iterator iterator;
2925
2926   BuiltinCandidateTypeSet(Sema &SemaRef)
2927     : SemaRef(SemaRef), Context(SemaRef.Context) { }
2928
2929   void AddTypesConvertedFrom(QualType Ty, 
2930                              SourceLocation Loc,
2931                              bool AllowUserConversions,
2932                              bool AllowExplicitConversions,
2933                              const Qualifiers &VisibleTypeConversionsQuals);
2934
2935   /// pointer_begin - First pointer type found;
2936   iterator pointer_begin() { return PointerTypes.begin(); }
2937
2938   /// pointer_end - Past the last pointer type found;
2939   iterator pointer_end() { return PointerTypes.end(); }
2940
2941   /// member_pointer_begin - First member pointer type found;
2942   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2943
2944   /// member_pointer_end - Past the last member pointer type found;
2945   iterator member_pointer_end() { return MemberPointerTypes.end(); }
2946
2947   /// enumeration_begin - First enumeration type found;
2948   iterator enumeration_begin() { return EnumerationTypes.begin(); }
2949
2950   /// enumeration_end - Past the last enumeration type found;
2951   iterator enumeration_end() { return EnumerationTypes.end(); }
2952 };
2953
2954 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2955 /// the set of pointer types along with any more-qualified variants of
2956 /// that type. For example, if @p Ty is "int const *", this routine
2957 /// will add "int const *", "int const volatile *", "int const
2958 /// restrict *", and "int const volatile restrict *" to the set of
2959 /// pointer types. Returns true if the add of @p Ty itself succeeded,
2960 /// false otherwise.
2961 ///
2962 /// FIXME: what to do about extended qualifiers?
2963 bool
2964 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2965                                              const Qualifiers &VisibleQuals) {
2966
2967   // Insert this type.
2968   if (!PointerTypes.insert(Ty))
2969     return false;
2970
2971   const PointerType *PointerTy = Ty->getAs<PointerType>();
2972   assert(PointerTy && "type was not a pointer type!");
2973
2974   QualType PointeeTy = PointerTy->getPointeeType();
2975   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2976   bool hasVolatile = VisibleQuals.hasVolatile();
2977   bool hasRestrict = VisibleQuals.hasRestrict();
2978   
2979   // Iterate through all strict supersets of BaseCVR.
2980   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2981     if ((CVR | BaseCVR) != CVR) continue;
2982     // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
2983     // in the types.
2984     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
2985     if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
2986     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2987     PointerTypes.insert(Context.getPointerType(QPointeeTy));
2988   }
2989
2990   return true;
2991 }
2992
2993 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2994 /// to the set of pointer types along with any more-qualified variants of
2995 /// that type. For example, if @p Ty is "int const *", this routine
2996 /// will add "int const *", "int const volatile *", "int const
2997 /// restrict *", and "int const volatile restrict *" to the set of
2998 /// pointer types. Returns true if the add of @p Ty itself succeeded,
2999 /// false otherwise.
3000 ///
3001 /// FIXME: what to do about extended qualifiers?
3002 bool
3003 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3004     QualType Ty) {
3005   // Insert this type.
3006   if (!MemberPointerTypes.insert(Ty))
3007     return false;
3008
3009   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3010   assert(PointerTy && "type was not a member pointer type!");
3011
3012   QualType PointeeTy = PointerTy->getPointeeType();
3013   const Type *ClassTy = PointerTy->getClass();
3014
3015   // Iterate through all strict supersets of the pointee type's CVR
3016   // qualifiers.
3017   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3018   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3019     if ((CVR | BaseCVR) != CVR) continue;
3020     
3021     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3022     MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
3023   }
3024
3025   return true;
3026 }
3027
3028 /// AddTypesConvertedFrom - Add each of the types to which the type @p
3029 /// Ty can be implicit converted to the given set of @p Types. We're
3030 /// primarily interested in pointer types and enumeration types. We also
3031 /// take member pointer types, for the conditional operator.
3032 /// AllowUserConversions is true if we should look at the conversion
3033 /// functions of a class type, and AllowExplicitConversions if we
3034 /// should also include the explicit conversion functions of a class
3035 /// type.
3036 void
3037 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
3038                                                SourceLocation Loc,
3039                                                bool AllowUserConversions,
3040                                                bool AllowExplicitConversions,
3041                                                const Qualifiers &VisibleQuals) {
3042   // Only deal with canonical types.
3043   Ty = Context.getCanonicalType(Ty);
3044
3045   // Look through reference types; they aren't part of the type of an
3046   // expression for the purposes of conversions.
3047   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3048     Ty = RefTy->getPointeeType();
3049
3050   // We don't care about qualifiers on the type.
3051   Ty = Ty.getUnqualifiedType();
3052
3053   if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
3054     QualType PointeeTy = PointerTy->getPointeeType();
3055
3056     // Insert our type, and its more-qualified variants, into the set
3057     // of types.
3058     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
3059       return;
3060   } else if (Ty->isMemberPointerType()) {
3061     // Member pointers are far easier, since the pointee can't be converted.
3062     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3063       return;
3064   } else if (Ty->isEnumeralType()) {
3065     EnumerationTypes.insert(Ty);
3066   } else if (AllowUserConversions) {
3067     if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3068       if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
3069         // No conversion functions in incomplete types.
3070         return;
3071       }
3072
3073       CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3074       OverloadedFunctionDecl *Conversions
3075         = ClassDecl->getVisibleConversionFunctions();
3076       for (OverloadedFunctionDecl::function_iterator Func
3077              = Conversions->function_begin();
3078            Func != Conversions->function_end(); ++Func) {
3079         CXXConversionDecl *Conv;
3080         FunctionTemplateDecl *ConvTemplate;
3081         GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3082
3083         // Skip conversion function templates; they don't tell us anything
3084         // about which builtin types we can convert to.
3085         if (ConvTemplate)
3086           continue;
3087
3088         if (AllowExplicitConversions || !Conv->isExplicit()) {
3089           AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 
3090                                 VisibleQuals);
3091         }
3092       }
3093     }
3094   }
3095 }
3096
3097 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3098 /// the volatile- and non-volatile-qualified assignment operators for the
3099 /// given type to the candidate set.
3100 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3101                                                    QualType T,
3102                                                    Expr **Args,
3103                                                    unsigned NumArgs,
3104                                     OverloadCandidateSet &CandidateSet) {
3105   QualType ParamTypes[2];
3106
3107   // T& operator=(T&, T)
3108   ParamTypes[0] = S.Context.getLValueReferenceType(T);
3109   ParamTypes[1] = T;
3110   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3111                         /*IsAssignmentOperator=*/true);
3112
3113   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3114     // volatile T& operator=(volatile T&, T)
3115     ParamTypes[0]
3116       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3117     ParamTypes[1] = T;
3118     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3119                           /*IsAssignmentOperator=*/true);
3120   }
3121 }
3122
3123 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3124 /// if any, found in visible type conversion functions found in ArgExpr's type.
3125 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3126     Qualifiers VRQuals;
3127     const RecordType *TyRec;
3128     if (const MemberPointerType *RHSMPType =
3129         ArgExpr->getType()->getAs<MemberPointerType>())
3130       TyRec = cast<RecordType>(RHSMPType->getClass());
3131     else
3132       TyRec = ArgExpr->getType()->getAs<RecordType>();
3133     if (!TyRec) {
3134       // Just to be safe, assume the worst case.
3135       VRQuals.addVolatile();
3136       VRQuals.addRestrict();
3137       return VRQuals;
3138     }
3139     
3140     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3141     OverloadedFunctionDecl *Conversions =
3142       ClassDecl->getVisibleConversionFunctions();
3143     
3144     for (OverloadedFunctionDecl::function_iterator Func
3145          = Conversions->function_begin();
3146          Func != Conversions->function_end(); ++Func) {
3147       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3148         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3149         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3150           CanTy = ResTypeRef->getPointeeType();
3151         // Need to go down the pointer/mempointer chain and add qualifiers
3152         // as see them.
3153         bool done = false;
3154         while (!done) {
3155           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3156             CanTy = ResTypePtr->getPointeeType();
3157           else if (const MemberPointerType *ResTypeMPtr = 
3158                 CanTy->getAs<MemberPointerType>())
3159             CanTy = ResTypeMPtr->getPointeeType();
3160           else
3161             done = true;
3162           if (CanTy.isVolatileQualified())
3163             VRQuals.addVolatile();
3164           if (CanTy.isRestrictQualified())
3165             VRQuals.addRestrict();
3166           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3167             return VRQuals;
3168         }
3169       }
3170     }
3171     return VRQuals;
3172 }
3173   
3174 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
3175 /// operator overloads to the candidate set (C++ [over.built]), based
3176 /// on the operator @p Op and the arguments given. For example, if the
3177 /// operator is a binary '+', this routine might add "int
3178 /// operator+(int, int)" to cover integer addition.
3179 void
3180 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3181                                    SourceLocation OpLoc,
3182                                    Expr **Args, unsigned NumArgs,
3183                                    OverloadCandidateSet& CandidateSet) {
3184   // The set of "promoted arithmetic types", which are the arithmetic
3185   // types are that preserved by promotion (C++ [over.built]p2). Note
3186   // that the first few of these types are the promoted integral
3187   // types; these types need to be first.
3188   // FIXME: What about complex?
3189   const unsigned FirstIntegralType = 0;
3190   const unsigned LastIntegralType = 13;
3191   const unsigned FirstPromotedIntegralType = 7,
3192                  LastPromotedIntegralType = 13;
3193   const unsigned FirstPromotedArithmeticType = 7,
3194                  LastPromotedArithmeticType = 16;
3195   const unsigned NumArithmeticTypes = 16;
3196   QualType ArithmeticTypes[NumArithmeticTypes] = {
3197     Context.BoolTy, Context.CharTy, Context.WCharTy,
3198 // FIXME:   Context.Char16Ty, Context.Char32Ty,
3199     Context.SignedCharTy, Context.ShortTy,
3200     Context.UnsignedCharTy, Context.UnsignedShortTy,
3201     Context.IntTy, Context.LongTy, Context.LongLongTy,
3202     Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3203     Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3204   };
3205   assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3206          "Invalid first promoted integral type");
3207   assert(ArithmeticTypes[LastPromotedIntegralType - 1] 
3208            == Context.UnsignedLongLongTy &&
3209          "Invalid last promoted integral type");
3210   assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3211          "Invalid first promoted arithmetic type");
3212   assert(ArithmeticTypes[LastPromotedArithmeticType - 1] 
3213             == Context.LongDoubleTy &&
3214          "Invalid last promoted arithmetic type");
3215          
3216   // Find all of the types that the arguments can convert to, but only
3217   // if the operator we're looking at has built-in operator candidates
3218   // that make use of these types.
3219   Qualifiers VisibleTypeConversionsQuals;
3220   VisibleTypeConversionsQuals.addConst();
3221   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3222     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3223   
3224   BuiltinCandidateTypeSet CandidateTypes(*this);
3225   if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3226       Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3227       Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3228       Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3229       Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3230       (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3231     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3232       CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3233                                            OpLoc,
3234                                            true,
3235                                            (Op == OO_Exclaim ||
3236                                             Op == OO_AmpAmp ||
3237                                             Op == OO_PipePipe),
3238                                            VisibleTypeConversionsQuals);
3239   }
3240
3241   bool isComparison = false;
3242   switch (Op) {
3243   case OO_None:
3244   case NUM_OVERLOADED_OPERATORS:
3245     assert(false && "Expected an overloaded operator");
3246     break;
3247
3248   case OO_Star: // '*' is either unary or binary
3249     if (NumArgs == 1)
3250       goto UnaryStar;
3251     else
3252       goto BinaryStar;
3253     break;
3254
3255   case OO_Plus: // '+' is either unary or binary
3256     if (NumArgs == 1)
3257       goto UnaryPlus;
3258     else
3259       goto BinaryPlus;
3260     break;
3261
3262   case OO_Minus: // '-' is either unary or binary
3263     if (NumArgs == 1)
3264       goto UnaryMinus;
3265     else
3266       goto BinaryMinus;
3267     break;
3268
3269   case OO_Amp: // '&' is either unary or binary
3270     if (NumArgs == 1)
3271       goto UnaryAmp;
3272     else
3273       goto BinaryAmp;
3274
3275   case OO_PlusPlus:
3276   case OO_MinusMinus:
3277     // C++ [over.built]p3:
3278     //
3279     //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3280     //   is either volatile or empty, there exist candidate operator
3281     //   functions of the form
3282     //
3283     //       VQ T&      operator++(VQ T&);
3284     //       T          operator++(VQ T&, int);
3285     //
3286     // C++ [over.built]p4:
3287     //
3288     //   For every pair (T, VQ), where T is an arithmetic type other
3289     //   than bool, and VQ is either volatile or empty, there exist
3290     //   candidate operator functions of the form
3291     //
3292     //       VQ T&      operator--(VQ T&);
3293     //       T          operator--(VQ T&, int);
3294     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3295          Arith < NumArithmeticTypes; ++Arith) {
3296       QualType ArithTy = ArithmeticTypes[Arith];
3297       QualType ParamTypes[2]
3298         = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3299
3300       // Non-volatile version.
3301       if (NumArgs == 1)
3302         AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3303       else
3304         AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3305       // heuristic to reduce number of builtin candidates in the set.
3306       // Add volatile version only if there are conversions to a volatile type.
3307       if (VisibleTypeConversionsQuals.hasVolatile()) {
3308         // Volatile version
3309         ParamTypes[0]
3310           = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3311         if (NumArgs == 1)
3312           AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3313         else
3314           AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3315       }
3316     }
3317
3318     // C++ [over.built]p5:
3319     //
3320     //   For every pair (T, VQ), where T is a cv-qualified or
3321     //   cv-unqualified object type, and VQ is either volatile or
3322     //   empty, there exist candidate operator functions of the form
3323     //
3324     //       T*VQ&      operator++(T*VQ&);
3325     //       T*VQ&      operator--(T*VQ&);
3326     //       T*         operator++(T*VQ&, int);
3327     //       T*         operator--(T*VQ&, int);
3328     for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3329          Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3330       // Skip pointer types that aren't pointers to object types.
3331       if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3332         continue;
3333
3334       QualType ParamTypes[2] = {
3335         Context.getLValueReferenceType(*Ptr), Context.IntTy
3336       };
3337
3338       // Without volatile
3339       if (NumArgs == 1)
3340         AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3341       else
3342         AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3343
3344       if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3345           VisibleTypeConversionsQuals.hasVolatile()) {
3346         // With volatile
3347         ParamTypes[0]
3348           = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3349         if (NumArgs == 1)
3350           AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3351         else
3352           AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3353       }
3354     }
3355     break;
3356
3357   UnaryStar:
3358     // C++ [over.built]p6:
3359     //   For every cv-qualified or cv-unqualified object type T, there
3360     //   exist candidate operator functions of the form
3361     //
3362     //       T&         operator*(T*);
3363     //
3364     // C++ [over.built]p7:
3365     //   For every function type T, there exist candidate operator
3366     //   functions of the form
3367     //       T&         operator*(T*);
3368     for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3369          Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3370       QualType ParamTy = *Ptr;
3371       QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3372       AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3373                           &ParamTy, Args, 1, CandidateSet);
3374     }
3375     break;
3376
3377   UnaryPlus:
3378     // C++ [over.built]p8:
3379     //   For every type T, there exist candidate operator functions of
3380     //   the form
3381     //
3382     //       T*         operator+(T*);
3383     for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3384          Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3385       QualType ParamTy = *Ptr;
3386       AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3387     }
3388
3389     // Fall through
3390
3391   UnaryMinus:
3392     // C++ [over.built]p9:
3393     //  For every promoted arithmetic type T, there exist candidate
3394     //  operator functions of the form
3395     //
3396     //       T         operator+(T);
3397     //       T         operator-(T);
3398     for (unsigned Arith = FirstPromotedArithmeticType;
3399          Arith < LastPromotedArithmeticType; ++Arith) {
3400       QualType ArithTy = ArithmeticTypes[Arith];
3401       AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3402     }
3403     break;
3404
3405   case OO_Tilde:
3406     // C++ [over.built]p10:
3407     //   For every promoted integral type T, there exist candidate
3408     //   operator functions of the form
3409     //
3410     //        T         operator~(T);
3411     for (unsigned Int = FirstPromotedIntegralType;
3412          Int < LastPromotedIntegralType; ++Int) {
3413       QualType IntTy = ArithmeticTypes[Int];
3414       AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3415     }
3416     break;
3417
3418   case OO_New:
3419   case OO_Delete:
3420   case OO_Array_New:
3421   case OO_Array_Delete:
3422   case OO_Call:
3423     assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3424     break;
3425
3426   case OO_Comma:
3427   UnaryAmp:
3428   case OO_Arrow:
3429     // C++ [over.match.oper]p3:
3430     //   -- For the operator ',', the unary operator '&', or the
3431     //      operator '->', the built-in candidates set is empty.
3432     break;
3433
3434   case OO_EqualEqual:
3435   case OO_ExclaimEqual:
3436     // C++ [over.match.oper]p16:
3437     //   For every pointer to member type T, there exist candidate operator
3438     //   functions of the form
3439     //
3440     //        bool operator==(T,T);
3441     //        bool operator!=(T,T);
3442     for (BuiltinCandidateTypeSet::iterator
3443            MemPtr = CandidateTypes.member_pointer_begin(),
3444            MemPtrEnd = CandidateTypes.member_pointer_end();
3445          MemPtr != MemPtrEnd;
3446          ++MemPtr) {
3447       QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3448       AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3449     }
3450
3451     // Fall through
3452
3453   case OO_Less:
3454   case OO_Greater:
3455   case OO_LessEqual:
3456   case OO_GreaterEqual:
3457     // C++ [over.built]p15:
3458     //
3459     //   For every pointer or enumeration type T, there exist
3460     //   candidate operator functions of the form
3461     //
3462     //        bool       operator<(T, T);
3463     //        bool       operator>(T, T);
3464     //        bool       operator<=(T, T);
3465     //        bool       operator>=(T, T);
3466     //        bool       operator==(T, T);
3467     //        bool       operator!=(T, T);
3468     for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3469          Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3470       QualType ParamTypes[2] = { *Ptr, *Ptr };
3471       AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3472     }
3473     for (BuiltinCandidateTypeSet::iterator Enum
3474            = CandidateTypes.enumeration_begin();
3475          Enum != CandidateTypes.enumeration_end(); ++Enum) {
3476       QualType ParamTypes[2] = { *Enum, *Enum };
3477       AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3478     }
3479
3480     // Fall through.
3481     isComparison = true;
3482
3483   BinaryPlus:
3484   BinaryMinus:
3485     if (!isComparison) {
3486       // We didn't fall through, so we must have OO_Plus or OO_Minus.
3487
3488       // C++ [over.built]p13:
3489       //
3490       //   For every cv-qualified or cv-unqualified object type T
3491       //   there exist candidate operator functions of the form
3492       //
3493       //      T*         operator+(T*, ptrdiff_t);
3494       //      T&         operator[](T*, ptrdiff_t);    [BELOW]
3495       //      T*         operator-(T*, ptrdiff_t);
3496       //      T*         operator+(ptrdiff_t, T*);
3497       //      T&         operator[](ptrdiff_t, T*);    [BELOW]
3498       //
3499       // C++ [over.built]p14:
3500       //
3501       //   For every T, where T is a pointer to object type, there
3502       //   exist candidate operator functions of the form
3503       //
3504       //      ptrdiff_t  operator-(T, T);
3505       for (BuiltinCandidateTypeSet::iterator Ptr
3506              = CandidateTypes.pointer_begin();
3507            Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3508         QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3509
3510         // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3511         AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3512
3513         if (Op == OO_Plus) {
3514           // T* operator+(ptrdiff_t, T*);
3515           ParamTypes[0] = ParamTypes[1];
3516           ParamTypes[1] = *Ptr;
3517           AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3518         } else {
3519           // ptrdiff_t operator-(T, T);
3520           ParamTypes[1] = *Ptr;
3521           AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3522                               Args, 2, CandidateSet);
3523         }
3524       }
3525     }
3526     // Fall through
3527
3528   case OO_Slash:
3529   BinaryStar:
3530   Conditional:
3531     // C++ [over.built]p12:
3532     //
3533     //   For every pair of promoted arithmetic types L and R, there
3534     //   exist candidate operator functions of the form
3535     //
3536     //        LR         operator*(L, R);
3537     //        LR         operator/(L, R);
3538     //        LR         operator+(L, R);
3539     //        LR         operator-(L, R);
3540     //        bool       operator<(L, R);
3541     //        bool       operator>(L, R);
3542     //        bool       operator<=(L, R);
3543     //        bool       operator>=(L, R);
3544     //        bool       operator==(L, R);
3545     //        bool       operator!=(L, R);
3546     //
3547     //   where LR is the result of the usual arithmetic conversions
3548     //   between types L and R.
3549     //
3550     // C++ [over.built]p24:
3551     //
3552     //   For every pair of promoted arithmetic types L and R, there exist
3553     //   candidate operator functions of the form
3554     //
3555     //        LR       operator?(bool, L, R);
3556     //
3557     //   where LR is the result of the usual arithmetic conversions
3558     //   between types L and R.
3559     // Our candidates ignore the first parameter.
3560     for (unsigned Left = FirstPromotedArithmeticType;
3561          Left < LastPromotedArithmeticType; ++Left) {
3562       for (unsigned Right = FirstPromotedArithmeticType;
3563            Right < LastPromotedArithmeticType; ++Right) {
3564         QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3565         QualType Result
3566           = isComparison
3567           ? Context.BoolTy
3568           : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3569         AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3570       }
3571     }
3572     break;
3573
3574   case OO_Percent:
3575   BinaryAmp:
3576   case OO_Caret:
3577   case OO_Pipe:
3578   case OO_LessLess:
3579   case OO_GreaterGreater:
3580     // C++ [over.built]p17:
3581     //
3582     //   For every pair of promoted integral types L and R, there
3583     //   exist candidate operator functions of the form
3584     //
3585     //      LR         operator%(L, R);
3586     //      LR         operator&(L, R);
3587     //      LR         operator^(L, R);
3588     //      LR         operator|(L, R);
3589     //      L          operator<<(L, R);
3590     //      L          operator>>(L, R);
3591     //
3592     //   where LR is the result of the usual arithmetic conversions
3593     //   between types L and R.
3594     for (unsigned Left = FirstPromotedIntegralType;
3595          Left < LastPromotedIntegralType; ++Left) {
3596       for (unsigned Right = FirstPromotedIntegralType;
3597            Right < LastPromotedIntegralType; ++Right) {
3598         QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3599         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3600             ? LandR[0]
3601             : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3602         AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3603       }
3604     }
3605     break;
3606
3607   case OO_Equal:
3608     // C++ [over.built]p20:
3609     //
3610     //   For every pair (T, VQ), where T is an enumeration or
3611     //   pointer to member type and VQ is either volatile or
3612     //   empty, there exist candidate operator functions of the form
3613     //
3614     //        VQ T&      operator=(VQ T&, T);
3615     for (BuiltinCandidateTypeSet::iterator
3616            Enum = CandidateTypes.enumeration_begin(),
3617            EnumEnd = CandidateTypes.enumeration_end();
3618          Enum != EnumEnd; ++Enum)
3619       AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3620                                              CandidateSet);
3621     for (BuiltinCandidateTypeSet::iterator
3622            MemPtr = CandidateTypes.member_pointer_begin(),
3623          MemPtrEnd = CandidateTypes.member_pointer_end();
3624          MemPtr != MemPtrEnd; ++MemPtr)
3625       AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3626                                              CandidateSet);
3627       // Fall through.
3628
3629   case OO_PlusEqual:
3630   case OO_MinusEqual:
3631     // C++ [over.built]p19:
3632     //
3633     //   For every pair (T, VQ), where T is any type and VQ is either
3634     //   volatile or empty, there exist candidate operator functions
3635     //   of the form
3636     //
3637     //        T*VQ&      operator=(T*VQ&, T*);
3638     //
3639     // C++ [over.built]p21:
3640     //
3641     //   For every pair (T, VQ), where T is a cv-qualified or
3642     //   cv-unqualified object type and VQ is either volatile or
3643     //   empty, there exist candidate operator functions of the form
3644     //
3645     //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3646     //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3647     for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3648          Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3649       QualType ParamTypes[2];
3650       ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3651
3652       // non-volatile version
3653       ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3654       AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3655                           /*IsAssigmentOperator=*/Op == OO_Equal);
3656
3657       if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3658           VisibleTypeConversionsQuals.hasVolatile()) {
3659         // volatile version
3660         ParamTypes[0]
3661           = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3662         AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3663                             /*IsAssigmentOperator=*/Op == OO_Equal);
3664       }
3665     }
3666     // Fall through.
3667
3668   case OO_StarEqual:
3669   case OO_SlashEqual:
3670     // C++ [over.built]p18:
3671     //
3672     //   For every triple (L, VQ, R), where L is an arithmetic type,
3673     //   VQ is either volatile or empty, and R is a promoted
3674     //   arithmetic type, there exist candidate operator functions of
3675     //   the form
3676     //
3677     //        VQ L&      operator=(VQ L&, R);
3678     //        VQ L&      operator*=(VQ L&, R);
3679     //        VQ L&      operator/=(VQ L&, R);
3680     //        VQ L&      operator+=(VQ L&, R);
3681     //        VQ L&      operator-=(VQ L&, R);
3682     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3683       for (unsigned Right = FirstPromotedArithmeticType;
3684            Right < LastPromotedArithmeticType; ++Right) {
3685         QualType ParamTypes[2];
3686         ParamTypes[1] = ArithmeticTypes[Right];
3687
3688         // Add this built-in operator as a candidate (VQ is empty).
3689         ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3690         AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3691                             /*IsAssigmentOperator=*/Op == OO_Equal);
3692
3693         // Add this built-in operator as a candidate (VQ is 'volatile').
3694         if (VisibleTypeConversionsQuals.hasVolatile()) {
3695           ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3696           ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3697           AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3698                               /*IsAssigmentOperator=*/Op == OO_Equal);
3699         }
3700       }
3701     }
3702     break;
3703
3704   case OO_PercentEqual:
3705   case OO_LessLessEqual:
3706   case OO_GreaterGreaterEqual:
3707   case OO_AmpEqual:
3708   case OO_CaretEqual:
3709   case OO_PipeEqual:
3710     // C++ [over.built]p22:
3711     //
3712     //   For every triple (L, VQ, R), where L is an integral type, VQ
3713     //   is either volatile or empty, and R is a promoted integral
3714     //   type, there exist candidate operator functions of the form
3715     //
3716     //        VQ L&       operator%=(VQ L&, R);
3717     //        VQ L&       operator<<=(VQ L&, R);
3718     //        VQ L&       operator>>=(VQ L&, R);
3719     //        VQ L&       operator&=(VQ L&, R);
3720     //        VQ L&       operator^=(VQ L&, R);
3721     //        VQ L&       operator|=(VQ L&, R);
3722     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3723       for (unsigned Right = FirstPromotedIntegralType;
3724            Right < LastPromotedIntegralType; ++Right) {
3725         QualType ParamTypes[2];
3726         ParamTypes[1] = ArithmeticTypes[Right];
3727
3728         // Add this built-in operator as a candidate (VQ is empty).
3729         ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3730         AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3731         if (VisibleTypeConversionsQuals.hasVolatile()) {
3732           // Add this built-in operator as a candidate (VQ is 'volatile').
3733           ParamTypes[0] = ArithmeticTypes[Left];
3734           ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3735           ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3736           AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3737         }
3738       }
3739     }
3740     break;
3741
3742   case OO_Exclaim: {
3743     // C++ [over.operator]p23:
3744     //
3745     //   There also exist candidate operator functions of the form
3746     //
3747     //        bool        operator!(bool);
3748     //        bool        operator&&(bool, bool);     [BELOW]
3749     //        bool        operator||(bool, bool);     [BELOW]
3750     QualType ParamTy = Context.BoolTy;
3751     AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3752                         /*IsAssignmentOperator=*/false,
3753                         /*NumContextualBoolArguments=*/1);
3754     break;
3755   }
3756
3757   case OO_AmpAmp:
3758   case OO_PipePipe: {
3759     // C++ [over.operator]p23:
3760     //
3761     //   There also exist candidate operator functions of the form
3762     //
3763     //        bool        operator!(bool);            [ABOVE]
3764     //        bool        operator&&(bool, bool);
3765     //        bool        operator||(bool, bool);
3766     QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3767     AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3768                         /*IsAssignmentOperator=*/false,
3769                         /*NumContextualBoolArguments=*/2);
3770     break;
3771   }
3772
3773   case OO_Subscript:
3774     // C++ [over.built]p13:
3775     //
3776     //   For every cv-qualified or cv-unqualified object type T there
3777     //   exist candidate operator functions of the form
3778     //
3779     //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3780     //        T&         operator[](T*, ptrdiff_t);
3781     //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3782     //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3783     //        T&         operator[](ptrdiff_t, T*);
3784     for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3785          Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3786       QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3787       QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
3788       QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3789
3790       // T& operator[](T*, ptrdiff_t)
3791       AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3792
3793       // T& operator[](ptrdiff_t, T*);
3794       ParamTypes[0] = ParamTypes[1];
3795       ParamTypes[1] = *Ptr;
3796       AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3797     }
3798     break;
3799
3800   case OO_ArrowStar:
3801     // C++ [over.built]p11:
3802     //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 
3803     //    C1 is the same type as C2 or is a derived class of C2, T is an object 
3804     //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 
3805     //    there exist candidate operator functions of the form 
3806     //    CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 
3807     //    where CV12 is the union of CV1 and CV2.
3808     {
3809       for (BuiltinCandidateTypeSet::iterator Ptr = 
3810              CandidateTypes.pointer_begin();
3811            Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3812         QualType C1Ty = (*Ptr);
3813         QualType C1;
3814         QualifierCollector Q1;
3815         if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
3816           C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
3817           if (!isa<RecordType>(C1))
3818             continue;
3819           // heuristic to reduce number of builtin candidates in the set.
3820           // Add volatile/restrict version only if there are conversions to a
3821           // volatile/restrict type.
3822           if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3823             continue;
3824           if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3825             continue;
3826         }
3827         for (BuiltinCandidateTypeSet::iterator
3828              MemPtr = CandidateTypes.member_pointer_begin(),
3829              MemPtrEnd = CandidateTypes.member_pointer_end();
3830              MemPtr != MemPtrEnd; ++MemPtr) {
3831           const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3832           QualType C2 = QualType(mptr->getClass(), 0);
3833           C2 = C2.getUnqualifiedType();
3834           if (C1 != C2 && !IsDerivedFrom(C1, C2))
3835             break;
3836           QualType ParamTypes[2] = { *Ptr, *MemPtr };
3837           // build CV12 T&
3838           QualType T = mptr->getPointeeType();
3839           if (!VisibleTypeConversionsQuals.hasVolatile() && 
3840               T.isVolatileQualified())
3841             continue;
3842           if (!VisibleTypeConversionsQuals.hasRestrict() && 
3843               T.isRestrictQualified())
3844             continue;
3845           T = Q1.apply(T);
3846           QualType ResultTy = Context.getLValueReferenceType(T);
3847           AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3848         }
3849       }
3850     }
3851     break;
3852
3853   case OO_Conditional:
3854     // Note that we don't consider the first argument, since it has been
3855     // contextually converted to bool long ago. The candidates below are
3856     // therefore added as binary.
3857     //
3858     // C++ [over.built]p24:
3859     //   For every type T, where T is a pointer or pointer-to-member type,
3860     //   there exist candidate operator functions of the form
3861     //
3862     //        T        operator?(bool, T, T);
3863     //
3864     for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3865          E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3866       QualType ParamTypes[2] = { *Ptr, *Ptr };
3867       AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3868     }
3869     for (BuiltinCandidateTypeSet::iterator Ptr =
3870            CandidateTypes.member_pointer_begin(),
3871          E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3872       QualType ParamTypes[2] = { *Ptr, *Ptr };
3873       AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3874     }
3875     goto Conditional;
3876   }
3877 }
3878
3879 /// \brief Add function candidates found via argument-dependent lookup
3880 /// to the set of overloading candidates.
3881 ///
3882 /// This routine performs argument-dependent name lookup based on the
3883 /// given function name (which may also be an operator name) and adds
3884 /// all of the overload candidates found by ADL to the overload
3885 /// candidate set (C++ [basic.lookup.argdep]).
3886 void
3887 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3888                                            Expr **Args, unsigned NumArgs,
3889                                            bool HasExplicitTemplateArgs,
3890                             const TemplateArgumentLoc *ExplicitTemplateArgs,
3891                                            unsigned NumExplicitTemplateArgs,                                            
3892                                            OverloadCandidateSet& CandidateSet,
3893                                            bool PartialOverloading) {
3894   FunctionSet Functions;
3895
3896   // FIXME: Should we be trafficking in canonical function decls throughout?
3897   
3898   // Record all of the function candidates that we've already
3899   // added to the overload set, so that we don't add those same
3900   // candidates a second time.
3901   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3902                                    CandEnd = CandidateSet.end();
3903        Cand != CandEnd; ++Cand)
3904     if (Cand->Function) {
3905       Functions.insert(Cand->Function);
3906       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3907         Functions.insert(FunTmpl);
3908     }
3909
3910   // FIXME: Pass in the explicit template arguments?
3911   ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
3912
3913   // Erase all of the candidates we already knew about.
3914   // FIXME: This is suboptimal. Is there a better way?
3915   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3916                                    CandEnd = CandidateSet.end();
3917        Cand != CandEnd; ++Cand)
3918     if (Cand->Function) {
3919       Functions.erase(Cand->Function);
3920       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3921         Functions.erase(FunTmpl);
3922     }
3923
3924   // For each of the ADL candidates we found, add it to the overload
3925   // set.
3926   for (FunctionSet::iterator Func = Functions.begin(),
3927                           FuncEnd = Functions.end();
3928        Func != FuncEnd; ++Func) {
3929     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3930       if (HasExplicitTemplateArgs)
3931         continue;
3932       
3933       AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3934                            false, false, PartialOverloading);
3935     } else
3936       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3937                                    HasExplicitTemplateArgs,
3938                                    ExplicitTemplateArgs,
3939                                    NumExplicitTemplateArgs,
3940                                    Args, NumArgs, CandidateSet);
3941   }
3942 }
3943
3944 /// isBetterOverloadCandidate - Determines whether the first overload
3945 /// candidate is a better candidate than the second (C++ 13.3.3p1).
3946 bool
3947 Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3948                                 const OverloadCandidate& Cand2) {
3949   // Define viable functions to be better candidates than non-viable
3950   // functions.
3951   if (!Cand2.Viable)
3952     return Cand1.Viable;
3953   else if (!Cand1.Viable)
3954     return false;
3955
3956   // C++ [over.match.best]p1:
3957   //
3958   //   -- if F is a static member function, ICS1(F) is defined such
3959   //      that ICS1(F) is neither better nor worse than ICS1(G) for
3960   //      any function G, and, symmetrically, ICS1(G) is neither
3961   //      better nor worse than ICS1(F).
3962   unsigned StartArg = 0;
3963   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3964     StartArg = 1;
3965
3966   // C++ [over.match.best]p1:
3967   //   A viable function F1 is defined to be a better function than another
3968   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
3969   //   conversion sequence than ICSi(F2), and then...
3970   unsigned NumArgs = Cand1.Conversions.size();
3971   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3972   bool HasBetterConversion = false;
3973   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3974     switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3975                                                Cand2.Conversions[ArgIdx])) {
3976     case ImplicitConversionSequence::Better:
3977       // Cand1 has a better conversion sequence.
3978       HasBetterConversion = true;
3979       break;
3980
3981     case ImplicitConversionSequence::Worse:
3982       // Cand1 can't be better than Cand2.
3983       return false;
3984
3985     case ImplicitConversionSequence::Indistinguishable:
3986       // Do nothing.
3987       break;
3988     }
3989   }
3990
3991   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
3992   //       ICSj(F2), or, if not that,
3993   if (HasBetterConversion)
3994     return true;
3995
3996   //     - F1 is a non-template function and F2 is a function template
3997   //       specialization, or, if not that,
3998   if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3999       Cand2.Function && Cand2.Function->getPrimaryTemplate())
4000     return true;
4001
4002   //   -- F1 and F2 are function template specializations, and the function
4003   //      template for F1 is more specialized than the template for F2
4004   //      according to the partial ordering rules described in 14.5.5.2, or,
4005   //      if not that,
4006   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4007       Cand2.Function && Cand2.Function->getPrimaryTemplate())
4008     if (FunctionTemplateDecl *BetterTemplate
4009           = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4010                                        Cand2.Function->getPrimaryTemplate(),
4011                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 
4012                                                              : TPOC_Call))
4013       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4014
4015   //   -- the context is an initialization by user-defined conversion
4016   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
4017   //      from the return type of F1 to the destination type (i.e.,
4018   //      the type of the entity being initialized) is a better
4019   //      conversion sequence than the standard conversion sequence
4020   //      from the return type of F2 to the destination type.
4021   if (Cand1.Function && Cand2.Function &&
4022       isa<CXXConversionDecl>(Cand1.Function) &&
4023       isa<CXXConversionDecl>(Cand2.Function)) {
4024     switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4025                                                Cand2.FinalConversion)) {
4026     case ImplicitConversionSequence::Better:
4027       // Cand1 has a better conversion sequence.
4028       return true;
4029
4030     case ImplicitConversionSequence::Worse:
4031       // Cand1 can't be better than Cand2.
4032       return false;
4033
4034     case ImplicitConversionSequence::Indistinguishable:
4035       // Do nothing
4036       break;
4037     }
4038   }
4039
4040   return false;
4041 }
4042
4043 /// \brief Computes the best viable function (C++ 13.3.3)
4044 /// within an overload candidate set.
4045 ///
4046 /// \param CandidateSet the set of candidate functions.
4047 ///
4048 /// \param Loc the location of the function name (or operator symbol) for
4049 /// which overload resolution occurs.
4050 ///
4051 /// \param Best f overload resolution was successful or found a deleted
4052 /// function, Best points to the candidate function found.
4053 ///
4054 /// \returns The result of overload resolution.
4055 Sema::OverloadingResult
4056 Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4057                          SourceLocation Loc,
4058                          OverloadCandidateSet::iterator& Best) {
4059   // Find the best viable function.
4060   Best = CandidateSet.end();
4061   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4062        Cand != CandidateSet.end(); ++Cand) {
4063     if (Cand->Viable) {
4064       if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4065         Best = Cand;
4066     }
4067   }
4068
4069   // If we didn't find any viable functions, abort.
4070   if (Best == CandidateSet.end())
4071     return OR_No_Viable_Function;
4072
4073   // Make sure that this function is better than every other viable
4074   // function. If not, we have an ambiguity.
4075   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4076        Cand != CandidateSet.end(); ++Cand) {
4077     if (Cand->Viable &&
4078         Cand != Best &&
4079         !isBetterOverloadCandidate(*Best, *Cand)) {
4080       Best = CandidateSet.end();
4081       return OR_Ambiguous;
4082     }
4083   }
4084
4085   // Best is the best viable function.
4086   if (Best->Function &&
4087       (Best->Function->isDeleted() ||
4088        Best->Function->getAttr<UnavailableAttr>()))
4089     return OR_Deleted;
4090
4091   // C++ [basic.def.odr]p2:
4092   //   An overloaded function is used if it is selected by overload resolution
4093   //   when referred to from a potentially-evaluated expression. [Note: this
4094   //   covers calls to named functions (5.2.2), operator overloading
4095   //   (clause 13), user-defined conversions (12.3.2), allocation function for
4096   //   placement new (5.3.4), as well as non-default initialization (8.5).
4097   if (Best->Function)
4098     MarkDeclarationReferenced(Loc, Best->Function);
4099   return OR_Success;
4100 }
4101
4102 /// PrintOverloadCandidates - When overload resolution fails, prints
4103 /// diagnostic messages containing the candidates in the candidate
4104 /// set. If OnlyViable is true, only viable candidates will be printed.
4105 void
4106 Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
4107                               bool OnlyViable,
4108                               const char *Opc,
4109                               SourceLocation OpLoc) {
4110   OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4111                              LastCand = CandidateSet.end();
4112   bool Reported = false;
4113   for (; Cand != LastCand; ++Cand) {
4114     if (Cand->Viable || !OnlyViable) {
4115       if (Cand->Function) {
4116         if (Cand->Function->isDeleted() ||
4117             Cand->Function->getAttr<UnavailableAttr>()) {
4118           // Deleted or "unavailable" function.
4119           Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4120             << Cand->Function->isDeleted();
4121         } else if (FunctionTemplateDecl *FunTmpl 
4122                      = Cand->Function->getPrimaryTemplate()) {
4123           // Function template specialization
4124           // FIXME: Give a better reason!
4125           Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4126             << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4127                               *Cand->Function->getTemplateSpecializationArgs());
4128         } else {
4129           // Normal function
4130           bool errReported = false;
4131           if (!Cand->Viable && Cand->Conversions.size() > 0) {
4132             for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4133               const ImplicitConversionSequence &Conversion = 
4134                                                         Cand->Conversions[i];
4135               if ((Conversion.ConversionKind != 
4136                    ImplicitConversionSequence::BadConversion) ||
4137                   Conversion.ConversionFunctionSet.size() == 0)
4138                 continue;
4139               Diag(Cand->Function->getLocation(), 
4140                    diag::err_ovl_candidate_not_viable) << (i+1);
4141               errReported = true;
4142               for (int j = Conversion.ConversionFunctionSet.size()-1; 
4143                    j >= 0; j--) {
4144                 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4145                 Diag(Func->getLocation(), diag::err_ovl_candidate);
4146               }
4147             }
4148           }
4149           if (!errReported)
4150             Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
4151         }
4152       } else if (Cand->IsSurrogate) {
4153         // Desugar the type of the surrogate down to a function type,
4154         // retaining as many typedefs as possible while still showing
4155         // the function type (and, therefore, its parameter types).
4156         QualType FnType = Cand->Surrogate->getConversionType();
4157         bool isLValueReference = false;
4158         bool isRValueReference = false;
4159         bool isPointer = false;
4160         if (const LValueReferenceType *FnTypeRef =
4161               FnType->getAs<LValueReferenceType>()) {
4162           FnType = FnTypeRef->getPointeeType();
4163           isLValueReference = true;
4164         } else if (const RValueReferenceType *FnTypeRef =
4165                      FnType->getAs<RValueReferenceType>()) {
4166           FnType = FnTypeRef->getPointeeType();
4167           isRValueReference = true;
4168         }
4169         if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4170           FnType = FnTypePtr->getPointeeType();
4171           isPointer = true;
4172         }
4173         // Desugar down to a function type.
4174         FnType = QualType(FnType->getAs<FunctionType>(), 0);
4175         // Reconstruct the pointer/reference as appropriate.
4176         if (isPointer) FnType = Context.getPointerType(FnType);
4177         if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4178         if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
4179
4180         Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
4181           << FnType;
4182       } else if (OnlyViable) {
4183         assert(Cand->Conversions.size() <= 2 && 
4184                "builtin-binary-operator-not-binary");
4185         std::string TypeStr("operator");
4186         TypeStr += Opc;
4187         TypeStr += "(";
4188         TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4189         if (Cand->Conversions.size() == 1) {
4190           TypeStr += ")";
4191           Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4192         }
4193         else {
4194           TypeStr += ", ";
4195           TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4196           TypeStr += ")";
4197           Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4198         }
4199       }
4200       else if (!Cand->Viable && !Reported) {
4201         // Non-viability might be due to ambiguous user-defined conversions,
4202         // needed for built-in operators. Report them as well, but only once
4203         // as we have typically many built-in candidates.
4204         unsigned NoOperands = Cand->Conversions.size();
4205         for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4206           const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4207           if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4208               ICS.ConversionFunctionSet.empty())
4209             continue;
4210           if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4211                          Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4212             QualType FromTy = 
4213               QualType(
4214                      static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4215             Diag(OpLoc,diag::note_ambiguous_type_conversion)
4216                   << FromTy << Func->getConversionType();
4217           }
4218           for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4219             FunctionDecl *Func = 
4220               Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4221             Diag(Func->getLocation(),diag::err_ovl_candidate);
4222           }
4223         }
4224         Reported = true;
4225       }
4226     }
4227   }
4228 }
4229
4230 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4231 /// an overloaded function (C++ [over.over]), where @p From is an
4232 /// expression with overloaded function type and @p ToType is the type
4233 /// we're trying to resolve to. For example:
4234 ///
4235 /// @code
4236 /// int f(double);
4237 /// int f(int);
4238 ///
4239 /// int (*pfd)(double) = f; // selects f(double)
4240 /// @endcode
4241 ///
4242 /// This routine returns the resulting FunctionDecl if it could be
4243 /// resolved, and NULL otherwise. When @p Complain is true, this
4244 /// routine will emit diagnostics if there is an error.
4245 FunctionDecl *
4246 Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
4247                                          bool Complain) {
4248   QualType FunctionType = ToType;
4249   bool IsMember = false;
4250   if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
4251     FunctionType = ToTypePtr->getPointeeType();
4252   else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
4253     FunctionType = ToTypeRef->getPointeeType();
4254   else if (const MemberPointerType *MemTypePtr =
4255                     ToType->getAs<MemberPointerType>()) {
4256     FunctionType = MemTypePtr->getPointeeType();
4257     IsMember = true;
4258   }
4259
4260   // We only look at pointers or references to functions.
4261   FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
4262   if (!FunctionType->isFunctionType())
4263     return 0;
4264
4265   // Find the actual overloaded function declaration.
4266   OverloadedFunctionDecl *Ovl = 0;
4267
4268   // C++ [over.over]p1:
4269   //   [...] [Note: any redundant set of parentheses surrounding the
4270   //   overloaded function name is ignored (5.1). ]
4271   Expr *OvlExpr = From->IgnoreParens();
4272
4273   // C++ [over.over]p1:
4274   //   [...] The overloaded function name can be preceded by the &
4275   //   operator.
4276   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4277     if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4278       OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4279   }
4280
4281   bool HasExplicitTemplateArgs = false;
4282   const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
4283   unsigned NumExplicitTemplateArgs = 0;
4284   
4285   // Try to dig out the overloaded function.
4286   FunctionTemplateDecl *FunctionTemplate = 0;
4287   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
4288     Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
4289     FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4290     HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4291     ExplicitTemplateArgs = DR->getTemplateArgs();
4292     NumExplicitTemplateArgs = DR->getNumTemplateArgs();
4293   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4294     Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4295     FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
4296     HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4297     ExplicitTemplateArgs = ME->getTemplateArgs();
4298     NumExplicitTemplateArgs = ME->getNumTemplateArgs();
4299   } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4300     TemplateName Name = TIRE->getTemplateName();
4301     Ovl = Name.getAsOverloadedFunctionDecl();
4302     FunctionTemplate = 
4303       dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4304     
4305     HasExplicitTemplateArgs = true;
4306     ExplicitTemplateArgs = TIRE->getTemplateArgs();
4307     NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
4308   }
4309   
4310   // If there's no overloaded function declaration or function template,
4311   // we're done.
4312   if (!Ovl && !FunctionTemplate)
4313     return 0;
4314
4315   OverloadIterator Fun;
4316   if (Ovl)
4317     Fun = Ovl;
4318   else
4319     Fun = FunctionTemplate;
4320
4321   // Look through all of the overloaded functions, searching for one
4322   // whose type matches exactly.
4323   llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
4324   bool FoundNonTemplateFunction = false;
4325   for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
4326     // C++ [over.over]p3:
4327     //   Non-member functions and static member functions match
4328     //   targets of type "pointer-to-function" or "reference-to-function."
4329     //   Nonstatic member functions match targets of
4330     //   type "pointer-to-member-function."
4331     // Note that according to DR 247, the containing class does not matter.
4332
4333     if (FunctionTemplateDecl *FunctionTemplate
4334           = dyn_cast<FunctionTemplateDecl>(*Fun)) {
4335       if (CXXMethodDecl *Method
4336             = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
4337         // Skip non-static function templates when converting to pointer, and
4338         // static when converting to member pointer.
4339         if (Method->isStatic() == IsMember)
4340           continue;
4341       } else if (IsMember)
4342         continue;
4343
4344       // C++ [over.over]p2:
4345       //   If the name is a function template, template argument deduction is
4346       //   done (14.8.2.2), and if the argument deduction succeeds, the
4347       //   resulting template argument list is used to generate a single
4348       //   function template specialization, which is added to the set of
4349       //   overloaded functions considered.
4350       // FIXME: We don't really want to build the specialization here, do we?
4351       FunctionDecl *Specialization = 0;
4352       TemplateDeductionInfo Info(Context);
4353       if (TemplateDeductionResult Result
4354             = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4355                                       ExplicitTemplateArgs,
4356                                       NumExplicitTemplateArgs,
4357                                       FunctionType, Specialization, Info)) {
4358         // FIXME: make a note of the failed deduction for diagnostics.
4359         (void)Result;
4360       } else {
4361         // FIXME: If the match isn't exact, shouldn't we just drop this as
4362         // a candidate? Find a testcase before changing the code.
4363         assert(FunctionType
4364                  == Context.getCanonicalType(Specialization->getType()));
4365         Matches.insert(
4366                 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
4367       }
4368     }
4369
4370     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4371       // Skip non-static functions when converting to pointer, and static
4372       // when converting to member pointer.
4373       if (Method->isStatic() == IsMember)
4374         continue;
4375       
4376       // If we have explicit template arguments, skip non-templates.
4377       if (HasExplicitTemplateArgs)
4378         continue;
4379     } else if (IsMember)
4380       continue;
4381
4382     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
4383       if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
4384         Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
4385         FoundNonTemplateFunction = true;
4386       }
4387     }
4388   }
4389
4390   // If there were 0 or 1 matches, we're done.
4391   if (Matches.empty())
4392     return 0;
4393   else if (Matches.size() == 1) {
4394     FunctionDecl *Result = *Matches.begin();
4395     MarkDeclarationReferenced(From->getLocStart(), Result);
4396     return Result;
4397   }
4398
4399   // C++ [over.over]p4:
4400   //   If more than one function is selected, [...]
4401   typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
4402   if (!FoundNonTemplateFunction) {
4403     //   [...] and any given function template specialization F1 is
4404     //   eliminated if the set contains a second function template
4405     //   specialization whose function template is more specialized
4406     //   than the function template of F1 according to the partial
4407     //   ordering rules of 14.5.5.2.
4408
4409     // The algorithm specified above is quadratic. We instead use a
4410     // two-pass algorithm (similar to the one used to identify the
4411     // best viable function in an overload set) that identifies the
4412     // best function template (if it exists).
4413     llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4414                                                          Matches.end());
4415     FunctionDecl *Result =
4416         getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4417                            TPOC_Other, From->getLocStart(),
4418                            PDiag(),
4419                            PDiag(diag::err_addr_ovl_ambiguous)
4420                                << TemplateMatches[0]->getDeclName(),
4421                            PDiag(diag::err_ovl_template_candidate));
4422     MarkDeclarationReferenced(From->getLocStart(), Result);
4423     return Result;
4424   }
4425
4426   //   [...] any function template specializations in the set are
4427   //   eliminated if the set also contains a non-template function, [...]
4428   llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4429   for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4430     if ((*M)->getPrimaryTemplate() == 0)
4431       RemainingMatches.push_back(*M);
4432   
4433   // [...] After such eliminations, if any, there shall remain exactly one
4434   // selected function.
4435   if (RemainingMatches.size() == 1) {
4436     FunctionDecl *Result = RemainingMatches.front();
4437     MarkDeclarationReferenced(From->getLocStart(), Result);
4438     return Result;
4439   }
4440
4441   // FIXME: We should probably return the same thing that BestViableFunction
4442   // returns (even if we issue the diagnostics here).
4443   Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4444     << RemainingMatches[0]->getDeclName();
4445   for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4446     Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
4447   return 0;
4448 }
4449
4450 /// \brief Add a single candidate to the overload set.
4451 static void AddOverloadedCallCandidate(Sema &S,
4452                                        AnyFunctionDecl Callee,
4453                                        bool &ArgumentDependentLookup,
4454                                        bool HasExplicitTemplateArgs,
4455                              const TemplateArgumentLoc *ExplicitTemplateArgs,
4456                                        unsigned NumExplicitTemplateArgs,
4457                                        Expr **Args, unsigned NumArgs,
4458                                        OverloadCandidateSet &CandidateSet,
4459                                        bool PartialOverloading) {
4460   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4461     assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4462     S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4463                            PartialOverloading);
4464   
4465     if (Func->getDeclContext()->isRecord() ||
4466         Func->getDeclContext()->isFunctionOrMethod())
4467       ArgumentDependentLookup = false;
4468     return;
4469   }  
4470   
4471   FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4472   S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4473                                  ExplicitTemplateArgs,
4474                                  NumExplicitTemplateArgs,
4475                                  Args, NumArgs, CandidateSet);
4476   
4477   if (FuncTemplate->getDeclContext()->isRecord())
4478     ArgumentDependentLookup = false;
4479 }
4480   
4481 /// \brief Add the overload candidates named by callee and/or found by argument
4482 /// dependent lookup to the given overload set.
4483 void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4484                                        DeclarationName &UnqualifiedName,
4485                                        bool &ArgumentDependentLookup,
4486                                        bool HasExplicitTemplateArgs,
4487                              const TemplateArgumentLoc *ExplicitTemplateArgs,
4488                                        unsigned NumExplicitTemplateArgs,
4489                                        Expr **Args, unsigned NumArgs,
4490                                        OverloadCandidateSet &CandidateSet,
4491                                        bool PartialOverloading) {
4492   // Add the functions denoted by Callee to the set of candidate
4493   // functions. While we're doing so, track whether argument-dependent
4494   // lookup still applies, per:
4495   //
4496   // C++0x [basic.lookup.argdep]p3:
4497   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
4498   //   and let Y be the lookup set produced by argument dependent
4499   //   lookup (defined as follows). If X contains
4500   //
4501   //     -- a declaration of a class member, or
4502   //
4503   //     -- a block-scope function declaration that is not a
4504   //        using-declaration (FIXME: check for using declaration), or
4505   //
4506   //     -- a declaration that is neither a function or a function
4507   //        template
4508   //
4509   //   then Y is empty.
4510   if (!Callee) {
4511     // Nothing to do.
4512   } else if (OverloadedFunctionDecl *Ovl
4513                = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4514     for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4515                                                 FuncEnd = Ovl->function_end();
4516          Func != FuncEnd; ++Func)
4517       AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4518                                  HasExplicitTemplateArgs,
4519                                  ExplicitTemplateArgs, NumExplicitTemplateArgs,
4520                                  Args, NumArgs, CandidateSet, 
4521                                  PartialOverloading);
4522   } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4523     AddOverloadedCallCandidate(*this, 
4524                                AnyFunctionDecl::getFromNamedDecl(Callee),
4525                                ArgumentDependentLookup,
4526                                HasExplicitTemplateArgs,
4527                                ExplicitTemplateArgs, NumExplicitTemplateArgs,
4528                                Args, NumArgs, CandidateSet,
4529                                PartialOverloading);
4530   // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4531   // checking dynamically.
4532   
4533   if (Callee)
4534     UnqualifiedName = Callee->getDeclName();
4535   
4536   if (ArgumentDependentLookup)
4537     AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4538                                          HasExplicitTemplateArgs,
4539                                          ExplicitTemplateArgs,
4540                                          NumExplicitTemplateArgs,
4541                                          CandidateSet,
4542                                          PartialOverloading);  
4543 }
4544   
4545 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
4546 /// (which eventually refers to the declaration Func) and the call
4547 /// arguments Args/NumArgs, attempt to resolve the function call down
4548 /// to a specific function. If overload resolution succeeds, returns
4549 /// the function declaration produced by overload
4550 /// resolution. Otherwise, emits diagnostics, deletes all of the
4551 /// arguments and Fn, and returns NULL.
4552 FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
4553                                             DeclarationName UnqualifiedName,
4554                                             bool HasExplicitTemplateArgs,
4555                              const TemplateArgumentLoc *ExplicitTemplateArgs,
4556                                             unsigned NumExplicitTemplateArgs,
4557                                             SourceLocation LParenLoc,
4558                                             Expr **Args, unsigned NumArgs,
4559                                             SourceLocation *CommaLocs,
4560                                             SourceLocation RParenLoc,
4561                                             bool &ArgumentDependentLookup) {
4562   OverloadCandidateSet CandidateSet;
4563
4564   // Add the functions denoted by Callee to the set of candidate
4565   // functions. 
4566   AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4567                               HasExplicitTemplateArgs, ExplicitTemplateArgs,
4568                               NumExplicitTemplateArgs, Args, NumArgs, 
4569                               CandidateSet);
4570   OverloadCandidateSet::iterator Best;
4571   switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
4572   case OR_Success:
4573     return Best->Function;
4574
4575   case OR_No_Viable_Function:
4576     Diag(Fn->getSourceRange().getBegin(),
4577          diag::err_ovl_no_viable_function_in_call)
4578       << UnqualifiedName << Fn->getSourceRange();
4579     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4580     break;
4581
4582   case OR_Ambiguous:
4583     Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
4584       << UnqualifiedName << Fn->getSourceRange();
4585     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4586     break;
4587
4588   case OR_Deleted:
4589     Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4590       << Best->Function->isDeleted()
4591       << UnqualifiedName
4592       << Fn->getSourceRange();
4593     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4594     break;
4595   }
4596
4597   // Overload resolution failed. Destroy all of the subexpressions and
4598   // return NULL.
4599   Fn->Destroy(Context);
4600   for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4601     Args[Arg]->Destroy(Context);
4602   return 0;
4603 }
4604
4605 /// \brief Create a unary operation that may resolve to an overloaded
4606 /// operator.
4607 ///
4608 /// \param OpLoc The location of the operator itself (e.g., '*').
4609 ///
4610 /// \param OpcIn The UnaryOperator::Opcode that describes this
4611 /// operator.
4612 ///
4613 /// \param Functions The set of non-member functions that will be
4614 /// considered by overload resolution. The caller needs to build this
4615 /// set based on the context using, e.g.,
4616 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4617 /// set should not contain any member functions; those will be added
4618 /// by CreateOverloadedUnaryOp().
4619 ///
4620 /// \param input The input argument.
4621 Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4622                                                      unsigned OpcIn,
4623                                                      FunctionSet &Functions,
4624                                                      ExprArg input) {
4625   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4626   Expr *Input = (Expr *)input.get();
4627
4628   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4629   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4630   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4631
4632   Expr *Args[2] = { Input, 0 };
4633   unsigned NumArgs = 1;
4634
4635   // For post-increment and post-decrement, add the implicit '0' as
4636   // the second argument, so that we know this is a post-increment or
4637   // post-decrement.
4638   if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4639     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4640     Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4641                                            SourceLocation());
4642     NumArgs = 2;
4643   }
4644
4645   if (Input->isTypeDependent()) {
4646     OverloadedFunctionDecl *Overloads
4647       = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4648     for (FunctionSet::iterator Func = Functions.begin(),
4649                             FuncEnd = Functions.end();
4650          Func != FuncEnd; ++Func)
4651       Overloads->addOverload(*Func);
4652
4653     DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4654                                                 OpLoc, false, false);
4655
4656     input.release();
4657     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4658                                                    &Args[0], NumArgs,
4659                                                    Context.DependentTy,
4660                                                    OpLoc));
4661   }
4662
4663   // Build an empty overload set.
4664   OverloadCandidateSet CandidateSet;
4665
4666   // Add the candidates from the given function set.
4667   AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4668
4669   // Add operator candidates that are member functions.
4670   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4671
4672   // Add builtin operator candidates.
4673   AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4674
4675   // Perform overload resolution.
4676   OverloadCandidateSet::iterator Best;
4677   switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4678   case OR_Success: {
4679     // We found a built-in operator or an overloaded operator.
4680     FunctionDecl *FnDecl = Best->Function;
4681
4682     if (FnDecl) {
4683       // We matched an overloaded operator. Build a call to that
4684       // operator.
4685
4686       // Convert the arguments.
4687       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4688         if (PerformObjectArgumentInitialization(Input, Method))
4689           return ExprError();
4690       } else {
4691         // Convert the arguments.
4692         if (PerformCopyInitialization(Input,
4693                                       FnDecl->getParamDecl(0)->getType(),
4694                                       "passing"))
4695           return ExprError();
4696       }
4697
4698       // Determine the result type
4699       QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
4700
4701       // Build the actual expression node.
4702       Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4703                                                SourceLocation());
4704       UsualUnaryConversions(FnExpr);
4705
4706       input.release();
4707
4708       ExprOwningPtr<CallExpr> TheCall(this,
4709         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4710                                           &Input, 1, ResultTy, OpLoc));
4711       
4712       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 
4713                               FnDecl))
4714         return ExprError();
4715
4716       return MaybeBindToTemporary(TheCall.release());
4717     } else {
4718       // We matched a built-in operator. Convert the arguments, then
4719       // break out so that we will build the appropriate built-in
4720       // operator node.
4721         if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4722                                       Best->Conversions[0], "passing"))
4723           return ExprError();
4724
4725         break;
4726       }
4727     }
4728
4729     case OR_No_Viable_Function:
4730       // No viable function; fall through to handling this as a
4731       // built-in operator, which will produce an error message for us.
4732       break;
4733
4734     case OR_Ambiguous:
4735       Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4736           << UnaryOperator::getOpcodeStr(Opc)
4737           << Input->getSourceRange();
4738       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true, 
4739                               UnaryOperator::getOpcodeStr(Opc), OpLoc);
4740       return ExprError();
4741
4742     case OR_Deleted:
4743       Diag(OpLoc, diag::err_ovl_deleted_oper)
4744         << Best->Function->isDeleted()
4745         << UnaryOperator::getOpcodeStr(Opc)
4746         << Input->getSourceRange();
4747       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4748       return ExprError();
4749     }
4750
4751   // Either we found no viable overloaded operator or we matched a
4752   // built-in operator. In either case, fall through to trying to
4753   // build a built-in operation.
4754   input.release();
4755   return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4756 }
4757
4758 /// \brief Create a binary operation that may resolve to an overloaded
4759 /// operator.
4760 ///
4761 /// \param OpLoc The location of the operator itself (e.g., '+').
4762 ///
4763 /// \param OpcIn The BinaryOperator::Opcode that describes this
4764 /// operator.
4765 ///
4766 /// \param Functions The set of non-member functions that will be
4767 /// considered by overload resolution. The caller needs to build this
4768 /// set based on the context using, e.g.,
4769 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4770 /// set should not contain any member functions; those will be added
4771 /// by CreateOverloadedBinOp().
4772 ///
4773 /// \param LHS Left-hand argument.
4774 /// \param RHS Right-hand argument.
4775 Sema::OwningExprResult
4776 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4777                             unsigned OpcIn,
4778                             FunctionSet &Functions,
4779                             Expr *LHS, Expr *RHS) {
4780   Expr *Args[2] = { LHS, RHS };
4781   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
4782
4783   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4784   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4785   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4786
4787   // If either side is type-dependent, create an appropriate dependent
4788   // expression.
4789   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4790     // .* cannot be overloaded.
4791     if (Opc == BinaryOperator::PtrMemD)
4792       return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4793                                                 Context.DependentTy, OpLoc));
4794
4795     OverloadedFunctionDecl *Overloads
4796       = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4797     for (FunctionSet::iterator Func = Functions.begin(),
4798                             FuncEnd = Functions.end();
4799          Func != FuncEnd; ++Func)
4800       Overloads->addOverload(*Func);
4801
4802     DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4803                                                 OpLoc, false, false);
4804
4805     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4806                                                    Args, 2,
4807                                                    Context.DependentTy,
4808                                                    OpLoc));
4809   }
4810
4811   // If this is the .* operator, which is not overloadable, just
4812   // create a built-in binary operator.
4813   if (Opc == BinaryOperator::PtrMemD)
4814     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4815
4816   // If this is one of the assignment operators, we only perform
4817   // overload resolution if the left-hand side is a class or
4818   // enumeration type (C++ [expr.ass]p3).
4819   if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4820       !Args[0]->getType()->isOverloadableType())
4821     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4822
4823   // Build an empty overload set.
4824   OverloadCandidateSet CandidateSet;
4825
4826   // Add the candidates from the given function set.
4827   AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4828
4829   // Add operator candidates that are member functions.
4830   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4831
4832   // Add builtin operator candidates.
4833   AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4834
4835   // Perform overload resolution.
4836   OverloadCandidateSet::iterator Best;
4837   switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4838     case OR_Success: {
4839       // We found a built-in operator or an overloaded operator.
4840       FunctionDecl *FnDecl = Best->Function;
4841
4842       if (FnDecl) {
4843         // We matched an overloaded operator. Build a call to that
4844         // operator.
4845
4846         // Convert the arguments.
4847         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4848           if (PerformObjectArgumentInitialization(Args[0], Method) ||
4849               PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
4850                                         "passing"))
4851             return ExprError();
4852         } else {
4853           // Convert the arguments.
4854           if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
4855                                         "passing") ||
4856               PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
4857                                         "passing"))
4858             return ExprError();
4859         }
4860
4861         // Determine the result type
4862         QualType ResultTy
4863           = FnDecl->getType()->getAs<FunctionType>()->getResultType();
4864         ResultTy = ResultTy.getNonReferenceType();
4865
4866         // Build the actual expression node.
4867         Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4868                                                  OpLoc);
4869         UsualUnaryConversions(FnExpr);
4870
4871         ExprOwningPtr<CXXOperatorCallExpr> 
4872           TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4873                                                           Args, 2, ResultTy, 
4874                                                           OpLoc));
4875         
4876         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 
4877                                 FnDecl))
4878           return ExprError();
4879
4880         return MaybeBindToTemporary(TheCall.release());
4881       } else {
4882         // We matched a built-in operator. Convert the arguments, then
4883         // break out so that we will build the appropriate built-in
4884         // operator node.
4885         if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
4886                                       Best->Conversions[0], "passing") ||
4887             PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
4888                                       Best->Conversions[1], "passing"))
4889           return ExprError();
4890
4891         break;
4892       }
4893     }
4894
4895     case OR_No_Viable_Function: {
4896       // C++ [over.match.oper]p9:
4897       //   If the operator is the operator , [...] and there are no
4898       //   viable functions, then the operator is assumed to be the
4899       //   built-in operator and interpreted according to clause 5.
4900       if (Opc == BinaryOperator::Comma)
4901         break;
4902
4903       // For class as left operand for assignment or compound assigment operator
4904       // do not fall through to handling in built-in, but report that no overloaded
4905       // assignment operator found
4906       OwningExprResult Result = ExprError();
4907       if (Args[0]->getType()->isRecordType() && 
4908           Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4909         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
4910              << BinaryOperator::getOpcodeStr(Opc)
4911              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4912       } else {
4913         // No viable function; try to create a built-in operation, which will
4914         // produce an error. Then, show the non-viable candidates.
4915         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4916       }
4917       assert(Result.isInvalid() && 
4918              "C++ binary operator overloading is missing candidates!");
4919       if (Result.isInvalid())
4920         PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false, 
4921                                 BinaryOperator::getOpcodeStr(Opc), OpLoc);
4922       return move(Result);
4923     }
4924
4925     case OR_Ambiguous:
4926       Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4927           << BinaryOperator::getOpcodeStr(Opc)
4928           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4929       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true, 
4930                               BinaryOperator::getOpcodeStr(Opc), OpLoc);
4931       return ExprError();
4932
4933     case OR_Deleted:
4934       Diag(OpLoc, diag::err_ovl_deleted_oper)
4935         << Best->Function->isDeleted()
4936         << BinaryOperator::getOpcodeStr(Opc)
4937         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4938       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4939       return ExprError();
4940     }
4941
4942   // We matched a built-in operator; build it.
4943   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4944 }
4945
4946 Action::OwningExprResult
4947 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4948                                          SourceLocation RLoc,
4949                                          ExprArg Base, ExprArg Idx) {
4950   Expr *Args[2] = { static_cast<Expr*>(Base.get()),
4951                     static_cast<Expr*>(Idx.get()) };
4952   DeclarationName OpName =
4953       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
4954
4955   // If either side is type-dependent, create an appropriate dependent
4956   // expression.
4957   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4958
4959     OverloadedFunctionDecl *Overloads
4960       = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4961
4962     DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4963                                                 LLoc, false, false);
4964
4965     Base.release();
4966     Idx.release();
4967     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
4968                                                    Args, 2,
4969                                                    Context.DependentTy,
4970                                                    RLoc));
4971   }
4972
4973   // Build an empty overload set.
4974   OverloadCandidateSet CandidateSet;
4975
4976   // Subscript can only be overloaded as a member function.
4977
4978   // Add operator candidates that are member functions.
4979   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4980
4981   // Add builtin operator candidates.
4982   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4983
4984   // Perform overload resolution.
4985   OverloadCandidateSet::iterator Best;
4986   switch (BestViableFunction(CandidateSet, LLoc, Best)) {
4987     case OR_Success: {
4988       // We found a built-in operator or an overloaded operator.
4989       FunctionDecl *FnDecl = Best->Function;
4990
4991       if (FnDecl) {
4992         // We matched an overloaded operator. Build a call to that
4993         // operator.
4994
4995         // Convert the arguments.
4996         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4997         if (PerformObjectArgumentInitialization(Args[0], Method) ||
4998             PerformCopyInitialization(Args[1],
4999                                       FnDecl->getParamDecl(0)->getType(),
5000                                       "passing"))
5001           return ExprError();
5002
5003         // Determine the result type
5004         QualType ResultTy
5005           = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5006         ResultTy = ResultTy.getNonReferenceType();
5007
5008         // Build the actual expression node.
5009         Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5010                                                  LLoc);
5011         UsualUnaryConversions(FnExpr);
5012
5013         Base.release();
5014         Idx.release();
5015         ExprOwningPtr<CXXOperatorCallExpr>
5016           TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5017                                                           FnExpr, Args, 2,
5018                                                           ResultTy, RLoc));
5019
5020         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5021                                 FnDecl))
5022           return ExprError();
5023
5024         return MaybeBindToTemporary(TheCall.release());
5025       } else {
5026         // We matched a built-in operator. Convert the arguments, then
5027         // break out so that we will build the appropriate built-in
5028         // operator node.
5029         if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5030                                       Best->Conversions[0], "passing") ||
5031             PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5032                                       Best->Conversions[1], "passing"))
5033           return ExprError();
5034
5035         break;
5036       }
5037     }
5038
5039     case OR_No_Viable_Function: {
5040       // No viable function; try to create a built-in operation, which will
5041       // produce an error. Then, show the non-viable candidates.
5042       OwningExprResult Result =
5043           CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5044       assert(Result.isInvalid() && 
5045              "C++ subscript operator overloading is missing candidates!");
5046       if (Result.isInvalid())
5047         PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5048                                 "[]", LLoc);
5049       return move(Result);
5050     }
5051
5052     case OR_Ambiguous:
5053       Diag(LLoc,  diag::err_ovl_ambiguous_oper)
5054           << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5055       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5056                               "[]", LLoc);
5057       return ExprError();
5058
5059     case OR_Deleted:
5060       Diag(LLoc, diag::err_ovl_deleted_oper)
5061         << Best->Function->isDeleted() << "[]"
5062         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5063       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5064       return ExprError();
5065     }
5066
5067   // We matched a built-in operator; build it.
5068   Base.release();
5069   Idx.release();
5070   return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5071                                          Owned(Args[1]), RLoc);
5072 }
5073
5074 /// BuildCallToMemberFunction - Build a call to a member
5075 /// function. MemExpr is the expression that refers to the member
5076 /// function (and includes the object parameter), Args/NumArgs are the
5077 /// arguments to the function call (not including the object
5078 /// parameter). The caller needs to validate that the member
5079 /// expression refers to a member function or an overloaded member
5080 /// function.
5081 Sema::ExprResult
5082 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5083                                 SourceLocation LParenLoc, Expr **Args,
5084                                 unsigned NumArgs, SourceLocation *CommaLocs,
5085                                 SourceLocation RParenLoc) {
5086   // Dig out the member expression. This holds both the object
5087   // argument and the member function we're referring to.
5088   MemberExpr *MemExpr = 0;
5089   if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5090     MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5091   else
5092     MemExpr = dyn_cast<MemberExpr>(MemExprE);
5093   assert(MemExpr && "Building member call without member expression");
5094
5095   // Extract the object argument.
5096   Expr *ObjectArg = MemExpr->getBase();
5097
5098   CXXMethodDecl *Method = 0;
5099   if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5100       isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
5101     // Add overload candidates
5102     OverloadCandidateSet CandidateSet;
5103     DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
5104
5105     for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5106          Func != FuncEnd; ++Func) {
5107       if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5108         // If explicit template arguments were provided, we can't call a
5109         // non-template member function.
5110         if (MemExpr->hasExplicitTemplateArgumentList())
5111           continue;
5112         
5113         AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
5114                            /*SuppressUserConversions=*/false);
5115       } else
5116         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5117                                    MemExpr->hasExplicitTemplateArgumentList(),
5118                                    MemExpr->getTemplateArgs(),
5119                                    MemExpr->getNumTemplateArgs(),
5120                                    ObjectArg, Args, NumArgs,
5121                                    CandidateSet,
5122                                    /*SuppressUsedConversions=*/false);
5123     }
5124
5125     OverloadCandidateSet::iterator Best;
5126     switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
5127     case OR_Success:
5128       Method = cast<CXXMethodDecl>(Best->Function);
5129       break;
5130
5131     case OR_No_Viable_Function:
5132       Diag(MemExpr->getSourceRange().getBegin(),
5133            diag::err_ovl_no_viable_member_function_in_call)
5134         << DeclName << MemExprE->getSourceRange();
5135       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5136       // FIXME: Leaking incoming expressions!
5137       return true;
5138
5139     case OR_Ambiguous:
5140       Diag(MemExpr->getSourceRange().getBegin(),
5141            diag::err_ovl_ambiguous_member_call)
5142         << DeclName << MemExprE->getSourceRange();
5143       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5144       // FIXME: Leaking incoming expressions!
5145       return true;
5146
5147     case OR_Deleted:
5148       Diag(MemExpr->getSourceRange().getBegin(),
5149            diag::err_ovl_deleted_member_call)
5150         << Best->Function->isDeleted()
5151         << DeclName << MemExprE->getSourceRange();
5152       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5153       // FIXME: Leaking incoming expressions!
5154       return true;
5155     }
5156
5157     FixOverloadedFunctionReference(MemExpr, Method);
5158   } else {
5159     Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5160   }
5161
5162   assert(Method && "Member call to something that isn't a method?");
5163   ExprOwningPtr<CXXMemberCallExpr>
5164     TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
5165                                                   NumArgs,
5166                                   Method->getResultType().getNonReferenceType(),
5167                                   RParenLoc));
5168
5169   // Check for a valid return type.
5170   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 
5171                           TheCall.get(), Method))
5172     return true;
5173   
5174   // Convert the object argument (for a non-static member function call).
5175   if (!Method->isStatic() &&
5176       PerformObjectArgumentInitialization(ObjectArg, Method))
5177     return true;
5178   MemExpr->setBase(ObjectArg);
5179
5180   // Convert the rest of the arguments
5181   const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
5182   if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
5183                               RParenLoc))
5184     return true;
5185
5186   if (CheckFunctionCall(Method, TheCall.get()))
5187     return true;
5188
5189   return MaybeBindToTemporary(TheCall.release()).release();
5190 }
5191
5192 /// BuildCallToObjectOfClassType - Build a call to an object of class
5193 /// type (C++ [over.call.object]), which can end up invoking an
5194 /// overloaded function call operator (@c operator()) or performing a
5195 /// user-defined conversion on the object argument.
5196 Sema::ExprResult
5197 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
5198                                    SourceLocation LParenLoc,
5199                                    Expr **Args, unsigned NumArgs,
5200                                    SourceLocation *CommaLocs,
5201                                    SourceLocation RParenLoc) {
5202   assert(Object->getType()->isRecordType() && "Requires object type argument");
5203   const RecordType *Record = Object->getType()->getAs<RecordType>();
5204
5205   // C++ [over.call.object]p1:
5206   //  If the primary-expression E in the function call syntax
5207   //  evaluates to a class object of type "cv T", then the set of
5208   //  candidate functions includes at least the function call
5209   //  operators of T. The function call operators of T are obtained by
5210   //  ordinary lookup of the name operator() in the context of
5211   //  (E).operator().
5212   OverloadCandidateSet CandidateSet;
5213   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
5214   DeclContext::lookup_const_iterator Oper, OperEnd;
5215   for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
5216        Oper != OperEnd; ++Oper)
5217     AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
5218                        CandidateSet, /*SuppressUserConversions=*/false);
5219
5220   if (RequireCompleteType(LParenLoc, Object->getType(), 
5221                           PartialDiagnostic(diag::err_incomplete_object_call)
5222                             << Object->getSourceRange()))
5223     return true;
5224   
5225   // C++ [over.call.object]p2:
5226   //   In addition, for each conversion function declared in T of the
5227   //   form
5228   //
5229   //        operator conversion-type-id () cv-qualifier;
5230   //
5231   //   where cv-qualifier is the same cv-qualification as, or a
5232   //   greater cv-qualification than, cv, and where conversion-type-id
5233   //   denotes the type "pointer to function of (P1,...,Pn) returning
5234   //   R", or the type "reference to pointer to function of
5235   //   (P1,...,Pn) returning R", or the type "reference to function
5236   //   of (P1,...,Pn) returning R", a surrogate call function [...]
5237   //   is also considered as a candidate function. Similarly,
5238   //   surrogate call functions are added to the set of candidate
5239   //   functions for each conversion function declared in an
5240   //   accessible base class provided the function is not hidden
5241   //   within T by another intervening declaration.
5242   // FIXME: Look in base classes for more conversion operators!
5243   OverloadedFunctionDecl *Conversions
5244     = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5245   for (OverloadedFunctionDecl::function_iterator
5246          Func = Conversions->function_begin(),
5247          FuncEnd = Conversions->function_end();
5248        Func != FuncEnd; ++Func) {
5249     CXXConversionDecl *Conv;
5250     FunctionTemplateDecl *ConvTemplate;
5251     GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
5252
5253     // Skip over templated conversion functions; they aren't
5254     // surrogates.
5255     if (ConvTemplate)
5256       continue;
5257
5258     // Strip the reference type (if any) and then the pointer type (if
5259     // any) to get down to what might be a function type.
5260     QualType ConvType = Conv->getConversionType().getNonReferenceType();
5261     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5262       ConvType = ConvPtrType->getPointeeType();
5263
5264     if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5265       AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
5266   }
5267
5268   // Perform overload resolution.
5269   OverloadCandidateSet::iterator Best;
5270   switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
5271   case OR_Success:
5272     // Overload resolution succeeded; we'll build the appropriate call
5273     // below.
5274     break;
5275
5276   case OR_No_Viable_Function:
5277     Diag(Object->getSourceRange().getBegin(),
5278          diag::err_ovl_no_viable_object_call)
5279       << Object->getType() << Object->getSourceRange();
5280     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5281     break;
5282
5283   case OR_Ambiguous:
5284     Diag(Object->getSourceRange().getBegin(),
5285          diag::err_ovl_ambiguous_object_call)
5286       << Object->getType() << Object->getSourceRange();
5287     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5288     break;
5289
5290   case OR_Deleted:
5291     Diag(Object->getSourceRange().getBegin(),
5292          diag::err_ovl_deleted_object_call)
5293       << Best->Function->isDeleted()
5294       << Object->getType() << Object->getSourceRange();
5295     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5296     break;
5297   }
5298
5299   if (Best == CandidateSet.end()) {
5300     // We had an error; delete all of the subexpressions and return
5301     // the error.
5302     Object->Destroy(Context);
5303     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5304       Args[ArgIdx]->Destroy(Context);
5305     return true;
5306   }
5307
5308   if (Best->Function == 0) {
5309     // Since there is no function declaration, this is one of the
5310     // surrogate candidates. Dig out the conversion function.
5311     CXXConversionDecl *Conv
5312       = cast<CXXConversionDecl>(
5313                          Best->Conversions[0].UserDefined.ConversionFunction);
5314
5315     // We selected one of the surrogate functions that converts the
5316     // object parameter to a function pointer. Perform the conversion
5317     // on the object argument, then let ActOnCallExpr finish the job.
5318     
5319     // Create an implicit member expr to refer to the conversion operator.
5320     // and then call it.
5321     CXXMemberCallExpr *CE =
5322     BuildCXXMemberCallExpr(Object, Conv);
5323       
5324     return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
5325                          MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5326                          CommaLocs, RParenLoc).release();
5327   }
5328
5329   // We found an overloaded operator(). Build a CXXOperatorCallExpr
5330   // that calls this method, using Object for the implicit object
5331   // parameter and passing along the remaining arguments.
5332   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5333   const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
5334
5335   unsigned NumArgsInProto = Proto->getNumArgs();
5336   unsigned NumArgsToCheck = NumArgs;
5337
5338   // Build the full argument list for the method call (the
5339   // implicit object parameter is placed at the beginning of the
5340   // list).
5341   Expr **MethodArgs;
5342   if (NumArgs < NumArgsInProto) {
5343     NumArgsToCheck = NumArgsInProto;
5344     MethodArgs = new Expr*[NumArgsInProto + 1];
5345   } else {
5346     MethodArgs = new Expr*[NumArgs + 1];
5347   }
5348   MethodArgs[0] = Object;
5349   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5350     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
5351
5352   Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
5353                                           SourceLocation());
5354   UsualUnaryConversions(NewFn);
5355
5356   // Once we've built TheCall, all of the expressions are properly
5357   // owned.
5358   QualType ResultTy = Method->getResultType().getNonReferenceType();
5359   ExprOwningPtr<CXXOperatorCallExpr>
5360     TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
5361                                                     MethodArgs, NumArgs + 1,
5362                                                     ResultTy, RParenLoc));
5363   delete [] MethodArgs;
5364
5365   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(), 
5366                           Method))
5367     return true;
5368   
5369   // We may have default arguments. If so, we need to allocate more
5370   // slots in the call for them.
5371   if (NumArgs < NumArgsInProto)
5372     TheCall->setNumArgs(Context, NumArgsInProto + 1);
5373   else if (NumArgs > NumArgsInProto)
5374     NumArgsToCheck = NumArgsInProto;
5375
5376   bool IsError = false;
5377
5378   // Initialize the implicit object parameter.
5379   IsError |= PerformObjectArgumentInitialization(Object, Method);
5380   TheCall->setArg(0, Object);
5381
5382
5383   // Check the argument types.
5384   for (unsigned i = 0; i != NumArgsToCheck; i++) {
5385     Expr *Arg;
5386     if (i < NumArgs) {
5387       Arg = Args[i];
5388
5389       // Pass the argument.
5390       QualType ProtoArgType = Proto->getArgType(i);
5391       IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
5392     } else {
5393       Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
5394     }
5395
5396     TheCall->setArg(i + 1, Arg);
5397   }
5398
5399   // If this is a variadic call, handle args passed through "...".
5400   if (Proto->isVariadic()) {
5401     // Promote the arguments (C99 6.5.2.2p7).
5402     for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5403       Expr *Arg = Args[i];
5404       IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
5405       TheCall->setArg(i + 1, Arg);
5406     }
5407   }
5408
5409   if (IsError) return true;
5410
5411   if (CheckFunctionCall(Method, TheCall.get()))
5412     return true;
5413
5414   return MaybeBindToTemporary(TheCall.release()).release();
5415 }
5416
5417 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
5418 ///  (if one exists), where @c Base is an expression of class type and
5419 /// @c Member is the name of the member we're trying to find.
5420 Sema::OwningExprResult
5421 Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5422   Expr *Base = static_cast<Expr *>(BaseIn.get());
5423   assert(Base->getType()->isRecordType() && "left-hand side must have class type");
5424
5425   // C++ [over.ref]p1:
5426   //
5427   //   [...] An expression x->m is interpreted as (x.operator->())->m
5428   //   for a class object x of type T if T::operator->() exists and if
5429   //   the operator is selected as the best match function by the
5430   //   overload resolution mechanism (13.3).
5431   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5432   OverloadCandidateSet CandidateSet;
5433   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
5434
5435   LookupResult R;
5436   LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
5437
5438   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5439        Oper != OperEnd; ++Oper)
5440     AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
5441                        /*SuppressUserConversions=*/false);
5442
5443   // Perform overload resolution.
5444   OverloadCandidateSet::iterator Best;
5445   switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5446   case OR_Success:
5447     // Overload resolution succeeded; we'll build the call below.
5448     break;
5449
5450   case OR_No_Viable_Function:
5451     if (CandidateSet.empty())
5452       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5453         << Base->getType() << Base->getSourceRange();
5454     else
5455       Diag(OpLoc, diag::err_ovl_no_viable_oper)
5456         << "operator->" << Base->getSourceRange();
5457     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5458     return ExprError();
5459
5460   case OR_Ambiguous:
5461     Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5462       << "->" << Base->getSourceRange();
5463     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5464     return ExprError();
5465
5466   case OR_Deleted:
5467     Diag(OpLoc,  diag::err_ovl_deleted_oper)
5468       << Best->Function->isDeleted()
5469       << "->" << Base->getSourceRange();
5470     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5471     return ExprError();
5472   }
5473
5474   // Convert the object parameter.
5475   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5476   if (PerformObjectArgumentInitialization(Base, Method))
5477     return ExprError();
5478
5479   // No concerns about early exits now.
5480   BaseIn.release();
5481
5482   // Build the operator call.
5483   Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5484                                            SourceLocation());
5485   UsualUnaryConversions(FnExpr);
5486   
5487   QualType ResultTy = Method->getResultType().getNonReferenceType();
5488   ExprOwningPtr<CXXOperatorCallExpr> 
5489     TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, 
5490                                                     &Base, 1, ResultTy, OpLoc));
5491
5492   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(), 
5493                           Method))
5494           return ExprError();
5495   return move(TheCall);
5496 }
5497
5498 /// FixOverloadedFunctionReference - E is an expression that refers to
5499 /// a C++ overloaded function (possibly with some parentheses and
5500 /// perhaps a '&' around it). We have resolved the overloaded function
5501 /// to the function declaration Fn, so patch up the expression E to
5502 /// refer (possibly indirectly) to Fn. Returns the new expr.
5503 Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5504   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5505     Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5506     PE->setSubExpr(NewExpr);
5507     PE->setType(NewExpr->getType());
5508   } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5509     Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5510     assert(Context.hasSameType(ICE->getSubExpr()->getType(), 
5511                                NewExpr->getType()) &&
5512            "Implicit cast type cannot be determined from overload");
5513     ICE->setSubExpr(NewExpr);
5514   } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
5515     assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
5516            "Can only take the address of an overloaded function");
5517     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5518       if (Method->isStatic()) {
5519         // Do nothing: static member functions aren't any different
5520         // from non-member functions.
5521       } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5522         if (DRE->getQualifier()) {
5523           // We have taken the address of a pointer to member
5524           // function. Perform the computation here so that we get the
5525           // appropriate pointer to member type.
5526           DRE->setDecl(Fn);
5527           DRE->setType(Fn->getType());
5528           QualType ClassType
5529             = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5530           E->setType(Context.getMemberPointerType(Fn->getType(),
5531                                                   ClassType.getTypePtr()));
5532           return E;
5533         }
5534       }
5535       // FIXME: TemplateIdRefExpr referring to a member function template
5536       // specialization!
5537     }
5538     Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5539     UnOp->setSubExpr(NewExpr);
5540     UnOp->setType(Context.getPointerType(NewExpr->getType()));
5541     
5542     return UnOp;
5543   } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
5544     assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
5545             isa<FunctionTemplateDecl>(DR->getDecl()) ||
5546             isa<FunctionDecl>(DR->getDecl())) &&
5547            "Expected function or function template");
5548     DR->setDecl(Fn);
5549     E->setType(Fn->getType());
5550   } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5551     MemExpr->setMemberDecl(Fn);
5552     E->setType(Fn->getType());
5553   } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
5554     E = DeclRefExpr::Create(Context, 
5555                             TID->getQualifier(), TID->getQualifierRange(),
5556                             Fn, TID->getTemplateNameLoc(), 
5557                             true,
5558                             TID->getLAngleLoc(),
5559                             TID->getTemplateArgs(),
5560                             TID->getNumTemplateArgs(),
5561                             TID->getRAngleLoc(),
5562                             Fn->getType(), 
5563                             /*FIXME?*/false, /*FIXME?*/false);
5564     
5565     // FIXME: Don't destroy TID here, since we need its template arguments
5566     // to survive.
5567     // TID->Destroy(Context);
5568   } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5569     return DeclRefExpr::Create(Context, 
5570                                /*Qualifier=*/0,
5571                                /*QualifierRange=*/SourceRange(),
5572                                Fn, E->getLocStart(),
5573                                Fn->getType(), false, false);
5574   } else {
5575     assert(false && "Invalid reference to overloaded function");
5576   }
5577   
5578   return E;
5579 }
5580
5581 } // end namespace clang