blob: dec9854c72ebef73e862187b14f0ff6af577b3eb [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- 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"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(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,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // 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.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// 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).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
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
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000229 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296//
John McCall3d988d92009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301//
John McCall3d988d92009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000318 }
John McCall3d988d92009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000323 }
John McCall84d87672009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall1f82f242009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000338 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 }
John McCall1f82f242009-11-18 22:49:29 +0000340
John McCalldaa3d6b2009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000377 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000378 return true;
379
380 // C++ [temp.over.link]p4:
381 // The signature of a function template consists of its function
382 // signature, its return type and its template parameter list. The names
383 // of the template parameters are significant only for establishing the
384 // relationship between the template parameters and the rest of the
385 // signature.
386 //
387 // We check the return type and template parameter lists for function
388 // templates first; the remaining checks follow.
389 if (NewTemplate &&
390 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
391 OldTemplate->getTemplateParameters(),
392 false, TPL_TemplateMatch) ||
393 OldType->getResultType() != NewType->getResultType()))
394 return true;
395
396 // If the function is a class member, its signature includes the
397 // cv-qualifiers (if any) on the function itself.
398 //
399 // As part of this, also check whether one of the member functions
400 // is static, in which case they are not overloads (C++
401 // 13.1p2). While not part of the definition of the signature,
402 // this check is important to determine whether these functions
403 // can be overloaded.
404 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
405 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
406 if (OldMethod && NewMethod &&
407 !OldMethod->isStatic() && !NewMethod->isStatic() &&
408 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
409 return true;
410
411 // The signatures match; this is not an overload.
412 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000413}
414
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000415/// TryImplicitConversion - Attempt to perform an implicit conversion
416/// from the given expression (Expr) to the given type (ToType). This
417/// function returns an implicit conversion sequence that can be used
418/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000419///
420/// void f(float f);
421/// void g(int i) { f(i); }
422///
423/// this routine would produce an implicit conversion sequence to
424/// describe the initialization of f from i, which will be a standard
425/// conversion sequence containing an lvalue-to-rvalue conversion (C++
426/// 4.1) followed by a floating-integral conversion (C++ 4.9).
427//
428/// Note that this routine only determines how the conversion can be
429/// performed; it does not actually perform the conversion. As such,
430/// it will not produce any diagnostics if no conversion is available,
431/// but will instead return an implicit conversion sequence of kind
432/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000433///
434/// If @p SuppressUserConversions, then user-defined conversions are
435/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000436/// If @p AllowExplicit, then explicit user-defined conversions are
437/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000439Sema::TryImplicitConversion(Expr* From, QualType ToType,
440 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000441 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000442 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000444 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000445 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000446 return ICS;
447 }
448
449 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000450 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000451 return ICS;
452 }
453
Douglas Gregor5ab11652010-04-17 22:01:05 +0000454 if (SuppressUserConversions) {
455 // C++ [over.ics.user]p4:
456 // A conversion of an expression of class type to the same class
457 // type is given Exact Match rank, and a conversion of an
458 // expression of class type to a base class of that type is
459 // given Conversion rank, in spite of the fact that a copy/move
460 // constructor (i.e., a user-defined conversion function) is
461 // called for those cases.
462 QualType FromType = From->getType();
463 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
464 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
465 IsDerivedFrom(FromType, ToType))) {
466 // We're not in the case above, so there is no conversion that
467 // we can perform.
468 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
469 return ICS;
470 }
471
472 ICS.setStandard();
473 ICS.Standard.setAsIdentityConversion();
474 ICS.Standard.setFromType(FromType);
475 ICS.Standard.setAllToTypes(ToType);
476
477 // We don't actually check at this point whether there is a valid
478 // copy/move constructor, since overloading just assumes that it
479 // exists. When we actually perform initialization, we'll find the
480 // appropriate constructor to copy the returned object, if needed.
481 ICS.Standard.CopyConstructor = 0;
482
483 // Determine whether this is considered a derived-to-base conversion.
484 if (!Context.hasSameUnqualifiedType(FromType, ToType))
485 ICS.Standard.Second = ICK_Derived_To_Base;
486
487 return ICS;
488 }
489
490 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000491 OverloadCandidateSet Conversions(From->getExprLoc());
492 OverloadingResult UserDefResult
493 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000494 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000495
496 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000497 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000498 // C++ [over.ics.user]p4:
499 // A conversion of an expression of class type to the same class
500 // type is given Exact Match rank, and a conversion of an
501 // expression of class type to a base class of that type is
502 // given Conversion rank, in spite of the fact that a copy
503 // constructor (i.e., a user-defined conversion function) is
504 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000505 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000506 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000507 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000508 = Context.getCanonicalType(From->getType().getUnqualifiedType());
509 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000510 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000511 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000512 // Turn this into a "standard" conversion sequence, so that it
513 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000514 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000515 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000516 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000517 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000518 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000519 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000520 ICS.Standard.Second = ICK_Derived_To_Base;
521 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000522 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000523
524 // C++ [over.best.ics]p4:
525 // However, when considering the argument of a user-defined
526 // conversion function that is a candidate by 13.3.1.3 when
527 // invoked for the copying of the temporary in the second step
528 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
529 // 13.3.1.6 in all cases, only standard conversion sequences and
530 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000531 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000532 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000533 }
John McCalle8c8cd22010-01-13 22:30:33 +0000534 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000535 ICS.setAmbiguous();
536 ICS.Ambiguous.setFromType(From->getType());
537 ICS.Ambiguous.setToType(ToType);
538 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
539 Cand != Conversions.end(); ++Cand)
540 if (Cand->Viable)
541 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000542 } else {
John McCall65eb8792010-02-25 01:37:24 +0000543 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000544 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545
546 return ICS;
547}
548
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000549/// PerformImplicitConversion - Perform an implicit conversion of the
550/// expression From to the type ToType. Returns true if there was an
551/// error, false otherwise. The expression From is replaced with the
552/// converted expression. Flavor is the kind of conversion we're
553/// performing, used in the error message. If @p AllowExplicit,
554/// explicit user-defined conversions are permitted.
555bool
556Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
557 AssignmentAction Action, bool AllowExplicit) {
558 ImplicitConversionSequence ICS;
559 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
560}
561
562bool
563Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
564 AssignmentAction Action, bool AllowExplicit,
565 ImplicitConversionSequence& ICS) {
566 ICS = TryImplicitConversion(From, ToType,
567 /*SuppressUserConversions=*/false,
568 AllowExplicit,
569 /*InOverloadResolution=*/false);
570 return PerformImplicitConversion(From, ToType, ICS, Action);
571}
572
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000573/// \brief Determine whether the conversion from FromType to ToType is a valid
574/// conversion that strips "noreturn" off the nested function type.
575static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
576 QualType ToType, QualType &ResultTy) {
577 if (Context.hasSameUnqualifiedType(FromType, ToType))
578 return false;
579
580 // Strip the noreturn off the type we're converting from; noreturn can
581 // safely be removed.
582 FromType = Context.getNoReturnType(FromType, false);
583 if (!Context.hasSameUnqualifiedType(FromType, ToType))
584 return false;
585
586 ResultTy = FromType;
587 return true;
588}
589
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000590/// IsStandardConversion - Determines whether there is a standard
591/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
592/// expression From to the type ToType. Standard conversion sequences
593/// only consider non-class types; for conversions that involve class
594/// types, use TryImplicitConversion. If a conversion exists, SCS will
595/// contain the standard conversion sequence required to perform this
596/// conversion and this routine will return true. Otherwise, this
597/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000598bool
599Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000600 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000601 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 QualType FromType = From->getType();
603
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000605 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000606 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000607 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000608 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000609 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000610
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000611 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000612 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000613 if (FromType->isRecordType() || ToType->isRecordType()) {
614 if (getLangOptions().CPlusPlus)
615 return false;
616
Mike Stump11289f42009-09-09 15:08:12 +0000617 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000618 }
619
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000620 // The first conversion can be an lvalue-to-rvalue conversion,
621 // array-to-pointer conversion, or function-to-pointer conversion
622 // (C++ 4p1).
623
Douglas Gregor980fb162010-04-29 18:24:40 +0000624 if (FromType == Context.OverloadTy) {
625 DeclAccessPair AccessPair;
626 if (FunctionDecl *Fn
627 = ResolveAddressOfOverloadedFunction(From, ToType, false,
628 AccessPair)) {
629 // We were able to resolve the address of the overloaded function,
630 // so we can convert to the type of that function.
631 FromType = Fn->getType();
632 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
633 if (!Method->isStatic()) {
634 Type *ClassType
635 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
636 FromType = Context.getMemberPointerType(FromType, ClassType);
637 }
638 }
639
640 // If the "from" expression takes the address of the overloaded
641 // function, update the type of the resulting expression accordingly.
642 if (FromType->getAs<FunctionType>())
643 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
644 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
645 FromType = Context.getPointerType(FromType);
646
647 // Check that we've computed the proper type after overload resolution.
648 assert(Context.hasSameType(FromType,
649 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
650 } else {
651 return false;
652 }
653 }
Mike Stump11289f42009-09-09 15:08:12 +0000654 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000655 // An lvalue (3.10) of a non-function, non-array type T can be
656 // converted to an rvalue.
657 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000658 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000659 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000660 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662
663 // If T is a non-class type, the type of the rvalue is the
664 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000665 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
666 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000667 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000668 } else if (FromType->isArrayType()) {
669 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000670 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671
672 // An lvalue or rvalue of type "array of N T" or "array of unknown
673 // bound of T" can be converted to an rvalue of type "pointer to
674 // T" (C++ 4.2p1).
675 FromType = Context.getArrayDecayedType(FromType);
676
677 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
678 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000679 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000680
681 // For the purpose of ranking in overload resolution
682 // (13.3.3.1.1), this conversion is considered an
683 // array-to-pointer conversion followed by a qualification
684 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000685 SCS.Second = ICK_Identity;
686 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000687 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000688 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000689 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000690 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
691 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000692 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000693
694 // An lvalue of function type T can be converted to an rvalue of
695 // type "pointer to T." The result is a pointer to the
696 // function. (C++ 4.3p1).
697 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000698 } else {
699 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000700 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000702 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000703
704 // The second conversion can be an integral promotion, floating
705 // point promotion, integral conversion, floating point conversion,
706 // floating-integral conversion, pointer conversion,
707 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000708 // For overloading in C, this can also be a "compatible-type"
709 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000710 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000711 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000712 // The unqualified versions of the types are the same: there's no
713 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000714 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000715 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000716 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000717 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000718 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000719 } else if (IsFloatingPointPromotion(FromType, ToType)) {
720 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000721 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000723 } else if (IsComplexPromotion(FromType, ToType)) {
724 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000725 SCS.Second = ICK_Complex_Promotion;
726 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000727 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000728 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000729 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000730 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000732 } else if (FromType->isComplexType() && ToType->isComplexType()) {
733 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000734 SCS.Second = ICK_Complex_Conversion;
735 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000736 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
737 (ToType->isComplexType() && FromType->isArithmeticType())) {
738 // Complex-real conversions (C99 6.3.1.7)
739 SCS.Second = ICK_Complex_Real;
740 FromType = ToType.getUnqualifiedType();
741 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
742 // Floating point conversions (C++ 4.8).
743 SCS.Second = ICK_Floating_Conversion;
744 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000745 } else if ((FromType->isFloatingType() &&
746 ToType->isIntegralType() && (!ToType->isBooleanType() &&
747 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000748 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000749 ToType->isFloatingType())) {
750 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000751 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000753 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
754 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000755 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000756 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000757 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000758 } else if (IsMemberPointerConversion(From, FromType, ToType,
759 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000760 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000761 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000762 } else if (ToType->isBooleanType() &&
763 (FromType->isArithmeticType() ||
764 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000765 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000766 FromType->isBlockPointerType() ||
767 FromType->isMemberPointerType() ||
768 FromType->isNullPtrType())) {
769 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000770 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000771 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000772 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000773 Context.typesAreCompatible(ToType, FromType)) {
774 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000775 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000776 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
777 // Treat a conversion that strips "noreturn" as an identity conversion.
778 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000779 } else {
780 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000781 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000782 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000783 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000785 QualType CanonFrom;
786 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000788 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000789 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000791 CanonFrom = Context.getCanonicalType(FromType);
792 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000793 } else {
794 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000795 SCS.Third = ICK_Identity;
796
Mike Stump11289f42009-09-09 15:08:12 +0000797 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000798 // [...] Any difference in top-level cv-qualification is
799 // subsumed by the initialization itself and does not constitute
800 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000801 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000802 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000803 if (CanonFrom.getLocalUnqualifiedType()
804 == CanonTo.getLocalUnqualifiedType() &&
805 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000806 FromType = ToType;
807 CanonFrom = CanonTo;
808 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000809 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000810 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811
812 // If we have not converted the argument type to the parameter type,
813 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000814 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000815 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000817 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000818}
819
820/// IsIntegralPromotion - Determines whether the conversion from the
821/// expression From (whose potentially-adjusted type is FromType) to
822/// ToType is an integral promotion (C++ 4.5). If so, returns true and
823/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000824bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000825 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000826 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000827 if (!To) {
828 return false;
829 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830
831 // An rvalue of type char, signed char, unsigned char, short int, or
832 // unsigned short int can be converted to an rvalue of type int if
833 // int can represent all the values of the source type; otherwise,
834 // the source rvalue can be converted to an rvalue of type unsigned
835 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000836 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
837 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000838 if (// We can promote any signed, promotable integer type to an int
839 (FromType->isSignedIntegerType() ||
840 // We can promote any unsigned integer type whose size is
841 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000842 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000843 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000844 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000845 }
846
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847 return To->getKind() == BuiltinType::UInt;
848 }
849
850 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
851 // can be converted to an rvalue of the first of the following types
852 // that can represent all the values of its underlying type: int,
853 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000854
855 // We pre-calculate the promotion type for enum types.
856 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
857 if (ToType->isIntegerType())
858 return Context.hasSameUnqualifiedType(ToType,
859 FromEnumType->getDecl()->getPromotionType());
860
861 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862 // Determine whether the type we're converting from is signed or
863 // unsigned.
864 bool FromIsSigned;
865 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000866
867 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
868 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869
870 // The types we'll try to promote to, in the appropriate
871 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000872 QualType PromoteTypes[6] = {
873 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000874 Context.LongTy, Context.UnsignedLongTy ,
875 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000876 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000877 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
879 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000880 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
882 // We found the type that we can promote to. If this is the
883 // type we wanted, we have a promotion. Otherwise, no
884 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000885 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886 }
887 }
888 }
889
890 // An rvalue for an integral bit-field (9.6) can be converted to an
891 // rvalue of type int if int can represent all the values of the
892 // bit-field; otherwise, it can be converted to unsigned int if
893 // unsigned int can represent all the values of the bit-field. If
894 // the bit-field is larger yet, no integral promotion applies to
895 // it. If the bit-field has an enumerated type, it is treated as any
896 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000897 // FIXME: We should delay checking of bit-fields until we actually perform the
898 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000899 using llvm::APSInt;
900 if (From)
901 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000902 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000903 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
904 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
905 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
906 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000908 // Are we promoting to an int from a bitfield that fits in an int?
909 if (BitWidth < ToSize ||
910 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
911 return To->getKind() == BuiltinType::Int;
912 }
Mike Stump11289f42009-09-09 15:08:12 +0000913
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000914 // Are we promoting to an unsigned int from an unsigned bitfield
915 // that fits into an unsigned int?
916 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
917 return To->getKind() == BuiltinType::UInt;
918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000920 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000921 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000922 }
Mike Stump11289f42009-09-09 15:08:12 +0000923
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000924 // An rvalue of type bool can be converted to an rvalue of type int,
925 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000926 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000927 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000928 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000929
930 return false;
931}
932
933/// IsFloatingPointPromotion - Determines whether the conversion from
934/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
935/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000936bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000937 /// An rvalue of type float can be converted to an rvalue of type
938 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000939 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
940 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941 if (FromBuiltin->getKind() == BuiltinType::Float &&
942 ToBuiltin->getKind() == BuiltinType::Double)
943 return true;
944
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000945 // C99 6.3.1.5p1:
946 // When a float is promoted to double or long double, or a
947 // double is promoted to long double [...].
948 if (!getLangOptions().CPlusPlus &&
949 (FromBuiltin->getKind() == BuiltinType::Float ||
950 FromBuiltin->getKind() == BuiltinType::Double) &&
951 (ToBuiltin->getKind() == BuiltinType::LongDouble))
952 return true;
953 }
954
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955 return false;
956}
957
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000958/// \brief Determine if a conversion is a complex promotion.
959///
960/// A complex promotion is defined as a complex -> complex conversion
961/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000962/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000963bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000964 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000965 if (!FromComplex)
966 return false;
967
John McCall9dd450b2009-09-21 23:43:11 +0000968 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000969 if (!ToComplex)
970 return false;
971
972 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000973 ToComplex->getElementType()) ||
974 IsIntegralPromotion(0, FromComplex->getElementType(),
975 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000976}
977
Douglas Gregor237f96c2008-11-26 23:31:11 +0000978/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
979/// the pointer type FromPtr to a pointer to type ToPointee, with the
980/// same type qualifiers as FromPtr has on its pointee type. ToType,
981/// if non-empty, will be a pointer to ToType that may or may not have
982/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000983static QualType
984BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000985 QualType ToPointee, QualType ToType,
986 ASTContext &Context) {
987 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
988 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000989 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000990
991 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000992 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000993 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000994 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000995 return ToType;
996
997 // Build a pointer to ToPointee. It has the right qualifiers
998 // already.
999 return Context.getPointerType(ToPointee);
1000 }
1001
1002 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001003 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001004 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1005 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001006}
1007
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001008/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1009/// the FromType, which is an objective-c pointer, to ToType, which may or may
1010/// not have the right set of qualifiers.
1011static QualType
1012BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1013 QualType ToType,
1014 ASTContext &Context) {
1015 QualType CanonFromType = Context.getCanonicalType(FromType);
1016 QualType CanonToType = Context.getCanonicalType(ToType);
1017 Qualifiers Quals = CanonFromType.getQualifiers();
1018
1019 // Exact qualifier match -> return the pointer type we're converting to.
1020 if (CanonToType.getLocalQualifiers() == Quals)
1021 return ToType;
1022
1023 // Just build a canonical type that has the right qualifiers.
1024 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1025}
1026
Mike Stump11289f42009-09-09 15:08:12 +00001027static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001028 bool InOverloadResolution,
1029 ASTContext &Context) {
1030 // Handle value-dependent integral null pointer constants correctly.
1031 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1032 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1033 Expr->getType()->isIntegralType())
1034 return !InOverloadResolution;
1035
Douglas Gregor56751b52009-09-25 04:25:58 +00001036 return Expr->isNullPointerConstant(Context,
1037 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1038 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001039}
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001041/// IsPointerConversion - Determines whether the conversion of the
1042/// expression From, which has the (possibly adjusted) type FromType,
1043/// can be converted to the type ToType via a pointer conversion (C++
1044/// 4.10). If so, returns true and places the converted type (that
1045/// might differ from ToType in its cv-qualifiers at some level) into
1046/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001047///
Douglas Gregora29dc052008-11-27 01:19:21 +00001048/// This routine also supports conversions to and from block pointers
1049/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1050/// pointers to interfaces. FIXME: Once we've determined the
1051/// appropriate overloading rules for Objective-C, we may want to
1052/// split the Objective-C checks into a different routine; however,
1053/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001054/// conversions, so for now they live here. IncompatibleObjC will be
1055/// set if the conversion is an allowed Objective-C conversion that
1056/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001057bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001058 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001059 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001060 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001061 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001062 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1063 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001064
Mike Stump11289f42009-09-09 15:08:12 +00001065 // Conversion from a null pointer constant to any Objective-C pointer type.
1066 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001067 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001068 ConvertedType = ToType;
1069 return true;
1070 }
1071
Douglas Gregor231d1c62008-11-27 00:15:41 +00001072 // Blocks: Block pointers can be converted to void*.
1073 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001074 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001075 ConvertedType = ToType;
1076 return true;
1077 }
1078 // Blocks: A null pointer constant can be converted to a block
1079 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001080 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001082 ConvertedType = ToType;
1083 return true;
1084 }
1085
Sebastian Redl576fd422009-05-10 18:38:11 +00001086 // If the left-hand-side is nullptr_t, the right side can be a null
1087 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001088 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001089 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001090 ConvertedType = ToType;
1091 return true;
1092 }
1093
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001094 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001095 if (!ToTypePtr)
1096 return false;
1097
1098 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001099 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100 ConvertedType = ToType;
1101 return true;
1102 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001103
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001104 // Beyond this point, both types need to be pointers
1105 // , including objective-c pointers.
1106 QualType ToPointeeType = ToTypePtr->getPointeeType();
1107 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1108 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1109 ToType, Context);
1110 return true;
1111
1112 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001113 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001114 if (!FromTypePtr)
1115 return false;
1116
1117 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001118
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119 // An rvalue of type "pointer to cv T," where T is an object type,
1120 // can be converted to an rvalue of type "pointer to cv void" (C++
1121 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001122 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001124 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001125 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126 return true;
1127 }
1128
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001129 // When we're overloading in C, we allow a special kind of pointer
1130 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001131 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001132 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001133 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001134 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001135 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001136 return true;
1137 }
1138
Douglas Gregor5c407d92008-10-23 00:40:37 +00001139 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001140 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001141 // An rvalue of type "pointer to cv D," where D is a class type,
1142 // can be converted to an rvalue of type "pointer to cv B," where
1143 // B is a base class (clause 10) of D. If B is an inaccessible
1144 // (clause 11) or ambiguous (10.2) base class of D, a program that
1145 // necessitates this conversion is ill-formed. The result of the
1146 // conversion is a pointer to the base class sub-object of the
1147 // derived class object. The null pointer value is converted to
1148 // the null pointer value of the destination type.
1149 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001150 // Note that we do not check for ambiguity or inaccessibility
1151 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001152 if (getLangOptions().CPlusPlus &&
1153 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001154 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001155 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001156 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001157 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001158 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001159 ToType, Context);
1160 return true;
1161 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001162
Douglas Gregora119f102008-12-19 19:13:09 +00001163 return false;
1164}
1165
1166/// isObjCPointerConversion - Determines whether this is an
1167/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1168/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001169bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001170 QualType& ConvertedType,
1171 bool &IncompatibleObjC) {
1172 if (!getLangOptions().ObjC1)
1173 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001174
Steve Naroff7cae42b2009-07-10 23:34:53 +00001175 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001176 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001177 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001178 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001179
Steve Naroff7cae42b2009-07-10 23:34:53 +00001180 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001181 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001182 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001183 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001184 ConvertedType = ToType;
1185 return true;
1186 }
1187 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001188 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001189 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001190 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001191 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001192 ConvertedType = ToType;
1193 return true;
1194 }
1195 // Objective C++: We're able to convert from a pointer to an
1196 // interface to a pointer to a different interface.
1197 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001198 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1199 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1200 if (getLangOptions().CPlusPlus && LHS && RHS &&
1201 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1202 FromObjCPtr->getPointeeType()))
1203 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001204 ConvertedType = ToType;
1205 return true;
1206 }
1207
1208 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1209 // Okay: this is some kind of implicit downcast of Objective-C
1210 // interfaces, which is permitted. However, we're going to
1211 // complain about it.
1212 IncompatibleObjC = true;
1213 ConvertedType = FromType;
1214 return true;
1215 }
Mike Stump11289f42009-09-09 15:08:12 +00001216 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001217 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001218 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001219 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001220 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001221 else if (const BlockPointerType *ToBlockPtr =
1222 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001223 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001224 // to a block pointer type.
1225 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1226 ConvertedType = ToType;
1227 return true;
1228 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001229 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001230 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001231 else if (FromType->getAs<BlockPointerType>() &&
1232 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1233 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001234 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001235 ConvertedType = ToType;
1236 return true;
1237 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001238 else
Douglas Gregora119f102008-12-19 19:13:09 +00001239 return false;
1240
Douglas Gregor033f56d2008-12-23 00:53:59 +00001241 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001242 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001243 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001244 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001245 FromPointeeType = FromBlockPtr->getPointeeType();
1246 else
Douglas Gregora119f102008-12-19 19:13:09 +00001247 return false;
1248
Douglas Gregora119f102008-12-19 19:13:09 +00001249 // If we have pointers to pointers, recursively check whether this
1250 // is an Objective-C conversion.
1251 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1252 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1253 IncompatibleObjC)) {
1254 // We always complain about this conversion.
1255 IncompatibleObjC = true;
1256 ConvertedType = ToType;
1257 return true;
1258 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001259 // Allow conversion of pointee being objective-c pointer to another one;
1260 // as in I* to id.
1261 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1262 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1263 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1264 IncompatibleObjC)) {
1265 ConvertedType = ToType;
1266 return true;
1267 }
1268
Douglas Gregor033f56d2008-12-23 00:53:59 +00001269 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001270 // differences in the argument and result types are in Objective-C
1271 // pointer conversions. If so, we permit the conversion (but
1272 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001273 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001274 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001275 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001276 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001277 if (FromFunctionType && ToFunctionType) {
1278 // If the function types are exactly the same, this isn't an
1279 // Objective-C pointer conversion.
1280 if (Context.getCanonicalType(FromPointeeType)
1281 == Context.getCanonicalType(ToPointeeType))
1282 return false;
1283
1284 // Perform the quick checks that will tell us whether these
1285 // function types are obviously different.
1286 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1287 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1288 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1289 return false;
1290
1291 bool HasObjCConversion = false;
1292 if (Context.getCanonicalType(FromFunctionType->getResultType())
1293 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1294 // Okay, the types match exactly. Nothing to do.
1295 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1296 ToFunctionType->getResultType(),
1297 ConvertedType, IncompatibleObjC)) {
1298 // Okay, we have an Objective-C pointer conversion.
1299 HasObjCConversion = true;
1300 } else {
1301 // Function types are too different. Abort.
1302 return false;
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregora119f102008-12-19 19:13:09 +00001305 // Check argument types.
1306 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1307 ArgIdx != NumArgs; ++ArgIdx) {
1308 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1309 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1310 if (Context.getCanonicalType(FromArgType)
1311 == Context.getCanonicalType(ToArgType)) {
1312 // Okay, the types match exactly. Nothing to do.
1313 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1314 ConvertedType, IncompatibleObjC)) {
1315 // Okay, we have an Objective-C pointer conversion.
1316 HasObjCConversion = true;
1317 } else {
1318 // Argument types are too different. Abort.
1319 return false;
1320 }
1321 }
1322
1323 if (HasObjCConversion) {
1324 // We had an Objective-C conversion. Allow this pointer
1325 // conversion, but complain about it.
1326 ConvertedType = ToType;
1327 IncompatibleObjC = true;
1328 return true;
1329 }
1330 }
1331
Sebastian Redl72b597d2009-01-25 19:43:20 +00001332 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001334
1335/// FunctionArgTypesAreEqual - This routine checks two function proto types
1336/// for equlity of their argument types. Caller has already checked that
1337/// they have same number of arguments. This routine assumes that Objective-C
1338/// pointer types which only differ in their protocol qualifiers are equal.
1339bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1340 FunctionProtoType* NewType){
1341 if (!getLangOptions().ObjC1)
1342 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1343 NewType->arg_type_begin());
1344
1345 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1346 N = NewType->arg_type_begin(),
1347 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1348 QualType ToType = (*O);
1349 QualType FromType = (*N);
1350 if (ToType != FromType) {
1351 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1352 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001353 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1354 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1355 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1356 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001357 continue;
1358 }
1359 else if (ToType->isObjCObjectPointerType() &&
1360 FromType->isObjCObjectPointerType()) {
1361 QualType ToInterfaceTy = ToType->getPointeeType();
1362 QualType FromInterfaceTy = FromType->getPointeeType();
1363 if (const ObjCInterfaceType *OITTo =
1364 ToInterfaceTy->getAs<ObjCInterfaceType>())
1365 if (const ObjCInterfaceType *OITFr =
1366 FromInterfaceTy->getAs<ObjCInterfaceType>())
1367 if (OITTo->getDecl() == OITFr->getDecl())
1368 continue;
1369 }
1370 return false;
1371 }
1372 }
1373 return true;
1374}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375
Douglas Gregor39c16d42008-10-24 04:54:22 +00001376/// CheckPointerConversion - Check the pointer conversion from the
1377/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001378/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001379/// conversions for which IsPointerConversion has already returned
1380/// true. It returns true and produces a diagnostic if there was an
1381/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001382bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001383 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001384 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001385 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001386 QualType FromType = From->getType();
1387
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001388 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1389 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001390 QualType FromPointeeType = FromPtrType->getPointeeType(),
1391 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001392
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001393 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1394 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001395 // We must have a derived-to-base conversion. Check an
1396 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001397 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1398 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001399 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001400 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001401 return true;
1402
1403 // The conversion was successful.
1404 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001405 }
1406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001408 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001409 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001410 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001411 // Objective-C++ conversions are always okay.
1412 // FIXME: We should have a different class of conversions for the
1413 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001414 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001415 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001416
Steve Naroff7cae42b2009-07-10 23:34:53 +00001417 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001418 return false;
1419}
1420
Sebastian Redl72b597d2009-01-25 19:43:20 +00001421/// IsMemberPointerConversion - Determines whether the conversion of the
1422/// expression From, which has the (possibly adjusted) type FromType, can be
1423/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1424/// If so, returns true and places the converted type (that might differ from
1425/// ToType in its cv-qualifiers at some level) into ConvertedType.
1426bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001427 QualType ToType,
1428 bool InOverloadResolution,
1429 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001430 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001431 if (!ToTypePtr)
1432 return false;
1433
1434 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001435 if (From->isNullPointerConstant(Context,
1436 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1437 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001438 ConvertedType = ToType;
1439 return true;
1440 }
1441
1442 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001443 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001444 if (!FromTypePtr)
1445 return false;
1446
1447 // A pointer to member of B can be converted to a pointer to member of D,
1448 // where D is derived from B (C++ 4.11p2).
1449 QualType FromClass(FromTypePtr->getClass(), 0);
1450 QualType ToClass(ToTypePtr->getClass(), 0);
1451 // FIXME: What happens when these are dependent? Is this function even called?
1452
1453 if (IsDerivedFrom(ToClass, FromClass)) {
1454 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1455 ToClass.getTypePtr());
1456 return true;
1457 }
1458
1459 return false;
1460}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001461
Sebastian Redl72b597d2009-01-25 19:43:20 +00001462/// CheckMemberPointerConversion - Check the member pointer conversion from the
1463/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001464/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001465/// for which IsMemberPointerConversion has already returned true. It returns
1466/// true and produces a diagnostic if there was an error, or returns false
1467/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001468bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001469 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001470 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001471 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001472 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001473 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001474 if (!FromPtrType) {
1475 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001476 assert(From->isNullPointerConstant(Context,
1477 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001478 "Expr must be null pointer constant!");
1479 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001480 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001481 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001482
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001483 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001484 assert(ToPtrType && "No member pointer cast has a target type "
1485 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001486
Sebastian Redled8f2002009-01-28 18:33:18 +00001487 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1488 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001489
Sebastian Redled8f2002009-01-28 18:33:18 +00001490 // FIXME: What about dependent types?
1491 assert(FromClass->isRecordType() && "Pointer into non-class.");
1492 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001493
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001494 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001495 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001496 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1497 assert(DerivationOkay &&
1498 "Should not have been called if derivation isn't OK.");
1499 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001500
Sebastian Redled8f2002009-01-28 18:33:18 +00001501 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1502 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001503 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1504 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1505 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1506 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001507 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001508
Douglas Gregor89ee6822009-02-28 01:32:25 +00001509 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001510 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1511 << FromClass << ToClass << QualType(VBase, 0)
1512 << From->getSourceRange();
1513 return true;
1514 }
1515
John McCall5b0829a2010-02-10 09:31:12 +00001516 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001517 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1518 Paths.front(),
1519 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001520
Anders Carlssond7923c62009-08-22 23:33:40 +00001521 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001522 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001523 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001524 return false;
1525}
1526
Douglas Gregor9a657932008-10-21 23:43:52 +00001527/// IsQualificationConversion - Determines whether the conversion from
1528/// an rvalue of type FromType to ToType is a qualification conversion
1529/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001530bool
1531Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001532 FromType = Context.getCanonicalType(FromType);
1533 ToType = Context.getCanonicalType(ToType);
1534
1535 // If FromType and ToType are the same type, this is not a
1536 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001537 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001538 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001539
Douglas Gregor9a657932008-10-21 23:43:52 +00001540 // (C++ 4.4p4):
1541 // A conversion can add cv-qualifiers at levels other than the first
1542 // in multi-level pointers, subject to the following rules: [...]
1543 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001544 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001545 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001546 // Within each iteration of the loop, we check the qualifiers to
1547 // determine if this still looks like a qualification
1548 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001549 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001550 // until there are no more pointers or pointers-to-members left to
1551 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001552 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001553
1554 // -- for every j > 0, if const is in cv 1,j then const is in cv
1555 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001556 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001557 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001558
Douglas Gregor9a657932008-10-21 23:43:52 +00001559 // -- if the cv 1,j and cv 2,j are different, then const is in
1560 // every cv for 0 < k < j.
1561 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001562 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001563 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregor9a657932008-10-21 23:43:52 +00001565 // Keep track of whether all prior cv-qualifiers in the "to" type
1566 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001567 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001568 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001569 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001570
1571 // We are left with FromType and ToType being the pointee types
1572 // after unwrapping the original FromType and ToType the same number
1573 // of types. If we unwrapped any pointers, and if FromType and
1574 // ToType have the same unqualified type (since we checked
1575 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001576 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001577}
1578
Douglas Gregor576e98c2009-01-30 23:27:23 +00001579/// Determines whether there is a user-defined conversion sequence
1580/// (C++ [over.ics.user]) that converts expression From to the type
1581/// ToType. If such a conversion exists, User will contain the
1582/// user-defined conversion sequence that performs such a conversion
1583/// and this routine will return true. Otherwise, this routine returns
1584/// false and User is unspecified.
1585///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001586/// \param AllowExplicit true if the conversion should consider C++0x
1587/// "explicit" conversion functions as well as non-explicit conversion
1588/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001589OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1590 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001591 OverloadCandidateSet& CandidateSet,
1592 bool AllowExplicit) {
1593 // Whether we will only visit constructors.
1594 bool ConstructorsOnly = false;
1595
1596 // If the type we are conversion to is a class type, enumerate its
1597 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001598 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001599 // C++ [over.match.ctor]p1:
1600 // When objects of class type are direct-initialized (8.5), or
1601 // copy-initialized from an expression of the same or a
1602 // derived class type (8.5), overload resolution selects the
1603 // constructor. [...] For copy-initialization, the candidate
1604 // functions are all the converting constructors (12.3.1) of
1605 // that class. The argument list is the expression-list within
1606 // the parentheses of the initializer.
1607 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1608 (From->getType()->getAs<RecordType>() &&
1609 IsDerivedFrom(From->getType(), ToType)))
1610 ConstructorsOnly = true;
1611
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001612 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1613 // We're not going to find any constructors.
1614 } else if (CXXRecordDecl *ToRecordDecl
1615 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001616 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001617 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001618 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001619 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001620 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001621 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001622 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001623 NamedDecl *D = *Con;
1624 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1625
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001626 // Find the constructor (which may be a template).
1627 CXXConstructorDecl *Constructor = 0;
1628 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001629 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001630 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001631 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001632 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1633 else
John McCalla0296f72010-03-19 07:35:19 +00001634 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001635
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001636 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001637 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001638 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001639 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001640 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001641 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001642 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001643 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001644 // Allow one user-defined conversion when user specifies a
1645 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001646 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001647 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001648 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001649 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001650 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001651 }
1652 }
1653
Douglas Gregor5ab11652010-04-17 22:01:05 +00001654 // Enumerate conversion functions, if we're allowed to.
1655 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001656 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001657 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001658 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001659 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001660 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001661 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001662 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1663 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001664 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001665 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001666 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001667 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001668 DeclAccessPair FoundDecl = I.getPair();
1669 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001670 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1671 if (isa<UsingShadowDecl>(D))
1672 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1673
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001674 CXXConversionDecl *Conv;
1675 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001676 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1677 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001678 else
John McCallda4458e2010-03-31 01:36:47 +00001679 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001680
1681 if (AllowExplicit || !Conv->isExplicit()) {
1682 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001683 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001684 ActingContext, From, ToType,
1685 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001686 else
John McCalla0296f72010-03-19 07:35:19 +00001687 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001688 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001689 }
1690 }
1691 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001692 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693
1694 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001695 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001696 case OR_Success:
1697 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001698 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001699 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1700 // C++ [over.ics.user]p1:
1701 // If the user-defined conversion is specified by a
1702 // constructor (12.3.1), the initial standard conversion
1703 // sequence converts the source type to the type required by
1704 // the argument of the constructor.
1705 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001706 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001707 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001708 User.EllipsisConversion = true;
1709 else {
1710 User.Before = Best->Conversions[0].Standard;
1711 User.EllipsisConversion = false;
1712 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001713 User.ConversionFunction = Constructor;
1714 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001715 User.After.setFromType(
1716 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001717 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001718 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001719 } else if (CXXConversionDecl *Conversion
1720 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1721 // C++ [over.ics.user]p1:
1722 //
1723 // [...] If the user-defined conversion is specified by a
1724 // conversion function (12.3.2), the initial standard
1725 // conversion sequence converts the source type to the
1726 // implicit object parameter of the conversion function.
1727 User.Before = Best->Conversions[0].Standard;
1728 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001729 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001730
1731 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001732 // The second standard conversion sequence converts the
1733 // result of the user-defined conversion to the target type
1734 // for the sequence. Since an implicit conversion sequence
1735 // is an initialization, the special rules for
1736 // initialization by user-defined conversion apply when
1737 // selecting the best user-defined conversion for a
1738 // user-defined conversion sequence (see 13.3.3 and
1739 // 13.3.3.1).
1740 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001741 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001742 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001743 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001744 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001745 }
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001747 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001748 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001749 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001750 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001751 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001752
1753 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001754 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001755 }
1756
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001757 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001758}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001759
1760bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001761Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001762 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001763 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001764 OverloadingResult OvResult =
1765 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001766 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001767 if (OvResult == OR_Ambiguous)
1768 Diag(From->getSourceRange().getBegin(),
1769 diag::err_typecheck_ambiguous_condition)
1770 << From->getType() << ToType << From->getSourceRange();
1771 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1772 Diag(From->getSourceRange().getBegin(),
1773 diag::err_typecheck_nonviable_condition)
1774 << From->getType() << ToType << From->getSourceRange();
1775 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001776 return false;
John McCallad907772010-01-12 07:18:19 +00001777 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001778 return true;
1779}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001780
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781/// CompareImplicitConversionSequences - Compare two implicit
1782/// conversion sequences to determine whether one is better than the
1783/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001784ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1786 const ImplicitConversionSequence& ICS2)
1787{
1788 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1789 // conversion sequences (as defined in 13.3.3.1)
1790 // -- a standard conversion sequence (13.3.3.1.1) is a better
1791 // conversion sequence than a user-defined conversion sequence or
1792 // an ellipsis conversion sequence, and
1793 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1794 // conversion sequence than an ellipsis conversion sequence
1795 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001796 //
John McCall0d1da222010-01-12 00:44:57 +00001797 // C++0x [over.best.ics]p10:
1798 // For the purpose of ranking implicit conversion sequences as
1799 // described in 13.3.3.2, the ambiguous conversion sequence is
1800 // treated as a user-defined sequence that is indistinguishable
1801 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001802 if (ICS1.getKindRank() < ICS2.getKindRank())
1803 return ImplicitConversionSequence::Better;
1804 else if (ICS2.getKindRank() < ICS1.getKindRank())
1805 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001806
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00001807 // The following checks require both conversion sequences to be of
1808 // the same kind.
1809 if (ICS1.getKind() != ICS2.getKind())
1810 return ImplicitConversionSequence::Indistinguishable;
1811
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001812 // Two implicit conversion sequences of the same form are
1813 // indistinguishable conversion sequences unless one of the
1814 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001815 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001816 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001817 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001818 // User-defined conversion sequence U1 is a better conversion
1819 // sequence than another user-defined conversion sequence U2 if
1820 // they contain the same user-defined conversion function or
1821 // constructor and if the second standard conversion sequence of
1822 // U1 is better than the second standard conversion sequence of
1823 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001824 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 ICS2.UserDefined.ConversionFunction)
1826 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1827 ICS2.UserDefined.After);
1828 }
1829
1830 return ImplicitConversionSequence::Indistinguishable;
1831}
1832
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001833// Per 13.3.3.2p3, compare the given standard conversion sequences to
1834// determine if one is a proper subset of the other.
1835static ImplicitConversionSequence::CompareKind
1836compareStandardConversionSubsets(ASTContext &Context,
1837 const StandardConversionSequence& SCS1,
1838 const StandardConversionSequence& SCS2) {
1839 ImplicitConversionSequence::CompareKind Result
1840 = ImplicitConversionSequence::Indistinguishable;
1841
1842 if (SCS1.Second != SCS2.Second) {
1843 if (SCS1.Second == ICK_Identity)
1844 Result = ImplicitConversionSequence::Better;
1845 else if (SCS2.Second == ICK_Identity)
1846 Result = ImplicitConversionSequence::Worse;
1847 else
1848 return ImplicitConversionSequence::Indistinguishable;
1849 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1850 return ImplicitConversionSequence::Indistinguishable;
1851
1852 if (SCS1.Third == SCS2.Third) {
1853 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1854 : ImplicitConversionSequence::Indistinguishable;
1855 }
1856
1857 if (SCS1.Third == ICK_Identity)
1858 return Result == ImplicitConversionSequence::Worse
1859 ? ImplicitConversionSequence::Indistinguishable
1860 : ImplicitConversionSequence::Better;
1861
1862 if (SCS2.Third == ICK_Identity)
1863 return Result == ImplicitConversionSequence::Better
1864 ? ImplicitConversionSequence::Indistinguishable
1865 : ImplicitConversionSequence::Worse;
1866
1867 return ImplicitConversionSequence::Indistinguishable;
1868}
1869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870/// CompareStandardConversionSequences - Compare two standard
1871/// conversion sequences to determine whether one is better than the
1872/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001873ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001874Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1875 const StandardConversionSequence& SCS2)
1876{
1877 // Standard conversion sequence S1 is a better conversion sequence
1878 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1879
1880 // -- S1 is a proper subsequence of S2 (comparing the conversion
1881 // sequences in the canonical form defined by 13.3.3.1.1,
1882 // excluding any Lvalue Transformation; the identity conversion
1883 // sequence is considered to be a subsequence of any
1884 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001885 if (ImplicitConversionSequence::CompareKind CK
1886 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1887 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888
1889 // -- the rank of S1 is better than the rank of S2 (by the rules
1890 // defined below), or, if not that,
1891 ImplicitConversionRank Rank1 = SCS1.getRank();
1892 ImplicitConversionRank Rank2 = SCS2.getRank();
1893 if (Rank1 < Rank2)
1894 return ImplicitConversionSequence::Better;
1895 else if (Rank2 < Rank1)
1896 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001897
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001898 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1899 // are indistinguishable unless one of the following rules
1900 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001901
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001902 // A conversion that is not a conversion of a pointer, or
1903 // pointer to member, to bool is better than another conversion
1904 // that is such a conversion.
1905 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1906 return SCS2.isPointerConversionToBool()
1907 ? ImplicitConversionSequence::Better
1908 : ImplicitConversionSequence::Worse;
1909
Douglas Gregor5c407d92008-10-23 00:40:37 +00001910 // C++ [over.ics.rank]p4b2:
1911 //
1912 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001913 // conversion of B* to A* is better than conversion of B* to
1914 // void*, and conversion of A* to void* is better than conversion
1915 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001916 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001917 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001918 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001919 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001920 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1921 // Exactly one of the conversion sequences is a conversion to
1922 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001923 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1924 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001925 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1926 // Neither conversion sequence converts to a void pointer; compare
1927 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001928 if (ImplicitConversionSequence::CompareKind DerivedCK
1929 = CompareDerivedToBaseConversions(SCS1, SCS2))
1930 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001931 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1932 // Both conversion sequences are conversions to void
1933 // pointers. Compare the source types to determine if there's an
1934 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001935 QualType FromType1 = SCS1.getFromType();
1936 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001937
1938 // Adjust the types we're converting from via the array-to-pointer
1939 // conversion, if we need to.
1940 if (SCS1.First == ICK_Array_To_Pointer)
1941 FromType1 = Context.getArrayDecayedType(FromType1);
1942 if (SCS2.First == ICK_Array_To_Pointer)
1943 FromType2 = Context.getArrayDecayedType(FromType2);
1944
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001945 QualType FromPointee1
1946 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1947 QualType FromPointee2
1948 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001949
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001950 if (IsDerivedFrom(FromPointee2, FromPointee1))
1951 return ImplicitConversionSequence::Better;
1952 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1953 return ImplicitConversionSequence::Worse;
1954
1955 // Objective-C++: If one interface is more specific than the
1956 // other, it is the better one.
1957 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1958 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1959 if (FromIface1 && FromIface1) {
1960 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1961 return ImplicitConversionSequence::Better;
1962 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1963 return ImplicitConversionSequence::Worse;
1964 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001965 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001966
1967 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1968 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001969 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001970 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001971 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001972
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001973 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001974 // C++0x [over.ics.rank]p3b4:
1975 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1976 // implicit object parameter of a non-static member function declared
1977 // without a ref-qualifier, and S1 binds an rvalue reference to an
1978 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001979 // FIXME: We don't know if we're dealing with the implicit object parameter,
1980 // or if the member function in this case has a ref qualifier.
1981 // (Of course, we don't have ref qualifiers yet.)
1982 if (SCS1.RRefBinding != SCS2.RRefBinding)
1983 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1984 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001985
1986 // C++ [over.ics.rank]p3b4:
1987 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1988 // which the references refer are the same type except for
1989 // top-level cv-qualifiers, and the type to which the reference
1990 // initialized by S2 refers is more cv-qualified than the type
1991 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001992 QualType T1 = SCS1.getToType(2);
1993 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001994 T1 = Context.getCanonicalType(T1);
1995 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001996 Qualifiers T1Quals, T2Quals;
1997 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1998 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1999 if (UnqualT1 == UnqualT2) {
2000 // If the type is an array type, promote the element qualifiers to the type
2001 // for comparison.
2002 if (isa<ArrayType>(T1) && T1Quals)
2003 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2004 if (isa<ArrayType>(T2) && T2Quals)
2005 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002006 if (T2.isMoreQualifiedThan(T1))
2007 return ImplicitConversionSequence::Better;
2008 else if (T1.isMoreQualifiedThan(T2))
2009 return ImplicitConversionSequence::Worse;
2010 }
2011 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002012
2013 return ImplicitConversionSequence::Indistinguishable;
2014}
2015
2016/// CompareQualificationConversions - Compares two standard conversion
2017/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002018/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2019ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002020Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002021 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002022 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002023 // -- S1 and S2 differ only in their qualification conversion and
2024 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2025 // cv-qualification signature of type T1 is a proper subset of
2026 // the cv-qualification signature of type T2, and S1 is not the
2027 // deprecated string literal array-to-pointer conversion (4.2).
2028 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2029 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2030 return ImplicitConversionSequence::Indistinguishable;
2031
2032 // FIXME: the example in the standard doesn't use a qualification
2033 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002034 QualType T1 = SCS1.getToType(2);
2035 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002036 T1 = Context.getCanonicalType(T1);
2037 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002038 Qualifiers T1Quals, T2Quals;
2039 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2040 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002041
2042 // If the types are the same, we won't learn anything by unwrapped
2043 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002044 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002045 return ImplicitConversionSequence::Indistinguishable;
2046
Chandler Carruth607f38e2009-12-29 07:16:59 +00002047 // If the type is an array type, promote the element qualifiers to the type
2048 // for comparison.
2049 if (isa<ArrayType>(T1) && T1Quals)
2050 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2051 if (isa<ArrayType>(T2) && T2Quals)
2052 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2053
Mike Stump11289f42009-09-09 15:08:12 +00002054 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002055 = ImplicitConversionSequence::Indistinguishable;
2056 while (UnwrapSimilarPointerTypes(T1, T2)) {
2057 // Within each iteration of the loop, we check the qualifiers to
2058 // determine if this still looks like a qualification
2059 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002060 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002061 // until there are no more pointers or pointers-to-members left
2062 // to unwrap. This essentially mimics what
2063 // IsQualificationConversion does, but here we're checking for a
2064 // strict subset of qualifiers.
2065 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2066 // The qualifiers are the same, so this doesn't tell us anything
2067 // about how the sequences rank.
2068 ;
2069 else if (T2.isMoreQualifiedThan(T1)) {
2070 // T1 has fewer qualifiers, so it could be the better sequence.
2071 if (Result == ImplicitConversionSequence::Worse)
2072 // Neither has qualifiers that are a subset of the other's
2073 // qualifiers.
2074 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002075
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002076 Result = ImplicitConversionSequence::Better;
2077 } else if (T1.isMoreQualifiedThan(T2)) {
2078 // T2 has fewer qualifiers, so it could be the better sequence.
2079 if (Result == ImplicitConversionSequence::Better)
2080 // Neither has qualifiers that are a subset of the other's
2081 // qualifiers.
2082 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002083
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002084 Result = ImplicitConversionSequence::Worse;
2085 } else {
2086 // Qualifiers are disjoint.
2087 return ImplicitConversionSequence::Indistinguishable;
2088 }
2089
2090 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002091 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002092 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002093 }
2094
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002095 // Check that the winning standard conversion sequence isn't using
2096 // the deprecated string literal array to pointer conversion.
2097 switch (Result) {
2098 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002099 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002100 Result = ImplicitConversionSequence::Indistinguishable;
2101 break;
2102
2103 case ImplicitConversionSequence::Indistinguishable:
2104 break;
2105
2106 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002107 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002108 Result = ImplicitConversionSequence::Indistinguishable;
2109 break;
2110 }
2111
2112 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002113}
2114
Douglas Gregor5c407d92008-10-23 00:40:37 +00002115/// CompareDerivedToBaseConversions - Compares two standard conversion
2116/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002117/// various kinds of derived-to-base conversions (C++
2118/// [over.ics.rank]p4b3). As part of these checks, we also look at
2119/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002120ImplicitConversionSequence::CompareKind
2121Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2122 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002123 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002124 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002125 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002126 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002127
2128 // Adjust the types we're converting from via the array-to-pointer
2129 // conversion, if we need to.
2130 if (SCS1.First == ICK_Array_To_Pointer)
2131 FromType1 = Context.getArrayDecayedType(FromType1);
2132 if (SCS2.First == ICK_Array_To_Pointer)
2133 FromType2 = Context.getArrayDecayedType(FromType2);
2134
2135 // Canonicalize all of the types.
2136 FromType1 = Context.getCanonicalType(FromType1);
2137 ToType1 = Context.getCanonicalType(ToType1);
2138 FromType2 = Context.getCanonicalType(FromType2);
2139 ToType2 = Context.getCanonicalType(ToType2);
2140
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002141 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002142 //
2143 // If class B is derived directly or indirectly from class A and
2144 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 //
2146 // For Objective-C, we let A, B, and C also be Objective-C
2147 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002148
2149 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002150 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002151 SCS2.Second == ICK_Pointer_Conversion &&
2152 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2153 FromType1->isPointerType() && FromType2->isPointerType() &&
2154 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002155 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002156 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002157 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002158 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002159 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002160 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002161 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002162 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002163
John McCall9dd450b2009-09-21 23:43:11 +00002164 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2165 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2166 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2167 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002168
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002169 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002170 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2171 if (IsDerivedFrom(ToPointee1, ToPointee2))
2172 return ImplicitConversionSequence::Better;
2173 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2174 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002175
2176 if (ToIface1 && ToIface2) {
2177 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2178 return ImplicitConversionSequence::Better;
2179 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2180 return ImplicitConversionSequence::Worse;
2181 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002182 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002183
2184 // -- conversion of B* to A* is better than conversion of C* to A*,
2185 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2186 if (IsDerivedFrom(FromPointee2, FromPointee1))
2187 return ImplicitConversionSequence::Better;
2188 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2189 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002190
Douglas Gregor237f96c2008-11-26 23:31:11 +00002191 if (FromIface1 && FromIface2) {
2192 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2193 return ImplicitConversionSequence::Better;
2194 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2195 return ImplicitConversionSequence::Worse;
2196 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002197 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002198 }
2199
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002200 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002201 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2202 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2203 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2204 const MemberPointerType * FromMemPointer1 =
2205 FromType1->getAs<MemberPointerType>();
2206 const MemberPointerType * ToMemPointer1 =
2207 ToType1->getAs<MemberPointerType>();
2208 const MemberPointerType * FromMemPointer2 =
2209 FromType2->getAs<MemberPointerType>();
2210 const MemberPointerType * ToMemPointer2 =
2211 ToType2->getAs<MemberPointerType>();
2212 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2213 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2214 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2215 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2216 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2217 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2218 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2219 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002220 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002221 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2222 if (IsDerivedFrom(ToPointee1, ToPointee2))
2223 return ImplicitConversionSequence::Worse;
2224 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2225 return ImplicitConversionSequence::Better;
2226 }
2227 // conversion of B::* to C::* is better than conversion of A::* to C::*
2228 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2229 if (IsDerivedFrom(FromPointee1, FromPointee2))
2230 return ImplicitConversionSequence::Better;
2231 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2232 return ImplicitConversionSequence::Worse;
2233 }
2234 }
2235
Douglas Gregor5ab11652010-04-17 22:01:05 +00002236 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002237 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002238 // -- binding of an expression of type C to a reference of type
2239 // B& is better than binding an expression of type C to a
2240 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002241 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2242 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002243 if (IsDerivedFrom(ToType1, ToType2))
2244 return ImplicitConversionSequence::Better;
2245 else if (IsDerivedFrom(ToType2, ToType1))
2246 return ImplicitConversionSequence::Worse;
2247 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002248
Douglas Gregor2fe98832008-11-03 19:09:14 +00002249 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002250 // -- binding of an expression of type B to a reference of type
2251 // A& is better than binding an expression of type C to a
2252 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002253 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2254 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002255 if (IsDerivedFrom(FromType2, FromType1))
2256 return ImplicitConversionSequence::Better;
2257 else if (IsDerivedFrom(FromType1, FromType2))
2258 return ImplicitConversionSequence::Worse;
2259 }
2260 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002261
Douglas Gregor5c407d92008-10-23 00:40:37 +00002262 return ImplicitConversionSequence::Indistinguishable;
2263}
2264
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002265/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2266/// determine whether they are reference-related,
2267/// reference-compatible, reference-compatible with added
2268/// qualification, or incompatible, for use in C++ initialization by
2269/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2270/// type, and the first type (T1) is the pointee type of the reference
2271/// type being initialized.
2272Sema::ReferenceCompareResult
2273Sema::CompareReferenceRelationship(SourceLocation Loc,
2274 QualType OrigT1, QualType OrigT2,
2275 bool& DerivedToBase) {
2276 assert(!OrigT1->isReferenceType() &&
2277 "T1 must be the pointee type of the reference type");
2278 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2279
2280 QualType T1 = Context.getCanonicalType(OrigT1);
2281 QualType T2 = Context.getCanonicalType(OrigT2);
2282 Qualifiers T1Quals, T2Quals;
2283 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2284 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2285
2286 // C++ [dcl.init.ref]p4:
2287 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2288 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2289 // T1 is a base class of T2.
2290 if (UnqualT1 == UnqualT2)
2291 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002292 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002293 IsDerivedFrom(UnqualT2, UnqualT1))
2294 DerivedToBase = true;
2295 else
2296 return Ref_Incompatible;
2297
2298 // At this point, we know that T1 and T2 are reference-related (at
2299 // least).
2300
2301 // If the type is an array type, promote the element qualifiers to the type
2302 // for comparison.
2303 if (isa<ArrayType>(T1) && T1Quals)
2304 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2305 if (isa<ArrayType>(T2) && T2Quals)
2306 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2307
2308 // C++ [dcl.init.ref]p4:
2309 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2310 // reference-related to T2 and cv1 is the same cv-qualification
2311 // as, or greater cv-qualification than, cv2. For purposes of
2312 // overload resolution, cases for which cv1 is greater
2313 // cv-qualification than cv2 are identified as
2314 // reference-compatible with added qualification (see 13.3.3.2).
2315 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2316 return Ref_Compatible;
2317 else if (T1.isMoreQualifiedThan(T2))
2318 return Ref_Compatible_With_Added_Qualification;
2319 else
2320 return Ref_Related;
2321}
2322
2323/// \brief Compute an implicit conversion sequence for reference
2324/// initialization.
2325static ImplicitConversionSequence
2326TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2327 SourceLocation DeclLoc,
2328 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002329 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002330 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2331
2332 // Most paths end in a failed conversion.
2333 ImplicitConversionSequence ICS;
2334 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2335
2336 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2337 QualType T2 = Init->getType();
2338
2339 // If the initializer is the address of an overloaded function, try
2340 // to resolve the overloaded function. If all goes well, T2 is the
2341 // type of the resulting function.
2342 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2343 DeclAccessPair Found;
2344 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2345 false, Found))
2346 T2 = Fn->getType();
2347 }
2348
2349 // Compute some basic properties of the types and the initializer.
2350 bool isRValRef = DeclType->isRValueReferenceType();
2351 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002352 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002353 Sema::ReferenceCompareResult RefRelationship
2354 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2355
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002356
2357 // C++ [over.ics.ref]p3:
2358 // Except for an implicit object parameter, for which see 13.3.1,
2359 // a standard conversion sequence cannot be formed if it requires
2360 // binding an lvalue reference to non-const to an rvalue or
2361 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002362 //
2363 // FIXME: DPG doesn't trust this code. It seems far too early to
2364 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002365 if (isRValRef && InitLvalue == Expr::LV_Valid)
2366 return ICS;
2367
Douglas Gregor870f3742010-04-18 09:22:00 +00002368 // C++0x [dcl.init.ref]p16:
2369 // A reference to type "cv1 T1" is initialized by an expression
2370 // of type "cv2 T2" as follows:
2371
2372 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002373 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2374 // reference-compatible with "cv2 T2," or
2375 //
2376 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2377 if (InitLvalue == Expr::LV_Valid &&
2378 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2379 // C++ [over.ics.ref]p1:
2380 // When a parameter of reference type binds directly (8.5.3)
2381 // to an argument expression, the implicit conversion sequence
2382 // is the identity conversion, unless the argument expression
2383 // has a type that is a derived class of the parameter type,
2384 // in which case the implicit conversion sequence is a
2385 // derived-to-base Conversion (13.3.3.1).
2386 ICS.setStandard();
2387 ICS.Standard.First = ICK_Identity;
2388 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2389 ICS.Standard.Third = ICK_Identity;
2390 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2391 ICS.Standard.setToType(0, T2);
2392 ICS.Standard.setToType(1, T1);
2393 ICS.Standard.setToType(2, T1);
2394 ICS.Standard.ReferenceBinding = true;
2395 ICS.Standard.DirectBinding = true;
2396 ICS.Standard.RRefBinding = false;
2397 ICS.Standard.CopyConstructor = 0;
2398
2399 // Nothing more to do: the inaccessibility/ambiguity check for
2400 // derived-to-base conversions is suppressed when we're
2401 // computing the implicit conversion sequence (C++
2402 // [over.best.ics]p2).
2403 return ICS;
2404 }
2405
2406 // -- has a class type (i.e., T2 is a class type), where T1 is
2407 // not reference-related to T2, and can be implicitly
2408 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2409 // is reference-compatible with "cv3 T3" 92) (this
2410 // conversion is selected by enumerating the applicable
2411 // conversion functions (13.3.1.6) and choosing the best
2412 // one through overload resolution (13.3)),
2413 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2414 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2415 RefRelationship == Sema::Ref_Incompatible) {
2416 CXXRecordDecl *T2RecordDecl
2417 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2418
2419 OverloadCandidateSet CandidateSet(DeclLoc);
2420 const UnresolvedSetImpl *Conversions
2421 = T2RecordDecl->getVisibleConversionFunctions();
2422 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2423 E = Conversions->end(); I != E; ++I) {
2424 NamedDecl *D = *I;
2425 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2426 if (isa<UsingShadowDecl>(D))
2427 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2428
2429 FunctionTemplateDecl *ConvTemplate
2430 = dyn_cast<FunctionTemplateDecl>(D);
2431 CXXConversionDecl *Conv;
2432 if (ConvTemplate)
2433 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2434 else
2435 Conv = cast<CXXConversionDecl>(D);
2436
2437 // If the conversion function doesn't return a reference type,
2438 // it can't be considered for this conversion.
2439 if (Conv->getConversionType()->isLValueReferenceType() &&
2440 (AllowExplicit || !Conv->isExplicit())) {
2441 if (ConvTemplate)
2442 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2443 Init, DeclType, CandidateSet);
2444 else
2445 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2446 DeclType, CandidateSet);
2447 }
2448 }
2449
2450 OverloadCandidateSet::iterator Best;
2451 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2452 case OR_Success:
2453 // C++ [over.ics.ref]p1:
2454 //
2455 // [...] If the parameter binds directly to the result of
2456 // applying a conversion function to the argument
2457 // expression, the implicit conversion sequence is a
2458 // user-defined conversion sequence (13.3.3.1.2), with the
2459 // second standard conversion sequence either an identity
2460 // conversion or, if the conversion function returns an
2461 // entity of a type that is a derived class of the parameter
2462 // type, a derived-to-base Conversion.
2463 if (!Best->FinalConversion.DirectBinding)
2464 break;
2465
2466 ICS.setUserDefined();
2467 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2468 ICS.UserDefined.After = Best->FinalConversion;
2469 ICS.UserDefined.ConversionFunction = Best->Function;
2470 ICS.UserDefined.EllipsisConversion = false;
2471 assert(ICS.UserDefined.After.ReferenceBinding &&
2472 ICS.UserDefined.After.DirectBinding &&
2473 "Expected a direct reference binding!");
2474 return ICS;
2475
2476 case OR_Ambiguous:
2477 ICS.setAmbiguous();
2478 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2479 Cand != CandidateSet.end(); ++Cand)
2480 if (Cand->Viable)
2481 ICS.Ambiguous.addConversion(Cand->Function);
2482 return ICS;
2483
2484 case OR_No_Viable_Function:
2485 case OR_Deleted:
2486 // There was no suitable conversion, or we found a deleted
2487 // conversion; continue with other checks.
2488 break;
2489 }
2490 }
2491
2492 // -- Otherwise, the reference shall be to a non-volatile const
2493 // type (i.e., cv1 shall be const), or the reference shall be an
2494 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002495 //
2496 // We actually handle one oddity of C++ [over.ics.ref] at this
2497 // point, which is that, due to p2 (which short-circuits reference
2498 // binding by only attempting a simple conversion for non-direct
2499 // bindings) and p3's strange wording, we allow a const volatile
2500 // reference to bind to an rvalue. Hence the check for the presence
2501 // of "const" rather than checking for "const" being the only
2502 // qualifier.
2503 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002504 return ICS;
2505
Douglas Gregorf93df192010-04-18 08:46:23 +00002506 // -- if T2 is a class type and
2507 // -- the initializer expression is an rvalue and "cv1 T1"
2508 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002509 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002510 // -- T1 is not reference-related to T2 and the initializer
2511 // expression can be implicitly converted to an rvalue
2512 // of type "cv3 T3" (this conversion is selected by
2513 // enumerating the applicable conversion functions
2514 // (13.3.1.6) and choosing the best one through overload
2515 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002516 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002517 // then the reference is bound to the initializer
2518 // expression rvalue in the first case and to the object
2519 // that is the result of the conversion in the second case
2520 // (or, in either case, to the appropriate base class
2521 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002522 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002523 // We're only checking the first case here, which is a direct
2524 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002525 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2526 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2527 ICS.setStandard();
2528 ICS.Standard.First = ICK_Identity;
2529 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2530 ICS.Standard.Third = ICK_Identity;
2531 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2532 ICS.Standard.setToType(0, T2);
2533 ICS.Standard.setToType(1, T1);
2534 ICS.Standard.setToType(2, T1);
2535 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002536 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002537 ICS.Standard.RRefBinding = isRValRef;
2538 ICS.Standard.CopyConstructor = 0;
2539 return ICS;
2540 }
2541
2542 // -- Otherwise, a temporary of type "cv1 T1" is created and
2543 // initialized from the initializer expression using the
2544 // rules for a non-reference copy initialization (8.5). The
2545 // reference is then bound to the temporary. If T1 is
2546 // reference-related to T2, cv1 must be the same
2547 // cv-qualification as, or greater cv-qualification than,
2548 // cv2; otherwise, the program is ill-formed.
2549 if (RefRelationship == Sema::Ref_Related) {
2550 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2551 // we would be reference-compatible or reference-compatible with
2552 // added qualification. But that wasn't the case, so the reference
2553 // initialization fails.
2554 return ICS;
2555 }
2556
2557 // If at least one of the types is a class type, the types are not
2558 // related, and we aren't allowed any user conversions, the
2559 // reference binding fails. This case is important for breaking
2560 // recursion, since TryImplicitConversion below will attempt to
2561 // create a temporary through the use of a copy constructor.
2562 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2563 (T1->isRecordType() || T2->isRecordType()))
2564 return ICS;
2565
2566 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002567 // When a parameter of reference type is not bound directly to
2568 // an argument expression, the conversion sequence is the one
2569 // required to convert the argument expression to the
2570 // underlying type of the reference according to
2571 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2572 // to copy-initializing a temporary of the underlying type with
2573 // the argument expression. Any difference in top-level
2574 // cv-qualification is subsumed by the initialization itself
2575 // and does not constitute a conversion.
2576 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2577 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002578 /*InOverloadResolution=*/false);
2579
2580 // Of course, that's still a reference binding.
2581 if (ICS.isStandard()) {
2582 ICS.Standard.ReferenceBinding = true;
2583 ICS.Standard.RRefBinding = isRValRef;
2584 } else if (ICS.isUserDefined()) {
2585 ICS.UserDefined.After.ReferenceBinding = true;
2586 ICS.UserDefined.After.RRefBinding = isRValRef;
2587 }
2588 return ICS;
2589}
2590
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002591/// TryCopyInitialization - Try to copy-initialize a value of type
2592/// ToType from the expression From. Return the implicit conversion
2593/// sequence required to pass this argument, which may be a bad
2594/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002595/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002596/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002597static ImplicitConversionSequence
2598TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002599 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002600 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002601 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002602 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002603 /*FIXME:*/From->getLocStart(),
2604 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002605 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002606
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002607 return S.TryImplicitConversion(From, ToType,
2608 SuppressUserConversions,
2609 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002610 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002611}
2612
Douglas Gregor436424c2008-11-18 23:14:02 +00002613/// TryObjectArgumentInitialization - Try to initialize the object
2614/// parameter of the given member function (@c Method) from the
2615/// expression @p From.
2616ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002617Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002618 CXXMethodDecl *Method,
2619 CXXRecordDecl *ActingContext) {
2620 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002621 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2622 // const volatile object.
2623 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2624 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2625 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002626
2627 // Set up the conversion sequence as a "bad" conversion, to allow us
2628 // to exit early.
2629 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002630
2631 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002632 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002633 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002634 FromType = PT->getPointeeType();
2635
2636 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002637
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002638 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002639 // where X is the class of which the function is a member
2640 // (C++ [over.match.funcs]p4). However, when finding an implicit
2641 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002642 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002643 // (C++ [over.match.funcs]p5). We perform a simplified version of
2644 // reference binding here, that allows class rvalues to bind to
2645 // non-constant references.
2646
2647 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2648 // with the implicit object parameter (C++ [over.match.funcs]p5).
2649 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002650 if (ImplicitParamType.getCVRQualifiers()
2651 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002652 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002653 ICS.setBad(BadConversionSequence::bad_qualifiers,
2654 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002655 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002656 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002657
2658 // Check that we have either the same type or a derived type. It
2659 // affects the conversion rank.
2660 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002661 ImplicitConversionKind SecondKind;
2662 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2663 SecondKind = ICK_Identity;
2664 } else if (IsDerivedFrom(FromType, ClassType))
2665 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002666 else {
John McCall65eb8792010-02-25 01:37:24 +00002667 ICS.setBad(BadConversionSequence::unrelated_class,
2668 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002669 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002670 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002671
2672 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002673 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002674 ICS.Standard.setAsIdentityConversion();
2675 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002676 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002677 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002678 ICS.Standard.ReferenceBinding = true;
2679 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002680 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002681 return ICS;
2682}
2683
2684/// PerformObjectArgumentInitialization - Perform initialization of
2685/// the implicit object parameter for the given Method with the given
2686/// expression.
2687bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002688Sema::PerformObjectArgumentInitialization(Expr *&From,
2689 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002690 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002691 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002692 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002693 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002694 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002695
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002696 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002697 FromRecordType = PT->getPointeeType();
2698 DestType = Method->getThisType(Context);
2699 } else {
2700 FromRecordType = From->getType();
2701 DestType = ImplicitParamRecordType;
2702 }
2703
John McCall6e9f8f62009-12-03 04:06:58 +00002704 // Note that we always use the true parent context when performing
2705 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002706 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002707 = TryObjectArgumentInitialization(From->getType(), Method,
2708 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002709 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002710 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002711 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002712 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002713
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002714 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002715 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002716
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002717 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002718 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2719 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002720 return false;
2721}
2722
Douglas Gregor5fb53972009-01-14 15:45:31 +00002723/// TryContextuallyConvertToBool - Attempt to contextually convert the
2724/// expression From to bool (C++0x [conv]p3).
2725ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002726 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002727 // FIXME: Are these flags correct?
2728 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002729 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002730 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002731}
2732
2733/// PerformContextuallyConvertToBool - Perform a contextual conversion
2734/// of the expression From to bool (C++0x [conv]p3).
2735bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2736 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002737 if (!ICS.isBad())
2738 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002739
Fariborz Jahanian76197412009-11-18 18:26:29 +00002740 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002741 return Diag(From->getSourceRange().getBegin(),
2742 diag::err_typecheck_bool_condition)
2743 << From->getType() << From->getSourceRange();
2744 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002745}
2746
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002747/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002748/// candidate functions, using the given function call arguments. If
2749/// @p SuppressUserConversions, then don't allow user-defined
2750/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002751///
2752/// \para PartialOverloading true if we are performing "partial" overloading
2753/// based on an incomplete set of function arguments. This feature is used by
2754/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002755void
2756Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002757 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002758 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002759 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002760 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002761 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002762 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002763 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002764 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002765 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002766 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002767
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002768 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002769 if (!isa<CXXConstructorDecl>(Method)) {
2770 // If we get here, it's because we're calling a member function
2771 // that is named without a member access expression (e.g.,
2772 // "this->f") that was either written explicitly or created
2773 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002774 // function, e.g., X::f(). We use an empty type for the implied
2775 // object argument (C++ [over.call.func]p3), and the acting context
2776 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002777 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002778 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002779 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002780 return;
2781 }
2782 // We treat a constructor like a non-member function, since its object
2783 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002784 }
2785
Douglas Gregorff7028a2009-11-13 23:59:09 +00002786 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002787 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002788
Douglas Gregor27381f32009-11-23 12:27:39 +00002789 // Overload resolution is always an unevaluated context.
2790 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2791
Douglas Gregorffe14e32009-11-14 01:20:54 +00002792 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2793 // C++ [class.copy]p3:
2794 // A member function template is never instantiated to perform the copy
2795 // of a class object to an object of its class type.
2796 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2797 if (NumArgs == 1 &&
2798 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002799 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2800 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002801 return;
2802 }
2803
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002804 // Add this candidate
2805 CandidateSet.push_back(OverloadCandidate());
2806 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002807 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002808 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002809 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002810 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002811 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002812
2813 unsigned NumArgsInProto = Proto->getNumArgs();
2814
2815 // (C++ 13.3.2p2): A candidate function having fewer than m
2816 // parameters is viable only if it has an ellipsis in its parameter
2817 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002818 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2819 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002820 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002821 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002822 return;
2823 }
2824
2825 // (C++ 13.3.2p2): A candidate function having more than m parameters
2826 // is viable only if the (m+1)st parameter has a default argument
2827 // (8.3.6). For the purposes of overload resolution, the
2828 // parameter list is truncated on the right, so that there are
2829 // exactly m parameters.
2830 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002831 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002832 // Not enough arguments.
2833 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002834 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002835 return;
2836 }
2837
2838 // Determine the implicit conversion sequences for each of the
2839 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002840 Candidate.Conversions.resize(NumArgs);
2841 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2842 if (ArgIdx < NumArgsInProto) {
2843 // (C++ 13.3.2p3): for F to be a viable function, there shall
2844 // exist for each argument an implicit conversion sequence
2845 // (13.3.3.1) that converts that argument to the corresponding
2846 // parameter of F.
2847 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002848 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002849 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002850 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00002851 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002852 if (Candidate.Conversions[ArgIdx].isBad()) {
2853 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002854 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002855 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002856 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002857 } else {
2858 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2859 // argument for which there is no corresponding parameter is
2860 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002861 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002862 }
2863 }
2864}
2865
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002866/// \brief Add all of the function declarations in the given function set to
2867/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002868void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002869 Expr **Args, unsigned NumArgs,
2870 OverloadCandidateSet& CandidateSet,
2871 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002872 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002873 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2874 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002875 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002876 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002877 cast<CXXMethodDecl>(FD)->getParent(),
2878 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002879 CandidateSet, SuppressUserConversions);
2880 else
John McCalla0296f72010-03-19 07:35:19 +00002881 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002882 SuppressUserConversions);
2883 } else {
John McCalla0296f72010-03-19 07:35:19 +00002884 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002885 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2886 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002887 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002888 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002889 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002890 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002891 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002892 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002893 else
John McCalla0296f72010-03-19 07:35:19 +00002894 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002895 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002896 Args, NumArgs, CandidateSet,
2897 SuppressUserConversions);
2898 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002899 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002900}
2901
John McCallf0f1cf02009-11-17 07:50:12 +00002902/// AddMethodCandidate - Adds a named decl (which is some kind of
2903/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002904void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002905 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002906 Expr **Args, unsigned NumArgs,
2907 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002908 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002909 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002910 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002911
2912 if (isa<UsingShadowDecl>(Decl))
2913 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2914
2915 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2916 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2917 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002918 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2919 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002920 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002921 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002922 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002923 } else {
John McCalla0296f72010-03-19 07:35:19 +00002924 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002925 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002926 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002927 }
2928}
2929
Douglas Gregor436424c2008-11-18 23:14:02 +00002930/// AddMethodCandidate - Adds the given C++ member function to the set
2931/// of candidate functions, using the given function call arguments
2932/// and the object argument (@c Object). For example, in a call
2933/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2934/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2935/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002936/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002937void
John McCalla0296f72010-03-19 07:35:19 +00002938Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002939 CXXRecordDecl *ActingContext, QualType ObjectType,
2940 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002941 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002942 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002943 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002944 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002945 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002946 assert(!isa<CXXConstructorDecl>(Method) &&
2947 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002948
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002949 if (!CandidateSet.isNewCandidate(Method))
2950 return;
2951
Douglas Gregor27381f32009-11-23 12:27:39 +00002952 // Overload resolution is always an unevaluated context.
2953 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2954
Douglas Gregor436424c2008-11-18 23:14:02 +00002955 // Add this candidate
2956 CandidateSet.push_back(OverloadCandidate());
2957 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002958 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002959 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002960 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002961 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002962
2963 unsigned NumArgsInProto = Proto->getNumArgs();
2964
2965 // (C++ 13.3.2p2): A candidate function having fewer than m
2966 // parameters is viable only if it has an ellipsis in its parameter
2967 // list (8.3.5).
2968 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2969 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002970 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002971 return;
2972 }
2973
2974 // (C++ 13.3.2p2): A candidate function having more than m parameters
2975 // is viable only if the (m+1)st parameter has a default argument
2976 // (8.3.6). For the purposes of overload resolution, the
2977 // parameter list is truncated on the right, so that there are
2978 // exactly m parameters.
2979 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2980 if (NumArgs < MinRequiredArgs) {
2981 // Not enough arguments.
2982 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002983 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002984 return;
2985 }
2986
2987 Candidate.Viable = true;
2988 Candidate.Conversions.resize(NumArgs + 1);
2989
John McCall6e9f8f62009-12-03 04:06:58 +00002990 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002991 // The implicit object argument is ignored.
2992 Candidate.IgnoreObjectArgument = true;
2993 else {
2994 // Determine the implicit conversion sequence for the object
2995 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002996 Candidate.Conversions[0]
2997 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002998 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002999 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003000 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003001 return;
3002 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003003 }
3004
3005 // Determine the implicit conversion sequences for each of the
3006 // arguments.
3007 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3008 if (ArgIdx < NumArgsInProto) {
3009 // (C++ 13.3.2p3): for F to be a viable function, there shall
3010 // exist for each argument an implicit conversion sequence
3011 // (13.3.3.1) that converts that argument to the corresponding
3012 // parameter of F.
3013 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003014 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003015 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003016 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003017 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003018 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003019 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003020 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003021 break;
3022 }
3023 } else {
3024 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3025 // argument for which there is no corresponding parameter is
3026 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003027 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003028 }
3029 }
3030}
3031
Douglas Gregor97628d62009-08-21 00:16:32 +00003032/// \brief Add a C++ member function template as a candidate to the candidate
3033/// set, using template argument deduction to produce an appropriate member
3034/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003035void
Douglas Gregor97628d62009-08-21 00:16:32 +00003036Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003037 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003038 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003039 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003040 QualType ObjectType,
3041 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003042 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003043 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003044 if (!CandidateSet.isNewCandidate(MethodTmpl))
3045 return;
3046
Douglas Gregor97628d62009-08-21 00:16:32 +00003047 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003048 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003049 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003050 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003051 // candidate functions in the usual way.113) A given name can refer to one
3052 // or more function templates and also to a set of overloaded non-template
3053 // functions. In such a case, the candidate functions generated from each
3054 // function template are combined with the set of non-template candidate
3055 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003056 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003057 FunctionDecl *Specialization = 0;
3058 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003059 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003060 Args, NumArgs, Specialization, Info)) {
3061 // FIXME: Record what happened with template argument deduction, so
3062 // that we can give the user a beautiful diagnostic.
3063 (void)Result;
3064 return;
3065 }
Mike Stump11289f42009-09-09 15:08:12 +00003066
Douglas Gregor97628d62009-08-21 00:16:32 +00003067 // Add the function template specialization produced by template argument
3068 // deduction as a candidate.
3069 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003070 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003071 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003072 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003073 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003074 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003075}
3076
Douglas Gregor05155d82009-08-21 23:19:43 +00003077/// \brief Add a C++ function template specialization as a candidate
3078/// in the candidate set, using template argument deduction to produce
3079/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003080void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003081Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003082 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003083 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003084 Expr **Args, unsigned NumArgs,
3085 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003086 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003087 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3088 return;
3089
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003090 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003091 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003092 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003093 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003094 // candidate functions in the usual way.113) A given name can refer to one
3095 // or more function templates and also to a set of overloaded non-template
3096 // functions. In such a case, the candidate functions generated from each
3097 // function template are combined with the set of non-template candidate
3098 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003099 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003100 FunctionDecl *Specialization = 0;
3101 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003102 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003103 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003104 CandidateSet.push_back(OverloadCandidate());
3105 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003106 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003107 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3108 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003109 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003110 Candidate.IsSurrogate = false;
3111 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003112
3113 // TODO: record more information about failed template arguments
3114 Candidate.DeductionFailure.Result = Result;
3115 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003116 return;
3117 }
Mike Stump11289f42009-09-09 15:08:12 +00003118
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003119 // Add the function template specialization produced by template argument
3120 // deduction as a candidate.
3121 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003122 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003123 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003124}
Mike Stump11289f42009-09-09 15:08:12 +00003125
Douglas Gregora1f013e2008-11-07 22:36:19 +00003126/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003127/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003128/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003129/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003130/// (which may or may not be the same type as the type that the
3131/// conversion function produces).
3132void
3133Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003134 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003135 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003136 Expr *From, QualType ToType,
3137 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003138 assert(!Conversion->getDescribedFunctionTemplate() &&
3139 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003140 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003141 if (!CandidateSet.isNewCandidate(Conversion))
3142 return;
3143
Douglas Gregor27381f32009-11-23 12:27:39 +00003144 // Overload resolution is always an unevaluated context.
3145 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3146
Douglas Gregora1f013e2008-11-07 22:36:19 +00003147 // Add this candidate
3148 CandidateSet.push_back(OverloadCandidate());
3149 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003150 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003151 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003152 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003153 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003154 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003155 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003156 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003157
Douglas Gregor436424c2008-11-18 23:14:02 +00003158 // Determine the implicit conversion sequence for the implicit
3159 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003160 Candidate.Viable = true;
3161 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003162 Candidate.Conversions[0]
3163 = TryObjectArgumentInitialization(From->getType(), Conversion,
3164 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003165 // Conversion functions to a different type in the base class is visible in
3166 // the derived class. So, a derived to base conversion should not participate
3167 // in overload resolution.
3168 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3169 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003170 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003171 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003172 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003173 return;
3174 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003175
3176 // We won't go through a user-define type conversion function to convert a
3177 // derived to base as such conversions are given Conversion Rank. They only
3178 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3179 QualType FromCanon
3180 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3181 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3182 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3183 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003184 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003185 return;
3186 }
3187
Douglas Gregora1f013e2008-11-07 22:36:19 +00003188 // To determine what the conversion from the result of calling the
3189 // conversion function to the type we're eventually trying to
3190 // convert to (ToType), we need to synthesize a call to the
3191 // conversion function and attempt copy initialization from it. This
3192 // makes sure that we get the right semantics with respect to
3193 // lvalues/rvalues and the type. Fortunately, we can allocate this
3194 // call on the stack and we don't need its arguments to be
3195 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003196 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003197 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003198 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003199 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003200 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003201
3202 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003203 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3204 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003205 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003206 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003207 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003208 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003209 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003210 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003211 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003212
John McCall0d1da222010-01-12 00:44:57 +00003213 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003214 case ImplicitConversionSequence::StandardConversion:
3215 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003216
3217 // C++ [over.ics.user]p3:
3218 // If the user-defined conversion is specified by a specialization of a
3219 // conversion function template, the second standard conversion sequence
3220 // shall have exact match rank.
3221 if (Conversion->getPrimaryTemplate() &&
3222 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3223 Candidate.Viable = false;
3224 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3225 }
3226
Douglas Gregora1f013e2008-11-07 22:36:19 +00003227 break;
3228
3229 case ImplicitConversionSequence::BadConversion:
3230 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003231 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003232 break;
3233
3234 default:
Mike Stump11289f42009-09-09 15:08:12 +00003235 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003236 "Can only end up with a standard conversion sequence or failure");
3237 }
3238}
3239
Douglas Gregor05155d82009-08-21 23:19:43 +00003240/// \brief Adds a conversion function template specialization
3241/// candidate to the overload set, using template argument deduction
3242/// to deduce the template arguments of the conversion function
3243/// template from the type that we are converting to (C++
3244/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003245void
Douglas Gregor05155d82009-08-21 23:19:43 +00003246Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003247 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003248 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003249 Expr *From, QualType ToType,
3250 OverloadCandidateSet &CandidateSet) {
3251 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3252 "Only conversion function templates permitted here");
3253
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003254 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3255 return;
3256
John McCallbc077cf2010-02-08 23:07:23 +00003257 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003258 CXXConversionDecl *Specialization = 0;
3259 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003260 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003261 Specialization, Info)) {
3262 // FIXME: Record what happened with template argument deduction, so
3263 // that we can give the user a beautiful diagnostic.
3264 (void)Result;
3265 return;
3266 }
Mike Stump11289f42009-09-09 15:08:12 +00003267
Douglas Gregor05155d82009-08-21 23:19:43 +00003268 // Add the conversion function template specialization produced by
3269 // template argument deduction as a candidate.
3270 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003271 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003272 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003273}
3274
Douglas Gregorab7897a2008-11-19 22:57:39 +00003275/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3276/// converts the given @c Object to a function pointer via the
3277/// conversion function @c Conversion, and then attempts to call it
3278/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3279/// the type of function that we'll eventually be calling.
3280void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003281 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003282 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003283 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003284 QualType ObjectType,
3285 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003286 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003287 if (!CandidateSet.isNewCandidate(Conversion))
3288 return;
3289
Douglas Gregor27381f32009-11-23 12:27:39 +00003290 // Overload resolution is always an unevaluated context.
3291 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3292
Douglas Gregorab7897a2008-11-19 22:57:39 +00003293 CandidateSet.push_back(OverloadCandidate());
3294 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003295 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003296 Candidate.Function = 0;
3297 Candidate.Surrogate = Conversion;
3298 Candidate.Viable = true;
3299 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003300 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003301 Candidate.Conversions.resize(NumArgs + 1);
3302
3303 // Determine the implicit conversion sequence for the implicit
3304 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003305 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003306 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003307 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003308 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003309 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003310 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003311 return;
3312 }
3313
3314 // The first conversion is actually a user-defined conversion whose
3315 // first conversion is ObjectInit's standard conversion (which is
3316 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003317 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003318 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003319 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003320 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003321 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003322 = Candidate.Conversions[0].UserDefined.Before;
3323 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3324
Mike Stump11289f42009-09-09 15:08:12 +00003325 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003326 unsigned NumArgsInProto = Proto->getNumArgs();
3327
3328 // (C++ 13.3.2p2): A candidate function having fewer than m
3329 // parameters is viable only if it has an ellipsis in its parameter
3330 // list (8.3.5).
3331 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3332 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003333 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003334 return;
3335 }
3336
3337 // Function types don't have any default arguments, so just check if
3338 // we have enough arguments.
3339 if (NumArgs < NumArgsInProto) {
3340 // Not enough arguments.
3341 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003342 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003343 return;
3344 }
3345
3346 // Determine the implicit conversion sequences for each of the
3347 // arguments.
3348 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3349 if (ArgIdx < NumArgsInProto) {
3350 // (C++ 13.3.2p3): for F to be a viable function, there shall
3351 // exist for each argument an implicit conversion sequence
3352 // (13.3.3.1) that converts that argument to the corresponding
3353 // parameter of F.
3354 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003355 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003356 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003357 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003358 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003359 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003360 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003361 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003362 break;
3363 }
3364 } else {
3365 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3366 // argument for which there is no corresponding parameter is
3367 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003368 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003369 }
3370 }
3371}
3372
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003373/// \brief Add overload candidates for overloaded operators that are
3374/// member functions.
3375///
3376/// Add the overloaded operator candidates that are member functions
3377/// for the operator Op that was used in an operator expression such
3378/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3379/// CandidateSet will store the added overload candidates. (C++
3380/// [over.match.oper]).
3381void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3382 SourceLocation OpLoc,
3383 Expr **Args, unsigned NumArgs,
3384 OverloadCandidateSet& CandidateSet,
3385 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003386 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3387
3388 // C++ [over.match.oper]p3:
3389 // For a unary operator @ with an operand of a type whose
3390 // cv-unqualified version is T1, and for a binary operator @ with
3391 // a left operand of a type whose cv-unqualified version is T1 and
3392 // a right operand of a type whose cv-unqualified version is T2,
3393 // three sets of candidate functions, designated member
3394 // candidates, non-member candidates and built-in candidates, are
3395 // constructed as follows:
3396 QualType T1 = Args[0]->getType();
3397 QualType T2;
3398 if (NumArgs > 1)
3399 T2 = Args[1]->getType();
3400
3401 // -- If T1 is a class type, the set of member candidates is the
3402 // result of the qualified lookup of T1::operator@
3403 // (13.3.1.1.1); otherwise, the set of member candidates is
3404 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003405 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003406 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003407 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003408 return;
Mike Stump11289f42009-09-09 15:08:12 +00003409
John McCall27b18f82009-11-17 02:14:36 +00003410 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3411 LookupQualifiedName(Operators, T1Rec->getDecl());
3412 Operators.suppressDiagnostics();
3413
Mike Stump11289f42009-09-09 15:08:12 +00003414 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003415 OperEnd = Operators.end();
3416 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003417 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003418 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003419 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003420 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003421 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003422}
3423
Douglas Gregora11693b2008-11-12 17:17:38 +00003424/// AddBuiltinCandidate - Add a candidate for a built-in
3425/// operator. ResultTy and ParamTys are the result and parameter types
3426/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003427/// arguments being passed to the candidate. IsAssignmentOperator
3428/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003429/// operator. NumContextualBoolArguments is the number of arguments
3430/// (at the beginning of the argument list) that will be contextually
3431/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003432void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003433 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003434 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003435 bool IsAssignmentOperator,
3436 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003437 // Overload resolution is always an unevaluated context.
3438 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3439
Douglas Gregora11693b2008-11-12 17:17:38 +00003440 // Add this candidate
3441 CandidateSet.push_back(OverloadCandidate());
3442 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003443 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003444 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003445 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003446 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003447 Candidate.BuiltinTypes.ResultTy = ResultTy;
3448 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3449 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3450
3451 // Determine the implicit conversion sequences for each of the
3452 // arguments.
3453 Candidate.Viable = true;
3454 Candidate.Conversions.resize(NumArgs);
3455 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003456 // C++ [over.match.oper]p4:
3457 // For the built-in assignment operators, conversions of the
3458 // left operand are restricted as follows:
3459 // -- no temporaries are introduced to hold the left operand, and
3460 // -- no user-defined conversions are applied to the left
3461 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003462 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003463 //
3464 // We block these conversions by turning off user-defined
3465 // conversions, since that is the only way that initialization of
3466 // a reference to a non-class type can occur from something that
3467 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003468 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003469 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003470 "Contextual conversion to bool requires bool type");
3471 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3472 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003473 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003474 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003475 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003476 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003477 }
John McCall0d1da222010-01-12 00:44:57 +00003478 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003479 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003480 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003481 break;
3482 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003483 }
3484}
3485
3486/// BuiltinCandidateTypeSet - A set of types that will be used for the
3487/// candidate operator functions for built-in operators (C++
3488/// [over.built]). The types are separated into pointer types and
3489/// enumeration types.
3490class BuiltinCandidateTypeSet {
3491 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003492 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003493
3494 /// PointerTypes - The set of pointer types that will be used in the
3495 /// built-in candidates.
3496 TypeSet PointerTypes;
3497
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003498 /// MemberPointerTypes - The set of member pointer types that will be
3499 /// used in the built-in candidates.
3500 TypeSet MemberPointerTypes;
3501
Douglas Gregora11693b2008-11-12 17:17:38 +00003502 /// EnumerationTypes - The set of enumeration types that will be
3503 /// used in the built-in candidates.
3504 TypeSet EnumerationTypes;
3505
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003506 /// Sema - The semantic analysis instance where we are building the
3507 /// candidate type set.
3508 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003509
Douglas Gregora11693b2008-11-12 17:17:38 +00003510 /// Context - The AST context in which we will build the type sets.
3511 ASTContext &Context;
3512
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003513 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3514 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003515 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003516
3517public:
3518 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003519 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003520
Mike Stump11289f42009-09-09 15:08:12 +00003521 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003522 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003523
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003524 void AddTypesConvertedFrom(QualType Ty,
3525 SourceLocation Loc,
3526 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003527 bool AllowExplicitConversions,
3528 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003529
3530 /// pointer_begin - First pointer type found;
3531 iterator pointer_begin() { return PointerTypes.begin(); }
3532
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003533 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003534 iterator pointer_end() { return PointerTypes.end(); }
3535
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003536 /// member_pointer_begin - First member pointer type found;
3537 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3538
3539 /// member_pointer_end - Past the last member pointer type found;
3540 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3541
Douglas Gregora11693b2008-11-12 17:17:38 +00003542 /// enumeration_begin - First enumeration type found;
3543 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3544
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003545 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003546 iterator enumeration_end() { return EnumerationTypes.end(); }
3547};
3548
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003549/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003550/// the set of pointer types along with any more-qualified variants of
3551/// that type. For example, if @p Ty is "int const *", this routine
3552/// will add "int const *", "int const volatile *", "int const
3553/// restrict *", and "int const volatile restrict *" to the set of
3554/// pointer types. Returns true if the add of @p Ty itself succeeded,
3555/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003556///
3557/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003558bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003559BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3560 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003561
Douglas Gregora11693b2008-11-12 17:17:38 +00003562 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003563 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003564 return false;
3565
John McCall8ccfcb52009-09-24 19:53:00 +00003566 const PointerType *PointerTy = Ty->getAs<PointerType>();
3567 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003568
John McCall8ccfcb52009-09-24 19:53:00 +00003569 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003570 // Don't add qualified variants of arrays. For one, they're not allowed
3571 // (the qualifier would sink to the element type), and for another, the
3572 // only overload situation where it matters is subscript or pointer +- int,
3573 // and those shouldn't have qualifier variants anyway.
3574 if (PointeeTy->isArrayType())
3575 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003576 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003577 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003578 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003579 bool hasVolatile = VisibleQuals.hasVolatile();
3580 bool hasRestrict = VisibleQuals.hasRestrict();
3581
John McCall8ccfcb52009-09-24 19:53:00 +00003582 // Iterate through all strict supersets of BaseCVR.
3583 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3584 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003585 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3586 // in the types.
3587 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3588 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003589 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3590 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003591 }
3592
3593 return true;
3594}
3595
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003596/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3597/// to the set of pointer types along with any more-qualified variants of
3598/// that type. For example, if @p Ty is "int const *", this routine
3599/// will add "int const *", "int const volatile *", "int const
3600/// restrict *", and "int const volatile restrict *" to the set of
3601/// pointer types. Returns true if the add of @p Ty itself succeeded,
3602/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003603///
3604/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003605bool
3606BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3607 QualType Ty) {
3608 // Insert this type.
3609 if (!MemberPointerTypes.insert(Ty))
3610 return false;
3611
John McCall8ccfcb52009-09-24 19:53:00 +00003612 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3613 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003614
John McCall8ccfcb52009-09-24 19:53:00 +00003615 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003616 // Don't add qualified variants of arrays. For one, they're not allowed
3617 // (the qualifier would sink to the element type), and for another, the
3618 // only overload situation where it matters is subscript or pointer +- int,
3619 // and those shouldn't have qualifier variants anyway.
3620 if (PointeeTy->isArrayType())
3621 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003622 const Type *ClassTy = PointerTy->getClass();
3623
3624 // Iterate through all strict supersets of the pointee type's CVR
3625 // qualifiers.
3626 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3627 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3628 if ((CVR | BaseCVR) != CVR) continue;
3629
3630 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3631 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003632 }
3633
3634 return true;
3635}
3636
Douglas Gregora11693b2008-11-12 17:17:38 +00003637/// AddTypesConvertedFrom - Add each of the types to which the type @p
3638/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003639/// primarily interested in pointer types and enumeration types. We also
3640/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003641/// AllowUserConversions is true if we should look at the conversion
3642/// functions of a class type, and AllowExplicitConversions if we
3643/// should also include the explicit conversion functions of a class
3644/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003645void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003646BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003647 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003648 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003649 bool AllowExplicitConversions,
3650 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003651 // Only deal with canonical types.
3652 Ty = Context.getCanonicalType(Ty);
3653
3654 // Look through reference types; they aren't part of the type of an
3655 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003656 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003657 Ty = RefTy->getPointeeType();
3658
3659 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003660 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003661
Sebastian Redl65ae2002009-11-05 16:36:20 +00003662 // If we're dealing with an array type, decay to the pointer.
3663 if (Ty->isArrayType())
3664 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3665
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003666 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003667 QualType PointeeTy = PointerTy->getPointeeType();
3668
3669 // Insert our type, and its more-qualified variants, into the set
3670 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003671 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003672 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003673 } else if (Ty->isMemberPointerType()) {
3674 // Member pointers are far easier, since the pointee can't be converted.
3675 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3676 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003677 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003678 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003679 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003680 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003681 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003682 // No conversion functions in incomplete types.
3683 return;
3684 }
Mike Stump11289f42009-09-09 15:08:12 +00003685
Douglas Gregora11693b2008-11-12 17:17:38 +00003686 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003687 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003688 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003689 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003690 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003691 NamedDecl *D = I.getDecl();
3692 if (isa<UsingShadowDecl>(D))
3693 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003694
Mike Stump11289f42009-09-09 15:08:12 +00003695 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003696 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003697 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003698 continue;
3699
John McCallda4458e2010-03-31 01:36:47 +00003700 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003701 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003702 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003703 VisibleQuals);
3704 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003705 }
3706 }
3707 }
3708}
3709
Douglas Gregor84605ae2009-08-24 13:43:27 +00003710/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3711/// the volatile- and non-volatile-qualified assignment operators for the
3712/// given type to the candidate set.
3713static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3714 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003715 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003716 unsigned NumArgs,
3717 OverloadCandidateSet &CandidateSet) {
3718 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003719
Douglas Gregor84605ae2009-08-24 13:43:27 +00003720 // T& operator=(T&, T)
3721 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3722 ParamTypes[1] = T;
3723 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3724 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003725
Douglas Gregor84605ae2009-08-24 13:43:27 +00003726 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3727 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003728 ParamTypes[0]
3729 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003730 ParamTypes[1] = T;
3731 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003732 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003733 }
3734}
Mike Stump11289f42009-09-09 15:08:12 +00003735
Sebastian Redl1054fae2009-10-25 17:03:50 +00003736/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3737/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003738static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3739 Qualifiers VRQuals;
3740 const RecordType *TyRec;
3741 if (const MemberPointerType *RHSMPType =
3742 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00003743 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003744 else
3745 TyRec = ArgExpr->getType()->getAs<RecordType>();
3746 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003747 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003748 VRQuals.addVolatile();
3749 VRQuals.addRestrict();
3750 return VRQuals;
3751 }
3752
3753 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003754 if (!ClassDecl->hasDefinition())
3755 return VRQuals;
3756
John McCallad371252010-01-20 00:46:10 +00003757 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003758 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003759
John McCallad371252010-01-20 00:46:10 +00003760 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003761 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003762 NamedDecl *D = I.getDecl();
3763 if (isa<UsingShadowDecl>(D))
3764 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3765 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003766 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3767 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3768 CanTy = ResTypeRef->getPointeeType();
3769 // Need to go down the pointer/mempointer chain and add qualifiers
3770 // as see them.
3771 bool done = false;
3772 while (!done) {
3773 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3774 CanTy = ResTypePtr->getPointeeType();
3775 else if (const MemberPointerType *ResTypeMPtr =
3776 CanTy->getAs<MemberPointerType>())
3777 CanTy = ResTypeMPtr->getPointeeType();
3778 else
3779 done = true;
3780 if (CanTy.isVolatileQualified())
3781 VRQuals.addVolatile();
3782 if (CanTy.isRestrictQualified())
3783 VRQuals.addRestrict();
3784 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3785 return VRQuals;
3786 }
3787 }
3788 }
3789 return VRQuals;
3790}
3791
Douglas Gregord08452f2008-11-19 15:42:04 +00003792/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3793/// operator overloads to the candidate set (C++ [over.built]), based
3794/// on the operator @p Op and the arguments given. For example, if the
3795/// operator is a binary '+', this routine might add "int
3796/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003797void
Mike Stump11289f42009-09-09 15:08:12 +00003798Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003799 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003800 Expr **Args, unsigned NumArgs,
3801 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003802 // The set of "promoted arithmetic types", which are the arithmetic
3803 // types are that preserved by promotion (C++ [over.built]p2). Note
3804 // that the first few of these types are the promoted integral
3805 // types; these types need to be first.
3806 // FIXME: What about complex?
3807 const unsigned FirstIntegralType = 0;
3808 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003809 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003810 LastPromotedIntegralType = 13;
3811 const unsigned FirstPromotedArithmeticType = 7,
3812 LastPromotedArithmeticType = 16;
3813 const unsigned NumArithmeticTypes = 16;
3814 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003815 Context.BoolTy, Context.CharTy, Context.WCharTy,
3816// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003817 Context.SignedCharTy, Context.ShortTy,
3818 Context.UnsignedCharTy, Context.UnsignedShortTy,
3819 Context.IntTy, Context.LongTy, Context.LongLongTy,
3820 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3821 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3822 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003823 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3824 "Invalid first promoted integral type");
3825 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3826 == Context.UnsignedLongLongTy &&
3827 "Invalid last promoted integral type");
3828 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3829 "Invalid first promoted arithmetic type");
3830 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3831 == Context.LongDoubleTy &&
3832 "Invalid last promoted arithmetic type");
3833
Douglas Gregora11693b2008-11-12 17:17:38 +00003834 // Find all of the types that the arguments can convert to, but only
3835 // if the operator we're looking at has built-in operator candidates
3836 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003837 Qualifiers VisibleTypeConversionsQuals;
3838 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003839 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3840 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3841
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003842 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003843 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3844 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003845 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003846 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003847 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003848 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003849 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003850 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003851 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003852 true,
3853 (Op == OO_Exclaim ||
3854 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003855 Op == OO_PipePipe),
3856 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003857 }
3858
3859 bool isComparison = false;
3860 switch (Op) {
3861 case OO_None:
3862 case NUM_OVERLOADED_OPERATORS:
3863 assert(false && "Expected an overloaded operator");
3864 break;
3865
Douglas Gregord08452f2008-11-19 15:42:04 +00003866 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003867 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003868 goto UnaryStar;
3869 else
3870 goto BinaryStar;
3871 break;
3872
3873 case OO_Plus: // '+' is either unary or binary
3874 if (NumArgs == 1)
3875 goto UnaryPlus;
3876 else
3877 goto BinaryPlus;
3878 break;
3879
3880 case OO_Minus: // '-' is either unary or binary
3881 if (NumArgs == 1)
3882 goto UnaryMinus;
3883 else
3884 goto BinaryMinus;
3885 break;
3886
3887 case OO_Amp: // '&' is either unary or binary
3888 if (NumArgs == 1)
3889 goto UnaryAmp;
3890 else
3891 goto BinaryAmp;
3892
3893 case OO_PlusPlus:
3894 case OO_MinusMinus:
3895 // C++ [over.built]p3:
3896 //
3897 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3898 // is either volatile or empty, there exist candidate operator
3899 // functions of the form
3900 //
3901 // VQ T& operator++(VQ T&);
3902 // T operator++(VQ T&, int);
3903 //
3904 // C++ [over.built]p4:
3905 //
3906 // For every pair (T, VQ), where T is an arithmetic type other
3907 // than bool, and VQ is either volatile or empty, there exist
3908 // candidate operator functions of the form
3909 //
3910 // VQ T& operator--(VQ T&);
3911 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003912 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003913 Arith < NumArithmeticTypes; ++Arith) {
3914 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003915 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003916 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003917
3918 // Non-volatile version.
3919 if (NumArgs == 1)
3920 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3921 else
3922 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003923 // heuristic to reduce number of builtin candidates in the set.
3924 // Add volatile version only if there are conversions to a volatile type.
3925 if (VisibleTypeConversionsQuals.hasVolatile()) {
3926 // Volatile version
3927 ParamTypes[0]
3928 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3929 if (NumArgs == 1)
3930 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3931 else
3932 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3933 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003934 }
3935
3936 // C++ [over.built]p5:
3937 //
3938 // For every pair (T, VQ), where T is a cv-qualified or
3939 // cv-unqualified object type, and VQ is either volatile or
3940 // empty, there exist candidate operator functions of the form
3941 //
3942 // T*VQ& operator++(T*VQ&);
3943 // T*VQ& operator--(T*VQ&);
3944 // T* operator++(T*VQ&, int);
3945 // T* operator--(T*VQ&, int);
3946 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3947 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3948 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003949 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003950 continue;
3951
Mike Stump11289f42009-09-09 15:08:12 +00003952 QualType ParamTypes[2] = {
3953 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003954 };
Mike Stump11289f42009-09-09 15:08:12 +00003955
Douglas Gregord08452f2008-11-19 15:42:04 +00003956 // Without volatile
3957 if (NumArgs == 1)
3958 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3959 else
3960 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3961
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003962 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3963 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003964 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003965 ParamTypes[0]
3966 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003967 if (NumArgs == 1)
3968 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3969 else
3970 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3971 }
3972 }
3973 break;
3974
3975 UnaryStar:
3976 // C++ [over.built]p6:
3977 // For every cv-qualified or cv-unqualified object type T, there
3978 // exist candidate operator functions of the form
3979 //
3980 // T& operator*(T*);
3981 //
3982 // C++ [over.built]p7:
3983 // For every function type T, there exist candidate operator
3984 // functions of the form
3985 // T& operator*(T*);
3986 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3987 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3988 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003989 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003990 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003991 &ParamTy, Args, 1, CandidateSet);
3992 }
3993 break;
3994
3995 UnaryPlus:
3996 // C++ [over.built]p8:
3997 // For every type T, there exist candidate operator functions of
3998 // the form
3999 //
4000 // T* operator+(T*);
4001 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4002 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4003 QualType ParamTy = *Ptr;
4004 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4005 }
Mike Stump11289f42009-09-09 15:08:12 +00004006
Douglas Gregord08452f2008-11-19 15:42:04 +00004007 // Fall through
4008
4009 UnaryMinus:
4010 // C++ [over.built]p9:
4011 // For every promoted arithmetic type T, there exist candidate
4012 // operator functions of the form
4013 //
4014 // T operator+(T);
4015 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004016 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004017 Arith < LastPromotedArithmeticType; ++Arith) {
4018 QualType ArithTy = ArithmeticTypes[Arith];
4019 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4020 }
4021 break;
4022
4023 case OO_Tilde:
4024 // C++ [over.built]p10:
4025 // For every promoted integral type T, there exist candidate
4026 // operator functions of the form
4027 //
4028 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004029 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004030 Int < LastPromotedIntegralType; ++Int) {
4031 QualType IntTy = ArithmeticTypes[Int];
4032 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4033 }
4034 break;
4035
Douglas Gregora11693b2008-11-12 17:17:38 +00004036 case OO_New:
4037 case OO_Delete:
4038 case OO_Array_New:
4039 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004040 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004041 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004042 break;
4043
4044 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004045 UnaryAmp:
4046 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004047 // C++ [over.match.oper]p3:
4048 // -- For the operator ',', the unary operator '&', or the
4049 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004050 break;
4051
Douglas Gregor84605ae2009-08-24 13:43:27 +00004052 case OO_EqualEqual:
4053 case OO_ExclaimEqual:
4054 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004055 // For every pointer to member type T, there exist candidate operator
4056 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004057 //
4058 // bool operator==(T,T);
4059 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004060 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004061 MemPtr = CandidateTypes.member_pointer_begin(),
4062 MemPtrEnd = CandidateTypes.member_pointer_end();
4063 MemPtr != MemPtrEnd;
4064 ++MemPtr) {
4065 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4066 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4067 }
Mike Stump11289f42009-09-09 15:08:12 +00004068
Douglas Gregor84605ae2009-08-24 13:43:27 +00004069 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004070
Douglas Gregora11693b2008-11-12 17:17:38 +00004071 case OO_Less:
4072 case OO_Greater:
4073 case OO_LessEqual:
4074 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004075 // C++ [over.built]p15:
4076 //
4077 // For every pointer or enumeration type T, there exist
4078 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004079 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004080 // bool operator<(T, T);
4081 // bool operator>(T, T);
4082 // bool operator<=(T, T);
4083 // bool operator>=(T, T);
4084 // bool operator==(T, T);
4085 // bool operator!=(T, T);
4086 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4087 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4088 QualType ParamTypes[2] = { *Ptr, *Ptr };
4089 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4090 }
Mike Stump11289f42009-09-09 15:08:12 +00004091 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004092 = CandidateTypes.enumeration_begin();
4093 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4094 QualType ParamTypes[2] = { *Enum, *Enum };
4095 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4096 }
4097
4098 // Fall through.
4099 isComparison = true;
4100
Douglas Gregord08452f2008-11-19 15:42:04 +00004101 BinaryPlus:
4102 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004103 if (!isComparison) {
4104 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4105
4106 // C++ [over.built]p13:
4107 //
4108 // For every cv-qualified or cv-unqualified object type T
4109 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004110 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004111 // T* operator+(T*, ptrdiff_t);
4112 // T& operator[](T*, ptrdiff_t); [BELOW]
4113 // T* operator-(T*, ptrdiff_t);
4114 // T* operator+(ptrdiff_t, T*);
4115 // T& operator[](ptrdiff_t, T*); [BELOW]
4116 //
4117 // C++ [over.built]p14:
4118 //
4119 // For every T, where T is a pointer to object type, there
4120 // exist candidate operator functions of the form
4121 //
4122 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004123 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004124 = CandidateTypes.pointer_begin();
4125 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4126 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4127
4128 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4129 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4130
4131 if (Op == OO_Plus) {
4132 // T* operator+(ptrdiff_t, T*);
4133 ParamTypes[0] = ParamTypes[1];
4134 ParamTypes[1] = *Ptr;
4135 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4136 } else {
4137 // ptrdiff_t operator-(T, T);
4138 ParamTypes[1] = *Ptr;
4139 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4140 Args, 2, CandidateSet);
4141 }
4142 }
4143 }
4144 // Fall through
4145
Douglas Gregora11693b2008-11-12 17:17:38 +00004146 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004147 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004148 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004149 // C++ [over.built]p12:
4150 //
4151 // For every pair of promoted arithmetic types L and R, there
4152 // exist candidate operator functions of the form
4153 //
4154 // LR operator*(L, R);
4155 // LR operator/(L, R);
4156 // LR operator+(L, R);
4157 // LR operator-(L, R);
4158 // bool operator<(L, R);
4159 // bool operator>(L, R);
4160 // bool operator<=(L, R);
4161 // bool operator>=(L, R);
4162 // bool operator==(L, R);
4163 // bool operator!=(L, R);
4164 //
4165 // where LR is the result of the usual arithmetic conversions
4166 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004167 //
4168 // C++ [over.built]p24:
4169 //
4170 // For every pair of promoted arithmetic types L and R, there exist
4171 // candidate operator functions of the form
4172 //
4173 // LR operator?(bool, L, R);
4174 //
4175 // where LR is the result of the usual arithmetic conversions
4176 // between types L and R.
4177 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004178 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004179 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004180 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004181 Right < LastPromotedArithmeticType; ++Right) {
4182 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004183 QualType Result
4184 = isComparison
4185 ? Context.BoolTy
4186 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004187 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4188 }
4189 }
4190 break;
4191
4192 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004193 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004194 case OO_Caret:
4195 case OO_Pipe:
4196 case OO_LessLess:
4197 case OO_GreaterGreater:
4198 // C++ [over.built]p17:
4199 //
4200 // For every pair of promoted integral types L and R, there
4201 // exist candidate operator functions of the form
4202 //
4203 // LR operator%(L, R);
4204 // LR operator&(L, R);
4205 // LR operator^(L, R);
4206 // LR operator|(L, R);
4207 // L operator<<(L, R);
4208 // L operator>>(L, R);
4209 //
4210 // where LR is the result of the usual arithmetic conversions
4211 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004212 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004213 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004214 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004215 Right < LastPromotedIntegralType; ++Right) {
4216 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4217 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4218 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004219 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004220 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4221 }
4222 }
4223 break;
4224
4225 case OO_Equal:
4226 // C++ [over.built]p20:
4227 //
4228 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004229 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004230 // empty, there exist candidate operator functions of the form
4231 //
4232 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004233 for (BuiltinCandidateTypeSet::iterator
4234 Enum = CandidateTypes.enumeration_begin(),
4235 EnumEnd = CandidateTypes.enumeration_end();
4236 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004237 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004238 CandidateSet);
4239 for (BuiltinCandidateTypeSet::iterator
4240 MemPtr = CandidateTypes.member_pointer_begin(),
4241 MemPtrEnd = CandidateTypes.member_pointer_end();
4242 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004243 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004244 CandidateSet);
4245 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004246
4247 case OO_PlusEqual:
4248 case OO_MinusEqual:
4249 // C++ [over.built]p19:
4250 //
4251 // For every pair (T, VQ), where T is any type and VQ is either
4252 // volatile or empty, there exist candidate operator functions
4253 // of the form
4254 //
4255 // T*VQ& operator=(T*VQ&, T*);
4256 //
4257 // C++ [over.built]p21:
4258 //
4259 // For every pair (T, VQ), where T is a cv-qualified or
4260 // cv-unqualified object type and VQ is either volatile or
4261 // empty, there exist candidate operator functions of the form
4262 //
4263 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4264 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4265 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4266 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4267 QualType ParamTypes[2];
4268 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4269
4270 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004271 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004272 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4273 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004274
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004275 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4276 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004277 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004278 ParamTypes[0]
4279 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004280 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4281 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004282 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004283 }
4284 // Fall through.
4285
4286 case OO_StarEqual:
4287 case OO_SlashEqual:
4288 // C++ [over.built]p18:
4289 //
4290 // For every triple (L, VQ, R), where L is an arithmetic type,
4291 // VQ is either volatile or empty, and R is a promoted
4292 // arithmetic type, there exist candidate operator functions of
4293 // the form
4294 //
4295 // VQ L& operator=(VQ L&, R);
4296 // VQ L& operator*=(VQ L&, R);
4297 // VQ L& operator/=(VQ L&, R);
4298 // VQ L& operator+=(VQ L&, R);
4299 // VQ L& operator-=(VQ L&, R);
4300 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004301 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004302 Right < LastPromotedArithmeticType; ++Right) {
4303 QualType ParamTypes[2];
4304 ParamTypes[1] = ArithmeticTypes[Right];
4305
4306 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004307 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004308 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4309 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004310
4311 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004312 if (VisibleTypeConversionsQuals.hasVolatile()) {
4313 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4314 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4315 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4316 /*IsAssigmentOperator=*/Op == OO_Equal);
4317 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004318 }
4319 }
4320 break;
4321
4322 case OO_PercentEqual:
4323 case OO_LessLessEqual:
4324 case OO_GreaterGreaterEqual:
4325 case OO_AmpEqual:
4326 case OO_CaretEqual:
4327 case OO_PipeEqual:
4328 // C++ [over.built]p22:
4329 //
4330 // For every triple (L, VQ, R), where L is an integral type, VQ
4331 // is either volatile or empty, and R is a promoted integral
4332 // type, there exist candidate operator functions of the form
4333 //
4334 // VQ L& operator%=(VQ L&, R);
4335 // VQ L& operator<<=(VQ L&, R);
4336 // VQ L& operator>>=(VQ L&, R);
4337 // VQ L& operator&=(VQ L&, R);
4338 // VQ L& operator^=(VQ L&, R);
4339 // VQ L& operator|=(VQ L&, R);
4340 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004341 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004342 Right < LastPromotedIntegralType; ++Right) {
4343 QualType ParamTypes[2];
4344 ParamTypes[1] = ArithmeticTypes[Right];
4345
4346 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004347 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004348 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004349 if (VisibleTypeConversionsQuals.hasVolatile()) {
4350 // Add this built-in operator as a candidate (VQ is 'volatile').
4351 ParamTypes[0] = ArithmeticTypes[Left];
4352 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4353 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4354 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4355 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004356 }
4357 }
4358 break;
4359
Douglas Gregord08452f2008-11-19 15:42:04 +00004360 case OO_Exclaim: {
4361 // C++ [over.operator]p23:
4362 //
4363 // There also exist candidate operator functions of the form
4364 //
Mike Stump11289f42009-09-09 15:08:12 +00004365 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004366 // bool operator&&(bool, bool); [BELOW]
4367 // bool operator||(bool, bool); [BELOW]
4368 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004369 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4370 /*IsAssignmentOperator=*/false,
4371 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004372 break;
4373 }
4374
Douglas Gregora11693b2008-11-12 17:17:38 +00004375 case OO_AmpAmp:
4376 case OO_PipePipe: {
4377 // C++ [over.operator]p23:
4378 //
4379 // There also exist candidate operator functions of the form
4380 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004381 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004382 // bool operator&&(bool, bool);
4383 // bool operator||(bool, bool);
4384 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004385 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4386 /*IsAssignmentOperator=*/false,
4387 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004388 break;
4389 }
4390
4391 case OO_Subscript:
4392 // C++ [over.built]p13:
4393 //
4394 // For every cv-qualified or cv-unqualified object type T there
4395 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004396 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004397 // T* operator+(T*, ptrdiff_t); [ABOVE]
4398 // T& operator[](T*, ptrdiff_t);
4399 // T* operator-(T*, ptrdiff_t); [ABOVE]
4400 // T* operator+(ptrdiff_t, T*); [ABOVE]
4401 // T& operator[](ptrdiff_t, T*);
4402 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4403 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4404 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004405 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004406 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004407
4408 // T& operator[](T*, ptrdiff_t)
4409 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4410
4411 // T& operator[](ptrdiff_t, T*);
4412 ParamTypes[0] = ParamTypes[1];
4413 ParamTypes[1] = *Ptr;
4414 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4415 }
4416 break;
4417
4418 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004419 // C++ [over.built]p11:
4420 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4421 // C1 is the same type as C2 or is a derived class of C2, T is an object
4422 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4423 // there exist candidate operator functions of the form
4424 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4425 // where CV12 is the union of CV1 and CV2.
4426 {
4427 for (BuiltinCandidateTypeSet::iterator Ptr =
4428 CandidateTypes.pointer_begin();
4429 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4430 QualType C1Ty = (*Ptr);
4431 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004432 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004433 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004434 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004435 if (!isa<RecordType>(C1))
4436 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004437 // heuristic to reduce number of builtin candidates in the set.
4438 // Add volatile/restrict version only if there are conversions to a
4439 // volatile/restrict type.
4440 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4441 continue;
4442 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4443 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004444 }
4445 for (BuiltinCandidateTypeSet::iterator
4446 MemPtr = CandidateTypes.member_pointer_begin(),
4447 MemPtrEnd = CandidateTypes.member_pointer_end();
4448 MemPtr != MemPtrEnd; ++MemPtr) {
4449 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4450 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004451 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004452 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4453 break;
4454 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4455 // build CV12 T&
4456 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004457 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4458 T.isVolatileQualified())
4459 continue;
4460 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4461 T.isRestrictQualified())
4462 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004463 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004464 QualType ResultTy = Context.getLValueReferenceType(T);
4465 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4466 }
4467 }
4468 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004469 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004470
4471 case OO_Conditional:
4472 // Note that we don't consider the first argument, since it has been
4473 // contextually converted to bool long ago. The candidates below are
4474 // therefore added as binary.
4475 //
4476 // C++ [over.built]p24:
4477 // For every type T, where T is a pointer or pointer-to-member type,
4478 // there exist candidate operator functions of the form
4479 //
4480 // T operator?(bool, T, T);
4481 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004482 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4483 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4484 QualType ParamTypes[2] = { *Ptr, *Ptr };
4485 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4486 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004487 for (BuiltinCandidateTypeSet::iterator Ptr =
4488 CandidateTypes.member_pointer_begin(),
4489 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4490 QualType ParamTypes[2] = { *Ptr, *Ptr };
4491 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4492 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004493 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004494 }
4495}
4496
Douglas Gregore254f902009-02-04 00:32:51 +00004497/// \brief Add function candidates found via argument-dependent lookup
4498/// to the set of overloading candidates.
4499///
4500/// This routine performs argument-dependent name lookup based on the
4501/// given function name (which may also be an operator name) and adds
4502/// all of the overload candidates found by ADL to the overload
4503/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004504void
Douglas Gregore254f902009-02-04 00:32:51 +00004505Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004506 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004507 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004508 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004509 OverloadCandidateSet& CandidateSet,
4510 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004511 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004512
John McCall91f61fc2010-01-26 06:04:06 +00004513 // FIXME: This approach for uniquing ADL results (and removing
4514 // redundant candidates from the set) relies on pointer-equality,
4515 // which means we need to key off the canonical decl. However,
4516 // always going back to the canonical decl might not get us the
4517 // right set of default arguments. What default arguments are
4518 // we supposed to consider on ADL candidates, anyway?
4519
Douglas Gregorcabea402009-09-22 15:41:20 +00004520 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004521 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004522
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004523 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004524 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4525 CandEnd = CandidateSet.end();
4526 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004527 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004528 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004529 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004530 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004531 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004532
4533 // For each of the ADL candidates we found, add it to the overload
4534 // set.
John McCall8fe68082010-01-26 07:16:45 +00004535 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004536 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004537 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004538 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004539 continue;
4540
John McCalla0296f72010-03-19 07:35:19 +00004541 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004542 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004543 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004544 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004545 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004546 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004547 }
Douglas Gregore254f902009-02-04 00:32:51 +00004548}
4549
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004550/// isBetterOverloadCandidate - Determines whether the first overload
4551/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004552bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004553Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004554 const OverloadCandidate& Cand2,
4555 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004556 // Define viable functions to be better candidates than non-viable
4557 // functions.
4558 if (!Cand2.Viable)
4559 return Cand1.Viable;
4560 else if (!Cand1.Viable)
4561 return false;
4562
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004563 // C++ [over.match.best]p1:
4564 //
4565 // -- if F is a static member function, ICS1(F) is defined such
4566 // that ICS1(F) is neither better nor worse than ICS1(G) for
4567 // any function G, and, symmetrically, ICS1(G) is neither
4568 // better nor worse than ICS1(F).
4569 unsigned StartArg = 0;
4570 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4571 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004572
Douglas Gregord3cb3562009-07-07 23:38:56 +00004573 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004574 // A viable function F1 is defined to be a better function than another
4575 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004576 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004577 unsigned NumArgs = Cand1.Conversions.size();
4578 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4579 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004580 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004581 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4582 Cand2.Conversions[ArgIdx])) {
4583 case ImplicitConversionSequence::Better:
4584 // Cand1 has a better conversion sequence.
4585 HasBetterConversion = true;
4586 break;
4587
4588 case ImplicitConversionSequence::Worse:
4589 // Cand1 can't be better than Cand2.
4590 return false;
4591
4592 case ImplicitConversionSequence::Indistinguishable:
4593 // Do nothing.
4594 break;
4595 }
4596 }
4597
Mike Stump11289f42009-09-09 15:08:12 +00004598 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004599 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004600 if (HasBetterConversion)
4601 return true;
4602
Mike Stump11289f42009-09-09 15:08:12 +00004603 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004604 // specialization, or, if not that,
4605 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4606 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4607 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004608
4609 // -- F1 and F2 are function template specializations, and the function
4610 // template for F1 is more specialized than the template for F2
4611 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004612 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004613 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4614 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004615 if (FunctionTemplateDecl *BetterTemplate
4616 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4617 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004618 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004619 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4620 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004621 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004622
Douglas Gregora1f013e2008-11-07 22:36:19 +00004623 // -- the context is an initialization by user-defined conversion
4624 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4625 // from the return type of F1 to the destination type (i.e.,
4626 // the type of the entity being initialized) is a better
4627 // conversion sequence than the standard conversion sequence
4628 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004629 if (Cand1.Function && Cand2.Function &&
4630 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004631 isa<CXXConversionDecl>(Cand2.Function)) {
4632 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4633 Cand2.FinalConversion)) {
4634 case ImplicitConversionSequence::Better:
4635 // Cand1 has a better conversion sequence.
4636 return true;
4637
4638 case ImplicitConversionSequence::Worse:
4639 // Cand1 can't be better than Cand2.
4640 return false;
4641
4642 case ImplicitConversionSequence::Indistinguishable:
4643 // Do nothing
4644 break;
4645 }
4646 }
4647
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004648 return false;
4649}
4650
Mike Stump11289f42009-09-09 15:08:12 +00004651/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004652/// within an overload candidate set.
4653///
4654/// \param CandidateSet the set of candidate functions.
4655///
4656/// \param Loc the location of the function name (or operator symbol) for
4657/// which overload resolution occurs.
4658///
Mike Stump11289f42009-09-09 15:08:12 +00004659/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004660/// function, Best points to the candidate function found.
4661///
4662/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004663OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4664 SourceLocation Loc,
4665 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004666 // Find the best viable function.
4667 Best = CandidateSet.end();
4668 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4669 Cand != CandidateSet.end(); ++Cand) {
4670 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004671 if (Best == CandidateSet.end() ||
4672 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004673 Best = Cand;
4674 }
4675 }
4676
4677 // If we didn't find any viable functions, abort.
4678 if (Best == CandidateSet.end())
4679 return OR_No_Viable_Function;
4680
4681 // Make sure that this function is better than every other viable
4682 // function. If not, we have an ambiguity.
4683 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4684 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004685 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004686 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004687 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004688 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004689 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004690 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004691 }
Mike Stump11289f42009-09-09 15:08:12 +00004692
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004693 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004694 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004695 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004696 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004697 return OR_Deleted;
4698
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004699 // C++ [basic.def.odr]p2:
4700 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004701 // when referred to from a potentially-evaluated expression. [Note: this
4702 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004703 // (clause 13), user-defined conversions (12.3.2), allocation function for
4704 // placement new (5.3.4), as well as non-default initialization (8.5).
4705 if (Best->Function)
4706 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004707 return OR_Success;
4708}
4709
John McCall53262c92010-01-12 02:15:36 +00004710namespace {
4711
4712enum OverloadCandidateKind {
4713 oc_function,
4714 oc_method,
4715 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004716 oc_function_template,
4717 oc_method_template,
4718 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004719 oc_implicit_default_constructor,
4720 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004721 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004722};
4723
John McCalle1ac8d12010-01-13 00:25:19 +00004724OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4725 FunctionDecl *Fn,
4726 std::string &Description) {
4727 bool isTemplate = false;
4728
4729 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4730 isTemplate = true;
4731 Description = S.getTemplateArgumentBindingsText(
4732 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4733 }
John McCallfd0b2f82010-01-06 09:43:14 +00004734
4735 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004736 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004737 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004738
John McCall53262c92010-01-12 02:15:36 +00004739 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4740 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004741 }
4742
4743 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4744 // This actually gets spelled 'candidate function' for now, but
4745 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004746 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004747 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004748
4749 assert(Meth->isCopyAssignment()
4750 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004751 return oc_implicit_copy_assignment;
4752 }
4753
John McCalle1ac8d12010-01-13 00:25:19 +00004754 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004755}
4756
4757} // end anonymous namespace
4758
4759// Notes the location of an overload candidate.
4760void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004761 std::string FnDesc;
4762 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4763 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4764 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004765}
4766
John McCall0d1da222010-01-12 00:44:57 +00004767/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4768/// "lead" diagnostic; it will be given two arguments, the source and
4769/// target types of the conversion.
4770void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4771 SourceLocation CaretLoc,
4772 const PartialDiagnostic &PDiag) {
4773 Diag(CaretLoc, PDiag)
4774 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4775 for (AmbiguousConversionSequence::const_iterator
4776 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4777 NoteOverloadCandidate(*I);
4778 }
John McCall12f97bc2010-01-08 04:41:39 +00004779}
4780
John McCall0d1da222010-01-12 00:44:57 +00004781namespace {
4782
John McCall6a61b522010-01-13 09:16:55 +00004783void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4784 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4785 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004786 assert(Cand->Function && "for now, candidate must be a function");
4787 FunctionDecl *Fn = Cand->Function;
4788
4789 // There's a conversion slot for the object argument if this is a
4790 // non-constructor method. Note that 'I' corresponds the
4791 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004792 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004793 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004794 if (I == 0)
4795 isObjectArgument = true;
4796 else
4797 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004798 }
4799
John McCalle1ac8d12010-01-13 00:25:19 +00004800 std::string FnDesc;
4801 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4802
John McCall6a61b522010-01-13 09:16:55 +00004803 Expr *FromExpr = Conv.Bad.FromExpr;
4804 QualType FromTy = Conv.Bad.getFromType();
4805 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004806
John McCallfb7ad0f2010-02-02 02:42:52 +00004807 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004808 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004809 Expr *E = FromExpr->IgnoreParens();
4810 if (isa<UnaryOperator>(E))
4811 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004812 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004813
4814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4815 << (unsigned) FnKind << FnDesc
4816 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4817 << ToTy << Name << I+1;
4818 return;
4819 }
4820
John McCall6d174642010-01-23 08:10:49 +00004821 // Do some hand-waving analysis to see if the non-viability is due
4822 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004823 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4824 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4825 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4826 CToTy = RT->getPointeeType();
4827 else {
4828 // TODO: detect and diagnose the full richness of const mismatches.
4829 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4830 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4831 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4832 }
4833
4834 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4835 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4836 // It is dumb that we have to do this here.
4837 while (isa<ArrayType>(CFromTy))
4838 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4839 while (isa<ArrayType>(CToTy))
4840 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4841
4842 Qualifiers FromQs = CFromTy.getQualifiers();
4843 Qualifiers ToQs = CToTy.getQualifiers();
4844
4845 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4846 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4847 << (unsigned) FnKind << FnDesc
4848 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4849 << FromTy
4850 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4851 << (unsigned) isObjectArgument << I+1;
4852 return;
4853 }
4854
4855 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4856 assert(CVR && "unexpected qualifiers mismatch");
4857
4858 if (isObjectArgument) {
4859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4860 << (unsigned) FnKind << FnDesc
4861 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4862 << FromTy << (CVR - 1);
4863 } else {
4864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4865 << (unsigned) FnKind << FnDesc
4866 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4867 << FromTy << (CVR - 1) << I+1;
4868 }
4869 return;
4870 }
4871
John McCall6d174642010-01-23 08:10:49 +00004872 // Diagnose references or pointers to incomplete types differently,
4873 // since it's far from impossible that the incompleteness triggered
4874 // the failure.
4875 QualType TempFromTy = FromTy.getNonReferenceType();
4876 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4877 TempFromTy = PTy->getPointeeType();
4878 if (TempFromTy->isIncompleteType()) {
4879 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4880 << (unsigned) FnKind << FnDesc
4881 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4882 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4883 return;
4884 }
4885
John McCall47000992010-01-14 03:28:57 +00004886 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4888 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004889 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004890 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004891}
4892
4893void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4894 unsigned NumFormalArgs) {
4895 // TODO: treat calls to a missing default constructor as a special case
4896
4897 FunctionDecl *Fn = Cand->Function;
4898 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4899
4900 unsigned MinParams = Fn->getMinRequiredArguments();
4901
4902 // at least / at most / exactly
4903 unsigned mode, modeCount;
4904 if (NumFormalArgs < MinParams) {
4905 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4906 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4907 mode = 0; // "at least"
4908 else
4909 mode = 2; // "exactly"
4910 modeCount = MinParams;
4911 } else {
4912 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4913 if (MinParams != FnTy->getNumArgs())
4914 mode = 1; // "at most"
4915 else
4916 mode = 2; // "exactly"
4917 modeCount = FnTy->getNumArgs();
4918 }
4919
4920 std::string Description;
4921 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4922
4923 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4924 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004925}
4926
John McCall8b9ed552010-02-01 18:53:26 +00004927/// Diagnose a failed template-argument deduction.
4928void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4929 Expr **Args, unsigned NumArgs) {
4930 FunctionDecl *Fn = Cand->Function; // pattern
4931
4932 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4933 Cand->DeductionFailure.TemplateParameter);
4934
4935 switch (Cand->DeductionFailure.Result) {
4936 case Sema::TDK_Success:
4937 llvm_unreachable("TDK_success while diagnosing bad deduction");
4938
4939 case Sema::TDK_Incomplete: {
4940 NamedDecl *ParamD;
4941 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4942 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4943 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4944 assert(ParamD && "no parameter found for incomplete deduction result");
4945 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4946 << ParamD->getDeclName();
4947 return;
4948 }
4949
4950 // TODO: diagnose these individually, then kill off
4951 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4952 case Sema::TDK_InstantiationDepth:
4953 case Sema::TDK_Inconsistent:
4954 case Sema::TDK_InconsistentQuals:
4955 case Sema::TDK_SubstitutionFailure:
4956 case Sema::TDK_NonDeducedMismatch:
4957 case Sema::TDK_TooManyArguments:
4958 case Sema::TDK_TooFewArguments:
4959 case Sema::TDK_InvalidExplicitArguments:
4960 case Sema::TDK_FailedOverloadResolution:
4961 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4962 return;
4963 }
4964}
4965
4966/// Generates a 'note' diagnostic for an overload candidate. We've
4967/// already generated a primary error at the call site.
4968///
4969/// It really does need to be a single diagnostic with its caret
4970/// pointed at the candidate declaration. Yes, this creates some
4971/// major challenges of technical writing. Yes, this makes pointing
4972/// out problems with specific arguments quite awkward. It's still
4973/// better than generating twenty screens of text for every failed
4974/// overload.
4975///
4976/// It would be great to be able to express per-candidate problems
4977/// more richly for those diagnostic clients that cared, but we'd
4978/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004979void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4980 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004981 FunctionDecl *Fn = Cand->Function;
4982
John McCall12f97bc2010-01-08 04:41:39 +00004983 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004984 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004985 std::string FnDesc;
4986 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004987
4988 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004989 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004990 return;
John McCall12f97bc2010-01-08 04:41:39 +00004991 }
4992
John McCalle1ac8d12010-01-13 00:25:19 +00004993 // We don't really have anything else to say about viable candidates.
4994 if (Cand->Viable) {
4995 S.NoteOverloadCandidate(Fn);
4996 return;
4997 }
John McCall0d1da222010-01-12 00:44:57 +00004998
John McCall6a61b522010-01-13 09:16:55 +00004999 switch (Cand->FailureKind) {
5000 case ovl_fail_too_many_arguments:
5001 case ovl_fail_too_few_arguments:
5002 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005003
John McCall6a61b522010-01-13 09:16:55 +00005004 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005005 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5006
John McCallfe796dd2010-01-23 05:17:32 +00005007 case ovl_fail_trivial_conversion:
5008 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005009 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005010 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005011
John McCall65eb8792010-02-25 01:37:24 +00005012 case ovl_fail_bad_conversion: {
5013 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5014 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005015 if (Cand->Conversions[I].isBad())
5016 return DiagnoseBadConversion(S, Cand, I);
5017
5018 // FIXME: this currently happens when we're called from SemaInit
5019 // when user-conversion overload fails. Figure out how to handle
5020 // those conditions and diagnose them well.
5021 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005022 }
John McCall65eb8792010-02-25 01:37:24 +00005023 }
John McCalld3224162010-01-08 00:58:21 +00005024}
5025
5026void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5027 // Desugar the type of the surrogate down to a function type,
5028 // retaining as many typedefs as possible while still showing
5029 // the function type (and, therefore, its parameter types).
5030 QualType FnType = Cand->Surrogate->getConversionType();
5031 bool isLValueReference = false;
5032 bool isRValueReference = false;
5033 bool isPointer = false;
5034 if (const LValueReferenceType *FnTypeRef =
5035 FnType->getAs<LValueReferenceType>()) {
5036 FnType = FnTypeRef->getPointeeType();
5037 isLValueReference = true;
5038 } else if (const RValueReferenceType *FnTypeRef =
5039 FnType->getAs<RValueReferenceType>()) {
5040 FnType = FnTypeRef->getPointeeType();
5041 isRValueReference = true;
5042 }
5043 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5044 FnType = FnTypePtr->getPointeeType();
5045 isPointer = true;
5046 }
5047 // Desugar down to a function type.
5048 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5049 // Reconstruct the pointer/reference as appropriate.
5050 if (isPointer) FnType = S.Context.getPointerType(FnType);
5051 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5052 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5053
5054 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5055 << FnType;
5056}
5057
5058void NoteBuiltinOperatorCandidate(Sema &S,
5059 const char *Opc,
5060 SourceLocation OpLoc,
5061 OverloadCandidate *Cand) {
5062 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5063 std::string TypeStr("operator");
5064 TypeStr += Opc;
5065 TypeStr += "(";
5066 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5067 if (Cand->Conversions.size() == 1) {
5068 TypeStr += ")";
5069 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5070 } else {
5071 TypeStr += ", ";
5072 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5073 TypeStr += ")";
5074 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5075 }
5076}
5077
5078void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5079 OverloadCandidate *Cand) {
5080 unsigned NoOperands = Cand->Conversions.size();
5081 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5082 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005083 if (ICS.isBad()) break; // all meaningless after first invalid
5084 if (!ICS.isAmbiguous()) continue;
5085
5086 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005087 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005088 }
5089}
5090
John McCall3712d9e2010-01-15 23:32:50 +00005091SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5092 if (Cand->Function)
5093 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005094 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005095 return Cand->Surrogate->getLocation();
5096 return SourceLocation();
5097}
5098
John McCallad2587a2010-01-12 00:48:53 +00005099struct CompareOverloadCandidatesForDisplay {
5100 Sema &S;
5101 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005102
5103 bool operator()(const OverloadCandidate *L,
5104 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005105 // Fast-path this check.
5106 if (L == R) return false;
5107
John McCall12f97bc2010-01-08 04:41:39 +00005108 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005109 if (L->Viable) {
5110 if (!R->Viable) return true;
5111
5112 // TODO: introduce a tri-valued comparison for overload
5113 // candidates. Would be more worthwhile if we had a sort
5114 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005115 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5116 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005117 } else if (R->Viable)
5118 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005119
John McCall3712d9e2010-01-15 23:32:50 +00005120 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005121
John McCall3712d9e2010-01-15 23:32:50 +00005122 // Criteria by which we can sort non-viable candidates:
5123 if (!L->Viable) {
5124 // 1. Arity mismatches come after other candidates.
5125 if (L->FailureKind == ovl_fail_too_many_arguments ||
5126 L->FailureKind == ovl_fail_too_few_arguments)
5127 return false;
5128 if (R->FailureKind == ovl_fail_too_many_arguments ||
5129 R->FailureKind == ovl_fail_too_few_arguments)
5130 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005131
John McCallfe796dd2010-01-23 05:17:32 +00005132 // 2. Bad conversions come first and are ordered by the number
5133 // of bad conversions and quality of good conversions.
5134 if (L->FailureKind == ovl_fail_bad_conversion) {
5135 if (R->FailureKind != ovl_fail_bad_conversion)
5136 return true;
5137
5138 // If there's any ordering between the defined conversions...
5139 // FIXME: this might not be transitive.
5140 assert(L->Conversions.size() == R->Conversions.size());
5141
5142 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005143 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5144 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005145 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5146 R->Conversions[I])) {
5147 case ImplicitConversionSequence::Better:
5148 leftBetter++;
5149 break;
5150
5151 case ImplicitConversionSequence::Worse:
5152 leftBetter--;
5153 break;
5154
5155 case ImplicitConversionSequence::Indistinguishable:
5156 break;
5157 }
5158 }
5159 if (leftBetter > 0) return true;
5160 if (leftBetter < 0) return false;
5161
5162 } else if (R->FailureKind == ovl_fail_bad_conversion)
5163 return false;
5164
John McCall3712d9e2010-01-15 23:32:50 +00005165 // TODO: others?
5166 }
5167
5168 // Sort everything else by location.
5169 SourceLocation LLoc = GetLocationForCandidate(L);
5170 SourceLocation RLoc = GetLocationForCandidate(R);
5171
5172 // Put candidates without locations (e.g. builtins) at the end.
5173 if (LLoc.isInvalid()) return false;
5174 if (RLoc.isInvalid()) return true;
5175
5176 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005177 }
5178};
5179
John McCallfe796dd2010-01-23 05:17:32 +00005180/// CompleteNonViableCandidate - Normally, overload resolution only
5181/// computes up to the first
5182void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5183 Expr **Args, unsigned NumArgs) {
5184 assert(!Cand->Viable);
5185
5186 // Don't do anything on failures other than bad conversion.
5187 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5188
5189 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005190 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005191 unsigned ConvCount = Cand->Conversions.size();
5192 while (true) {
5193 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5194 ConvIdx++;
5195 if (Cand->Conversions[ConvIdx - 1].isBad())
5196 break;
5197 }
5198
5199 if (ConvIdx == ConvCount)
5200 return;
5201
John McCall65eb8792010-02-25 01:37:24 +00005202 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5203 "remaining conversion is initialized?");
5204
Douglas Gregoradc7a702010-04-16 17:45:54 +00005205 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005206 // operation somehow.
5207 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005208
5209 const FunctionProtoType* Proto;
5210 unsigned ArgIdx = ConvIdx;
5211
5212 if (Cand->IsSurrogate) {
5213 QualType ConvType
5214 = Cand->Surrogate->getConversionType().getNonReferenceType();
5215 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5216 ConvType = ConvPtrType->getPointeeType();
5217 Proto = ConvType->getAs<FunctionProtoType>();
5218 ArgIdx--;
5219 } else if (Cand->Function) {
5220 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5221 if (isa<CXXMethodDecl>(Cand->Function) &&
5222 !isa<CXXConstructorDecl>(Cand->Function))
5223 ArgIdx--;
5224 } else {
5225 // Builtin binary operator with a bad first conversion.
5226 assert(ConvCount <= 3);
5227 for (; ConvIdx != ConvCount; ++ConvIdx)
5228 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005229 = TryCopyInitialization(S, Args[ConvIdx],
5230 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5231 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005232 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005233 return;
5234 }
5235
5236 // Fill in the rest of the conversions.
5237 unsigned NumArgsInProto = Proto->getNumArgs();
5238 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5239 if (ArgIdx < NumArgsInProto)
5240 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005241 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5242 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005243 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005244 else
5245 Cand->Conversions[ConvIdx].setEllipsis();
5246 }
5247}
5248
John McCalld3224162010-01-08 00:58:21 +00005249} // end anonymous namespace
5250
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005251/// PrintOverloadCandidates - When overload resolution fails, prints
5252/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005253/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005254void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005255Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005256 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005257 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005258 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005259 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005260 // Sort the candidates by viability and position. Sorting directly would
5261 // be prohibitive, so we make a set of pointers and sort those.
5262 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5263 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5264 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5265 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005266 Cand != LastCand; ++Cand) {
5267 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005268 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005269 else if (OCD == OCD_AllCandidates) {
5270 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5271 Cands.push_back(Cand);
5272 }
5273 }
5274
John McCallad2587a2010-01-12 00:48:53 +00005275 std::sort(Cands.begin(), Cands.end(),
5276 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005277
John McCall0d1da222010-01-12 00:44:57 +00005278 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005279
John McCall12f97bc2010-01-08 04:41:39 +00005280 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5281 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5282 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005283
John McCalld3224162010-01-08 00:58:21 +00005284 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005285 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005286 else if (Cand->IsSurrogate)
5287 NoteSurrogateCandidate(*this, Cand);
5288
5289 // This a builtin candidate. We do not, in general, want to list
5290 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005291 else if (Cand->Viable) {
5292 // Generally we only see ambiguities including viable builtin
5293 // operators if overload resolution got screwed up by an
5294 // ambiguous user-defined conversion.
5295 //
5296 // FIXME: It's quite possible for different conversions to see
5297 // different ambiguities, though.
5298 if (!ReportedAmbiguousConversions) {
5299 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5300 ReportedAmbiguousConversions = true;
5301 }
John McCalld3224162010-01-08 00:58:21 +00005302
John McCall0d1da222010-01-12 00:44:57 +00005303 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005304 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005305 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005306 }
5307}
5308
John McCalla0296f72010-03-19 07:35:19 +00005309static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005310 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005311 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005312
John McCalla0296f72010-03-19 07:35:19 +00005313 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005314}
5315
Douglas Gregorcd695e52008-11-10 20:40:00 +00005316/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5317/// an overloaded function (C++ [over.over]), where @p From is an
5318/// expression with overloaded function type and @p ToType is the type
5319/// we're trying to resolve to. For example:
5320///
5321/// @code
5322/// int f(double);
5323/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005324///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005325/// int (*pfd)(double) = f; // selects f(double)
5326/// @endcode
5327///
5328/// This routine returns the resulting FunctionDecl if it could be
5329/// resolved, and NULL otherwise. When @p Complain is true, this
5330/// routine will emit diagnostics if there is an error.
5331FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005332Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005333 bool Complain,
5334 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005335 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005336 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005337 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005338 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005339 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005340 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005341 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005342 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005343 FunctionType = MemTypePtr->getPointeeType();
5344 IsMember = true;
5345 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005346
Douglas Gregorcd695e52008-11-10 20:40:00 +00005347 // C++ [over.over]p1:
5348 // [...] [Note: any redundant set of parentheses surrounding the
5349 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005350 // C++ [over.over]p1:
5351 // [...] The overloaded function name can be preceded by the &
5352 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005353 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5354 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5355 if (OvlExpr->hasExplicitTemplateArgs()) {
5356 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5357 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005358 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005359
5360 // We expect a pointer or reference to function, or a function pointer.
5361 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5362 if (!FunctionType->isFunctionType()) {
5363 if (Complain)
5364 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5365 << OvlExpr->getName() << ToType;
5366
5367 return 0;
5368 }
5369
5370 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005371
Douglas Gregorcd695e52008-11-10 20:40:00 +00005372 // Look through all of the overloaded functions, searching for one
5373 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005374 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005375 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5376
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005377 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005378 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5379 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005380 // Look through any using declarations to find the underlying function.
5381 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5382
Douglas Gregorcd695e52008-11-10 20:40:00 +00005383 // C++ [over.over]p3:
5384 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005385 // targets of type "pointer-to-function" or "reference-to-function."
5386 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005387 // type "pointer-to-member-function."
5388 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005389
Mike Stump11289f42009-09-09 15:08:12 +00005390 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005391 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005392 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005393 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005394 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005395 // static when converting to member pointer.
5396 if (Method->isStatic() == IsMember)
5397 continue;
5398 } else if (IsMember)
5399 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005400
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005401 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005402 // If the name is a function template, template argument deduction is
5403 // done (14.8.2.2), and if the argument deduction succeeds, the
5404 // resulting template argument list is used to generate a single
5405 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005406 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005407 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005408 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005409 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005410 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005411 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005412 FunctionType, Specialization, Info)) {
5413 // FIXME: make a note of the failed deduction for diagnostics.
5414 (void)Result;
5415 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005416 // FIXME: If the match isn't exact, shouldn't we just drop this as
5417 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005418 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005419 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005420 Matches.push_back(std::make_pair(I.getPair(),
5421 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005422 }
John McCalld14a8642009-11-21 08:51:07 +00005423
5424 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005425 }
Mike Stump11289f42009-09-09 15:08:12 +00005426
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005427 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005428 // Skip non-static functions when converting to pointer, and static
5429 // when converting to member pointer.
5430 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005431 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005432
5433 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005434 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005435 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005436 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005437 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005438
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005439 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005440 QualType ResultTy;
5441 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5442 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5443 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005444 Matches.push_back(std::make_pair(I.getPair(),
5445 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005446 FoundNonTemplateFunction = true;
5447 }
Mike Stump11289f42009-09-09 15:08:12 +00005448 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005449 }
5450
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005451 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005452 if (Matches.empty()) {
5453 if (Complain) {
5454 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5455 << OvlExpr->getName() << FunctionType;
5456 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5457 E = OvlExpr->decls_end();
5458 I != E; ++I)
5459 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5460 NoteOverloadCandidate(F);
5461 }
5462
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005463 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005464 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005465 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005466 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005467 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005468 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005469 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005470 return Result;
5471 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005472
5473 // C++ [over.over]p4:
5474 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005475 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005476 // [...] and any given function template specialization F1 is
5477 // eliminated if the set contains a second function template
5478 // specialization whose function template is more specialized
5479 // than the function template of F1 according to the partial
5480 // ordering rules of 14.5.5.2.
5481
5482 // The algorithm specified above is quadratic. We instead use a
5483 // two-pass algorithm (similar to the one used to identify the
5484 // best viable function in an overload set) that identifies the
5485 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005486
5487 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5488 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5489 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005490
5491 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005492 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005493 TPOC_Other, From->getLocStart(),
5494 PDiag(),
5495 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005496 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005497 PDiag(diag::note_ovl_candidate)
5498 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005499 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005500 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005501 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005502 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005503 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005504 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5505 }
John McCall58cc69d2010-01-27 01:50:18 +00005506 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005507 }
Mike Stump11289f42009-09-09 15:08:12 +00005508
Douglas Gregorfae1d712009-09-26 03:56:17 +00005509 // [...] any function template specializations in the set are
5510 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005511 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005512 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005513 ++I;
5514 else {
John McCalla0296f72010-03-19 07:35:19 +00005515 Matches[I] = Matches[--N];
5516 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005517 }
5518 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005519
Mike Stump11289f42009-09-09 15:08:12 +00005520 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005521 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005522 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005523 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005524 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005525 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00005526 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00005527 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5528 }
John McCalla0296f72010-03-19 07:35:19 +00005529 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005530 }
Mike Stump11289f42009-09-09 15:08:12 +00005531
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005532 // FIXME: We should probably return the same thing that BestViableFunction
5533 // returns (even if we issue the diagnostics here).
5534 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005535 << Matches[0].second->getDeclName();
5536 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5537 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005538 return 0;
5539}
5540
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005541/// \brief Given an expression that refers to an overloaded function, try to
5542/// resolve that overloaded function expression down to a single function.
5543///
5544/// This routine can only resolve template-ids that refer to a single function
5545/// template, where that template-id refers to a single template whose template
5546/// arguments are either provided by the template-id or have defaults,
5547/// as described in C++0x [temp.arg.explicit]p3.
5548FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5549 // C++ [over.over]p1:
5550 // [...] [Note: any redundant set of parentheses surrounding the
5551 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005552 // C++ [over.over]p1:
5553 // [...] The overloaded function name can be preceded by the &
5554 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005555
5556 if (From->getType() != Context.OverloadTy)
5557 return 0;
5558
5559 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005560
5561 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005562 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005563 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005564
5565 TemplateArgumentListInfo ExplicitTemplateArgs;
5566 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005567
5568 // Look through all of the overloaded functions, searching for one
5569 // whose type matches exactly.
5570 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005571 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5572 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005573 // C++0x [temp.arg.explicit]p3:
5574 // [...] In contexts where deduction is done and fails, or in contexts
5575 // where deduction is not done, if a template argument list is
5576 // specified and it, along with any default template arguments,
5577 // identifies a single function template specialization, then the
5578 // template-id is an lvalue for the function template specialization.
5579 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5580
5581 // C++ [over.over]p2:
5582 // If the name is a function template, template argument deduction is
5583 // done (14.8.2.2), and if the argument deduction succeeds, the
5584 // resulting template argument list is used to generate a single
5585 // function template specialization, which is added to the set of
5586 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005587 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005588 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005589 if (TemplateDeductionResult Result
5590 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5591 Specialization, Info)) {
5592 // FIXME: make a note of the failed deduction for diagnostics.
5593 (void)Result;
5594 continue;
5595 }
5596
5597 // Multiple matches; we can't resolve to a single declaration.
5598 if (Matched)
5599 return 0;
5600
5601 Matched = Specialization;
5602 }
5603
5604 return Matched;
5605}
5606
Douglas Gregorcabea402009-09-22 15:41:20 +00005607/// \brief Add a single candidate to the overload set.
5608static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005609 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005610 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005611 Expr **Args, unsigned NumArgs,
5612 OverloadCandidateSet &CandidateSet,
5613 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005614 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005615 if (isa<UsingShadowDecl>(Callee))
5616 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5617
Douglas Gregorcabea402009-09-22 15:41:20 +00005618 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005619 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005620 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005621 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005622 return;
John McCalld14a8642009-11-21 08:51:07 +00005623 }
5624
5625 if (FunctionTemplateDecl *FuncTemplate
5626 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005627 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5628 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005629 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005630 return;
5631 }
5632
5633 assert(false && "unhandled case in overloaded call candidate");
5634
5635 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005636}
5637
5638/// \brief Add the overload candidates named by callee and/or found by argument
5639/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005640void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005641 Expr **Args, unsigned NumArgs,
5642 OverloadCandidateSet &CandidateSet,
5643 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005644
5645#ifndef NDEBUG
5646 // Verify that ArgumentDependentLookup is consistent with the rules
5647 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005648 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005649 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5650 // and let Y be the lookup set produced by argument dependent
5651 // lookup (defined as follows). If X contains
5652 //
5653 // -- a declaration of a class member, or
5654 //
5655 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005656 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005657 //
5658 // -- a declaration that is neither a function or a function
5659 // template
5660 //
5661 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005662
John McCall57500772009-12-16 12:17:52 +00005663 if (ULE->requiresADL()) {
5664 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5665 E = ULE->decls_end(); I != E; ++I) {
5666 assert(!(*I)->getDeclContext()->isRecord());
5667 assert(isa<UsingShadowDecl>(*I) ||
5668 !(*I)->getDeclContext()->isFunctionOrMethod());
5669 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005670 }
5671 }
5672#endif
5673
John McCall57500772009-12-16 12:17:52 +00005674 // It would be nice to avoid this copy.
5675 TemplateArgumentListInfo TABuffer;
5676 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5677 if (ULE->hasExplicitTemplateArgs()) {
5678 ULE->copyTemplateArgumentsInto(TABuffer);
5679 ExplicitTemplateArgs = &TABuffer;
5680 }
5681
5682 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5683 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005684 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005685 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005686 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005687
John McCall57500772009-12-16 12:17:52 +00005688 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005689 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5690 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005691 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005692 CandidateSet,
5693 PartialOverloading);
5694}
John McCalld681c392009-12-16 08:11:27 +00005695
John McCall57500772009-12-16 12:17:52 +00005696static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5697 Expr **Args, unsigned NumArgs) {
5698 Fn->Destroy(SemaRef.Context);
5699 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5700 Args[Arg]->Destroy(SemaRef.Context);
5701 return SemaRef.ExprError();
5702}
5703
John McCalld681c392009-12-16 08:11:27 +00005704/// Attempts to recover from a call where no functions were found.
5705///
5706/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005707static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005708BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005709 UnresolvedLookupExpr *ULE,
5710 SourceLocation LParenLoc,
5711 Expr **Args, unsigned NumArgs,
5712 SourceLocation *CommaLocs,
5713 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005714
5715 CXXScopeSpec SS;
5716 if (ULE->getQualifier()) {
5717 SS.setScopeRep(ULE->getQualifier());
5718 SS.setRange(ULE->getQualifierRange());
5719 }
5720
John McCall57500772009-12-16 12:17:52 +00005721 TemplateArgumentListInfo TABuffer;
5722 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5723 if (ULE->hasExplicitTemplateArgs()) {
5724 ULE->copyTemplateArgumentsInto(TABuffer);
5725 ExplicitTemplateArgs = &TABuffer;
5726 }
5727
John McCalld681c392009-12-16 08:11:27 +00005728 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5729 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005730 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005731 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005732
John McCall57500772009-12-16 12:17:52 +00005733 assert(!R.empty() && "lookup results empty despite recovery");
5734
5735 // Build an implicit member call if appropriate. Just drop the
5736 // casts and such from the call, we don't really care.
5737 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5738 if ((*R.begin())->isCXXClassMember())
5739 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5740 else if (ExplicitTemplateArgs)
5741 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5742 else
5743 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5744
5745 if (NewFn.isInvalid())
5746 return Destroy(SemaRef, Fn, Args, NumArgs);
5747
5748 Fn->Destroy(SemaRef.Context);
5749
5750 // This shouldn't cause an infinite loop because we're giving it
5751 // an expression with non-empty lookup results, which should never
5752 // end up here.
5753 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5754 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5755 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005756}
Douglas Gregorcabea402009-09-22 15:41:20 +00005757
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005758/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005759/// (which eventually refers to the declaration Func) and the call
5760/// arguments Args/NumArgs, attempt to resolve the function call down
5761/// to a specific function. If overload resolution succeeds, returns
5762/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005763/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005764/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005765Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005766Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005767 SourceLocation LParenLoc,
5768 Expr **Args, unsigned NumArgs,
5769 SourceLocation *CommaLocs,
5770 SourceLocation RParenLoc) {
5771#ifndef NDEBUG
5772 if (ULE->requiresADL()) {
5773 // To do ADL, we must have found an unqualified name.
5774 assert(!ULE->getQualifier() && "qualified name with ADL");
5775
5776 // We don't perform ADL for implicit declarations of builtins.
5777 // Verify that this was correctly set up.
5778 FunctionDecl *F;
5779 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5780 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5781 F->getBuiltinID() && F->isImplicit())
5782 assert(0 && "performing ADL for builtin");
5783
5784 // We don't perform ADL in C.
5785 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5786 }
5787#endif
5788
John McCallbc077cf2010-02-08 23:07:23 +00005789 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005790
John McCall57500772009-12-16 12:17:52 +00005791 // Add the functions denoted by the callee to the set of candidate
5792 // functions, including those from argument-dependent lookup.
5793 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005794
5795 // If we found nothing, try to recover.
5796 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5797 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005798 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005799 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005800 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005801
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005802 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005803 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005804 case OR_Success: {
5805 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005806 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00005807 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00005808 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005809 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5810 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005811
5812 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005813 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005814 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005815 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005816 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005817 break;
5818
5819 case OR_Ambiguous:
5820 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005821 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005822 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005823 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005824
5825 case OR_Deleted:
5826 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5827 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005828 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005829 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005830 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005831 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005832 }
5833
5834 // Overload resolution failed. Destroy all of the subexpressions and
5835 // return NULL.
5836 Fn->Destroy(Context);
5837 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5838 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005839 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005840}
5841
John McCall4c4c1df2010-01-26 03:27:55 +00005842static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005843 return Functions.size() > 1 ||
5844 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5845}
5846
Douglas Gregor084d8552009-03-13 23:49:33 +00005847/// \brief Create a unary operation that may resolve to an overloaded
5848/// operator.
5849///
5850/// \param OpLoc The location of the operator itself (e.g., '*').
5851///
5852/// \param OpcIn The UnaryOperator::Opcode that describes this
5853/// operator.
5854///
5855/// \param Functions The set of non-member functions that will be
5856/// considered by overload resolution. The caller needs to build this
5857/// set based on the context using, e.g.,
5858/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5859/// set should not contain any member functions; those will be added
5860/// by CreateOverloadedUnaryOp().
5861///
5862/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005863Sema::OwningExprResult
5864Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5865 const UnresolvedSetImpl &Fns,
5866 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005867 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5868 Expr *Input = (Expr *)input.get();
5869
5870 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5871 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5872 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5873
5874 Expr *Args[2] = { Input, 0 };
5875 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005876
Douglas Gregor084d8552009-03-13 23:49:33 +00005877 // For post-increment and post-decrement, add the implicit '0' as
5878 // the second argument, so that we know this is a post-increment or
5879 // post-decrement.
5880 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5881 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005882 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005883 SourceLocation());
5884 NumArgs = 2;
5885 }
5886
5887 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005888 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005889 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005890 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005891 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005892 /*ADL*/ true, IsOverloaded(Fns));
5893 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005894
Douglas Gregor084d8552009-03-13 23:49:33 +00005895 input.release();
5896 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5897 &Args[0], NumArgs,
5898 Context.DependentTy,
5899 OpLoc));
5900 }
5901
5902 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005903 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005904
5905 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005906 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005907
5908 // Add operator candidates that are member functions.
5909 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5910
John McCall4c4c1df2010-01-26 03:27:55 +00005911 // Add candidates from ADL.
5912 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005913 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005914 /*ExplicitTemplateArgs*/ 0,
5915 CandidateSet);
5916
Douglas Gregor084d8552009-03-13 23:49:33 +00005917 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005918 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005919
5920 // Perform overload resolution.
5921 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005922 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005923 case OR_Success: {
5924 // We found a built-in operator or an overloaded operator.
5925 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005926
Douglas Gregor084d8552009-03-13 23:49:33 +00005927 if (FnDecl) {
5928 // We matched an overloaded operator. Build a call to that
5929 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005930
Douglas Gregor084d8552009-03-13 23:49:33 +00005931 // Convert the arguments.
5932 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005933 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005934
John McCall16df1e52010-03-30 21:47:33 +00005935 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5936 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005937 return ExprError();
5938 } else {
5939 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005940 OwningExprResult InputInit
5941 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005942 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005943 SourceLocation(),
5944 move(input));
5945 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005946 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005947
Douglas Gregore6600372009-12-23 17:40:29 +00005948 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005949 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005950 }
5951
John McCall4fa0d5f2010-05-06 18:15:07 +00005952 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
5953
Douglas Gregor084d8552009-03-13 23:49:33 +00005954 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005955 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005956
Douglas Gregor084d8552009-03-13 23:49:33 +00005957 // Build the actual expression node.
5958 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5959 SourceLocation());
5960 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005961
Douglas Gregor084d8552009-03-13 23:49:33 +00005962 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005963 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005964 ExprOwningPtr<CallExpr> TheCall(this,
5965 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005966 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00005967
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005968 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5969 FnDecl))
5970 return ExprError();
5971
5972 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005973 } else {
5974 // We matched a built-in operator. Convert the arguments, then
5975 // break out so that we will build the appropriate built-in
5976 // operator node.
5977 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005978 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005979 return ExprError();
5980
5981 break;
5982 }
5983 }
5984
5985 case OR_No_Viable_Function:
5986 // No viable function; fall through to handling this as a
5987 // built-in operator, which will produce an error message for us.
5988 break;
5989
5990 case OR_Ambiguous:
5991 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5992 << UnaryOperator::getOpcodeStr(Opc)
5993 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005994 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005995 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005996 return ExprError();
5997
5998 case OR_Deleted:
5999 Diag(OpLoc, diag::err_ovl_deleted_oper)
6000 << Best->Function->isDeleted()
6001 << UnaryOperator::getOpcodeStr(Opc)
6002 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006003 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006004 return ExprError();
6005 }
6006
6007 // Either we found no viable overloaded operator or we matched a
6008 // built-in operator. In either case, fall through to trying to
6009 // build a built-in operation.
6010 input.release();
6011 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6012}
6013
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006014/// \brief Create a binary operation that may resolve to an overloaded
6015/// operator.
6016///
6017/// \param OpLoc The location of the operator itself (e.g., '+').
6018///
6019/// \param OpcIn The BinaryOperator::Opcode that describes this
6020/// operator.
6021///
6022/// \param Functions The set of non-member functions that will be
6023/// considered by overload resolution. The caller needs to build this
6024/// set based on the context using, e.g.,
6025/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6026/// set should not contain any member functions; those will be added
6027/// by CreateOverloadedBinOp().
6028///
6029/// \param LHS Left-hand argument.
6030/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006031Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006032Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006033 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006034 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006035 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006036 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006037 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006038
6039 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6040 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6041 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6042
6043 // If either side is type-dependent, create an appropriate dependent
6044 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006045 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006046 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006047 // If there are no functions to store, just build a dependent
6048 // BinaryOperator or CompoundAssignment.
6049 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6050 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6051 Context.DependentTy, OpLoc));
6052
6053 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6054 Context.DependentTy,
6055 Context.DependentTy,
6056 Context.DependentTy,
6057 OpLoc));
6058 }
John McCall4c4c1df2010-01-26 03:27:55 +00006059
6060 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006061 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006062 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006063 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006064 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006065 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006066
John McCall4c4c1df2010-01-26 03:27:55 +00006067 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006068 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006069 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006070 Context.DependentTy,
6071 OpLoc));
6072 }
6073
6074 // If this is the .* operator, which is not overloadable, just
6075 // create a built-in binary operator.
6076 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006077 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006078
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006079 // If this is the assignment operator, we only perform overload resolution
6080 // if the left-hand side is a class or enumeration type. This is actually
6081 // a hack. The standard requires that we do overload resolution between the
6082 // various built-in candidates, but as DR507 points out, this can lead to
6083 // problems. So we do it this way, which pretty much follows what GCC does.
6084 // Note that we go the traditional code path for compound assignment forms.
6085 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006086 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006087
Douglas Gregor084d8552009-03-13 23:49:33 +00006088 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006089 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006090
6091 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006092 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006093
6094 // Add operator candidates that are member functions.
6095 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6096
John McCall4c4c1df2010-01-26 03:27:55 +00006097 // Add candidates from ADL.
6098 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6099 Args, 2,
6100 /*ExplicitTemplateArgs*/ 0,
6101 CandidateSet);
6102
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006103 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006104 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006105
6106 // Perform overload resolution.
6107 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006108 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006109 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006110 // We found a built-in operator or an overloaded operator.
6111 FunctionDecl *FnDecl = Best->Function;
6112
6113 if (FnDecl) {
6114 // We matched an overloaded operator. Build a call to that
6115 // operator.
6116
6117 // Convert the arguments.
6118 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006119 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006120 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006121
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006122 OwningExprResult Arg1
6123 = PerformCopyInitialization(
6124 InitializedEntity::InitializeParameter(
6125 FnDecl->getParamDecl(0)),
6126 SourceLocation(),
6127 Owned(Args[1]));
6128 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006129 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006130
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006131 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006132 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006133 return ExprError();
6134
6135 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006136 } else {
6137 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006138 OwningExprResult Arg0
6139 = PerformCopyInitialization(
6140 InitializedEntity::InitializeParameter(
6141 FnDecl->getParamDecl(0)),
6142 SourceLocation(),
6143 Owned(Args[0]));
6144 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006145 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006146
6147 OwningExprResult Arg1
6148 = PerformCopyInitialization(
6149 InitializedEntity::InitializeParameter(
6150 FnDecl->getParamDecl(1)),
6151 SourceLocation(),
6152 Owned(Args[1]));
6153 if (Arg1.isInvalid())
6154 return ExprError();
6155 Args[0] = LHS = Arg0.takeAs<Expr>();
6156 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006157 }
6158
John McCall4fa0d5f2010-05-06 18:15:07 +00006159 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6160
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006161 // Determine the result type
6162 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006163 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006164 ResultTy = ResultTy.getNonReferenceType();
6165
6166 // Build the actual expression node.
6167 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006168 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006169 UsualUnaryConversions(FnExpr);
6170
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006171 ExprOwningPtr<CXXOperatorCallExpr>
6172 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6173 Args, 2, ResultTy,
6174 OpLoc));
6175
6176 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6177 FnDecl))
6178 return ExprError();
6179
6180 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006181 } else {
6182 // We matched a built-in operator. Convert the arguments, then
6183 // break out so that we will build the appropriate built-in
6184 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006185 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006186 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006187 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006188 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006189 return ExprError();
6190
6191 break;
6192 }
6193 }
6194
Douglas Gregor66950a32009-09-30 21:46:01 +00006195 case OR_No_Viable_Function: {
6196 // C++ [over.match.oper]p9:
6197 // If the operator is the operator , [...] and there are no
6198 // viable functions, then the operator is assumed to be the
6199 // built-in operator and interpreted according to clause 5.
6200 if (Opc == BinaryOperator::Comma)
6201 break;
6202
Sebastian Redl027de2a2009-05-21 11:50:50 +00006203 // For class as left operand for assignment or compound assigment operator
6204 // do not fall through to handling in built-in, but report that no overloaded
6205 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006206 OwningExprResult Result = ExprError();
6207 if (Args[0]->getType()->isRecordType() &&
6208 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006209 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6210 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006211 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006212 } else {
6213 // No viable function; try to create a built-in operation, which will
6214 // produce an error. Then, show the non-viable candidates.
6215 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006216 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006217 assert(Result.isInvalid() &&
6218 "C++ binary operator overloading is missing candidates!");
6219 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006220 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006221 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006222 return move(Result);
6223 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006224
6225 case OR_Ambiguous:
6226 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6227 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006228 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006229 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006230 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006231 return ExprError();
6232
6233 case OR_Deleted:
6234 Diag(OpLoc, diag::err_ovl_deleted_oper)
6235 << Best->Function->isDeleted()
6236 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006237 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006238 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006239 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006240 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006241
Douglas Gregor66950a32009-09-30 21:46:01 +00006242 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006243 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006244}
6245
Sebastian Redladba46e2009-10-29 20:17:01 +00006246Action::OwningExprResult
6247Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6248 SourceLocation RLoc,
6249 ExprArg Base, ExprArg Idx) {
6250 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6251 static_cast<Expr*>(Idx.get()) };
6252 DeclarationName OpName =
6253 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6254
6255 // If either side is type-dependent, create an appropriate dependent
6256 // expression.
6257 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6258
John McCall58cc69d2010-01-27 01:50:18 +00006259 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006260 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006261 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006262 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006263 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006264 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006265
6266 Base.release();
6267 Idx.release();
6268 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6269 Args, 2,
6270 Context.DependentTy,
6271 RLoc));
6272 }
6273
6274 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006275 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006276
6277 // Subscript can only be overloaded as a member function.
6278
6279 // Add operator candidates that are member functions.
6280 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6281
6282 // Add builtin operator candidates.
6283 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6284
6285 // Perform overload resolution.
6286 OverloadCandidateSet::iterator Best;
6287 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6288 case OR_Success: {
6289 // We found a built-in operator or an overloaded operator.
6290 FunctionDecl *FnDecl = Best->Function;
6291
6292 if (FnDecl) {
6293 // We matched an overloaded operator. Build a call to that
6294 // operator.
6295
John McCalla0296f72010-03-19 07:35:19 +00006296 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006297 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006298
Sebastian Redladba46e2009-10-29 20:17:01 +00006299 // Convert the arguments.
6300 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006301 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006302 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006303 return ExprError();
6304
Anders Carlssona68e51e2010-01-29 18:37:50 +00006305 // Convert the arguments.
6306 OwningExprResult InputInit
6307 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6308 FnDecl->getParamDecl(0)),
6309 SourceLocation(),
6310 Owned(Args[1]));
6311 if (InputInit.isInvalid())
6312 return ExprError();
6313
6314 Args[1] = InputInit.takeAs<Expr>();
6315
Sebastian Redladba46e2009-10-29 20:17:01 +00006316 // Determine the result type
6317 QualType ResultTy
6318 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6319 ResultTy = ResultTy.getNonReferenceType();
6320
6321 // Build the actual expression node.
6322 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6323 LLoc);
6324 UsualUnaryConversions(FnExpr);
6325
6326 Base.release();
6327 Idx.release();
6328 ExprOwningPtr<CXXOperatorCallExpr>
6329 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6330 FnExpr, Args, 2,
6331 ResultTy, RLoc));
6332
6333 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6334 FnDecl))
6335 return ExprError();
6336
6337 return MaybeBindToTemporary(TheCall.release());
6338 } else {
6339 // We matched a built-in operator. Convert the arguments, then
6340 // break out so that we will build the appropriate built-in
6341 // operator node.
6342 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006343 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006344 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006345 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006346 return ExprError();
6347
6348 break;
6349 }
6350 }
6351
6352 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006353 if (CandidateSet.empty())
6354 Diag(LLoc, diag::err_ovl_no_oper)
6355 << Args[0]->getType() << /*subscript*/ 0
6356 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6357 else
6358 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6359 << Args[0]->getType()
6360 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006361 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006362 "[]", LLoc);
6363 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006364 }
6365
6366 case OR_Ambiguous:
6367 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6368 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006369 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006370 "[]", LLoc);
6371 return ExprError();
6372
6373 case OR_Deleted:
6374 Diag(LLoc, diag::err_ovl_deleted_oper)
6375 << Best->Function->isDeleted() << "[]"
6376 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006377 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006378 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006379 return ExprError();
6380 }
6381
6382 // We matched a built-in operator; build it.
6383 Base.release();
6384 Idx.release();
6385 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6386 Owned(Args[1]), RLoc);
6387}
6388
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006389/// BuildCallToMemberFunction - Build a call to a member
6390/// function. MemExpr is the expression that refers to the member
6391/// function (and includes the object parameter), Args/NumArgs are the
6392/// arguments to the function call (not including the object
6393/// parameter). The caller needs to validate that the member
6394/// expression refers to a member function or an overloaded member
6395/// function.
John McCall2d74de92009-12-01 22:10:20 +00006396Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006397Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6398 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006399 unsigned NumArgs, SourceLocation *CommaLocs,
6400 SourceLocation RParenLoc) {
6401 // Dig out the member expression. This holds both the object
6402 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006403 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6404
John McCall10eae182009-11-30 22:42:35 +00006405 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006406 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006407 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006408 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006409 if (isa<MemberExpr>(NakedMemExpr)) {
6410 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006411 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006412 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006413 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006414 } else {
6415 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006416 Qualifier = UnresExpr->getQualifier();
6417
John McCall6e9f8f62009-12-03 04:06:58 +00006418 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006419
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006420 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006421 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006422
John McCall2d74de92009-12-01 22:10:20 +00006423 // FIXME: avoid copy.
6424 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6425 if (UnresExpr->hasExplicitTemplateArgs()) {
6426 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6427 TemplateArgs = &TemplateArgsBuffer;
6428 }
6429
John McCall10eae182009-11-30 22:42:35 +00006430 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6431 E = UnresExpr->decls_end(); I != E; ++I) {
6432
John McCall6e9f8f62009-12-03 04:06:58 +00006433 NamedDecl *Func = *I;
6434 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6435 if (isa<UsingShadowDecl>(Func))
6436 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6437
John McCall10eae182009-11-30 22:42:35 +00006438 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006439 // If explicit template arguments were provided, we can't call a
6440 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006441 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006442 continue;
6443
John McCalla0296f72010-03-19 07:35:19 +00006444 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006445 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006446 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006447 } else {
John McCall10eae182009-11-30 22:42:35 +00006448 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006449 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006450 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006451 CandidateSet,
6452 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006453 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006454 }
Mike Stump11289f42009-09-09 15:08:12 +00006455
John McCall10eae182009-11-30 22:42:35 +00006456 DeclarationName DeclName = UnresExpr->getMemberName();
6457
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006458 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006459 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006460 case OR_Success:
6461 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006462 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006463 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006464 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006465 break;
6466
6467 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006468 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006469 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006470 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006471 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006472 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006473 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006474
6475 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006476 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006477 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006478 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006479 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006480 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006481
6482 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006483 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006484 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006485 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006486 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006487 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006488 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006489 }
6490
John McCall16df1e52010-03-30 21:47:33 +00006491 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006492
John McCall2d74de92009-12-01 22:10:20 +00006493 // If overload resolution picked a static member, build a
6494 // non-member call based on that function.
6495 if (Method->isStatic()) {
6496 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6497 Args, NumArgs, RParenLoc);
6498 }
6499
John McCall10eae182009-11-30 22:42:35 +00006500 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006501 }
6502
6503 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006504 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006505 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006506 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006507 Method->getResultType().getNonReferenceType(),
6508 RParenLoc));
6509
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006510 // Check for a valid return type.
6511 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6512 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006513 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006514
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006515 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006516 // We only need to do this if there was actually an overload; otherwise
6517 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006518 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006519 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006520 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6521 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006522 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006523 MemExpr->setBase(ObjectArg);
6524
6525 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006526 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006527 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006528 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006529 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006530
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006531 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006532 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006533
John McCall2d74de92009-12-01 22:10:20 +00006534 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006535}
6536
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006537/// BuildCallToObjectOfClassType - Build a call to an object of class
6538/// type (C++ [over.call.object]), which can end up invoking an
6539/// overloaded function call operator (@c operator()) or performing a
6540/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006541Sema::ExprResult
6542Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006543 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006544 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006545 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006546 SourceLocation RParenLoc) {
6547 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006548 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006549
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006550 // C++ [over.call.object]p1:
6551 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006552 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006553 // candidate functions includes at least the function call
6554 // operators of T. The function call operators of T are obtained by
6555 // ordinary lookup of the name operator() in the context of
6556 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006557 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006558 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006559
6560 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006561 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006562 << Object->getSourceRange()))
6563 return true;
6564
John McCall27b18f82009-11-17 02:14:36 +00006565 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6566 LookupQualifiedName(R, Record->getDecl());
6567 R.suppressDiagnostics();
6568
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006569 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006570 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006571 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006572 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006573 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006574 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006575
Douglas Gregorab7897a2008-11-19 22:57:39 +00006576 // C++ [over.call.object]p2:
6577 // In addition, for each conversion function declared in T of the
6578 // form
6579 //
6580 // operator conversion-type-id () cv-qualifier;
6581 //
6582 // where cv-qualifier is the same cv-qualification as, or a
6583 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006584 // denotes the type "pointer to function of (P1,...,Pn) returning
6585 // R", or the type "reference to pointer to function of
6586 // (P1,...,Pn) returning R", or the type "reference to function
6587 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006588 // is also considered as a candidate function. Similarly,
6589 // surrogate call functions are added to the set of candidate
6590 // functions for each conversion function declared in an
6591 // accessible base class provided the function is not hidden
6592 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006593 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006594 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006595 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006596 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006597 NamedDecl *D = *I;
6598 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6599 if (isa<UsingShadowDecl>(D))
6600 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6601
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006602 // Skip over templated conversion functions; they aren't
6603 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006604 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006605 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006606
John McCall6e9f8f62009-12-03 04:06:58 +00006607 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006608
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006609 // Strip the reference type (if any) and then the pointer type (if
6610 // any) to get down to what might be a function type.
6611 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6612 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6613 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006614
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006615 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006616 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006617 Object->getType(), Args, NumArgs,
6618 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006619 }
Mike Stump11289f42009-09-09 15:08:12 +00006620
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006621 // Perform overload resolution.
6622 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006623 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006624 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006625 // Overload resolution succeeded; we'll build the appropriate call
6626 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006627 break;
6628
6629 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006630 if (CandidateSet.empty())
6631 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6632 << Object->getType() << /*call*/ 1
6633 << Object->getSourceRange();
6634 else
6635 Diag(Object->getSourceRange().getBegin(),
6636 diag::err_ovl_no_viable_object_call)
6637 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006638 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006639 break;
6640
6641 case OR_Ambiguous:
6642 Diag(Object->getSourceRange().getBegin(),
6643 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006644 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006645 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006646 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006647
6648 case OR_Deleted:
6649 Diag(Object->getSourceRange().getBegin(),
6650 diag::err_ovl_deleted_object_call)
6651 << Best->Function->isDeleted()
6652 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006653 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006654 break;
Mike Stump11289f42009-09-09 15:08:12 +00006655 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006656
Douglas Gregorab7897a2008-11-19 22:57:39 +00006657 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006658 // We had an error; delete all of the subexpressions and return
6659 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006660 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006661 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006662 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006663 return true;
6664 }
6665
Douglas Gregorab7897a2008-11-19 22:57:39 +00006666 if (Best->Function == 0) {
6667 // Since there is no function declaration, this is one of the
6668 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006669 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006670 = cast<CXXConversionDecl>(
6671 Best->Conversions[0].UserDefined.ConversionFunction);
6672
John McCalla0296f72010-03-19 07:35:19 +00006673 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006674 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006675
Douglas Gregorab7897a2008-11-19 22:57:39 +00006676 // We selected one of the surrogate functions that converts the
6677 // object parameter to a function pointer. Perform the conversion
6678 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006679
6680 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006681 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006682 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6683 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006684
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006685 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006686 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006687 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006688 }
6689
John McCalla0296f72010-03-19 07:35:19 +00006690 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006691 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006692
Douglas Gregorab7897a2008-11-19 22:57:39 +00006693 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6694 // that calls this method, using Object for the implicit object
6695 // parameter and passing along the remaining arguments.
6696 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006697 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006698
6699 unsigned NumArgsInProto = Proto->getNumArgs();
6700 unsigned NumArgsToCheck = NumArgs;
6701
6702 // Build the full argument list for the method call (the
6703 // implicit object parameter is placed at the beginning of the
6704 // list).
6705 Expr **MethodArgs;
6706 if (NumArgs < NumArgsInProto) {
6707 NumArgsToCheck = NumArgsInProto;
6708 MethodArgs = new Expr*[NumArgsInProto + 1];
6709 } else {
6710 MethodArgs = new Expr*[NumArgs + 1];
6711 }
6712 MethodArgs[0] = Object;
6713 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6714 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006715
6716 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006717 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006718 UsualUnaryConversions(NewFn);
6719
6720 // Once we've built TheCall, all of the expressions are properly
6721 // owned.
6722 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006723 ExprOwningPtr<CXXOperatorCallExpr>
6724 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006725 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006726 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006727 delete [] MethodArgs;
6728
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006729 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6730 Method))
6731 return true;
6732
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006733 // We may have default arguments. If so, we need to allocate more
6734 // slots in the call for them.
6735 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006736 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006737 else if (NumArgs > NumArgsInProto)
6738 NumArgsToCheck = NumArgsInProto;
6739
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006740 bool IsError = false;
6741
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006742 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006743 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006744 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006745 TheCall->setArg(0, Object);
6746
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006747
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006748 // Check the argument types.
6749 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006750 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006751 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006752 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006753
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006754 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006755
6756 OwningExprResult InputInit
6757 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6758 Method->getParamDecl(i)),
6759 SourceLocation(), Owned(Arg));
6760
6761 IsError |= InputInit.isInvalid();
6762 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006763 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006764 OwningExprResult DefArg
6765 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6766 if (DefArg.isInvalid()) {
6767 IsError = true;
6768 break;
6769 }
6770
6771 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006772 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006773
6774 TheCall->setArg(i + 1, Arg);
6775 }
6776
6777 // If this is a variadic call, handle args passed through "...".
6778 if (Proto->isVariadic()) {
6779 // Promote the arguments (C99 6.5.2.2p7).
6780 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6781 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006782 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006783 TheCall->setArg(i + 1, Arg);
6784 }
6785 }
6786
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006787 if (IsError) return true;
6788
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006789 if (CheckFunctionCall(Method, TheCall.get()))
6790 return true;
6791
Douglas Gregore5e775b2010-04-13 15:50:39 +00006792 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006793}
6794
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006795/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006796/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006797/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006798Sema::OwningExprResult
6799Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6800 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006801 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006802
John McCallbc077cf2010-02-08 23:07:23 +00006803 SourceLocation Loc = Base->getExprLoc();
6804
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006805 // C++ [over.ref]p1:
6806 //
6807 // [...] An expression x->m is interpreted as (x.operator->())->m
6808 // for a class object x of type T if T::operator->() exists and if
6809 // the operator is selected as the best match function by the
6810 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006811 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006812 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006813 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006814
John McCallbc077cf2010-02-08 23:07:23 +00006815 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006816 PDiag(diag::err_typecheck_incomplete_tag)
6817 << Base->getSourceRange()))
6818 return ExprError();
6819
John McCall27b18f82009-11-17 02:14:36 +00006820 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6821 LookupQualifiedName(R, BaseRecord->getDecl());
6822 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006823
6824 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006825 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006826 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006827 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006828 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006829
6830 // Perform overload resolution.
6831 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006832 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006833 case OR_Success:
6834 // Overload resolution succeeded; we'll build the call below.
6835 break;
6836
6837 case OR_No_Viable_Function:
6838 if (CandidateSet.empty())
6839 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006840 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006841 else
6842 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006843 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006844 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006845 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006846
6847 case OR_Ambiguous:
6848 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006849 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006850 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006851 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006852
6853 case OR_Deleted:
6854 Diag(OpLoc, diag::err_ovl_deleted_oper)
6855 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006856 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006857 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006858 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006859 }
6860
John McCalla0296f72010-03-19 07:35:19 +00006861 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006862 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00006863
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006864 // Convert the object parameter.
6865 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006866 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6867 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006868 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006869
6870 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006871 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006872
6873 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006874 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6875 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006876 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006877
6878 QualType ResultTy = Method->getResultType().getNonReferenceType();
6879 ExprOwningPtr<CXXOperatorCallExpr>
6880 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6881 &Base, 1, ResultTy, OpLoc));
6882
6883 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6884 Method))
6885 return ExprError();
6886 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006887}
6888
Douglas Gregorcd695e52008-11-10 20:40:00 +00006889/// FixOverloadedFunctionReference - E is an expression that refers to
6890/// a C++ overloaded function (possibly with some parentheses and
6891/// perhaps a '&' around it). We have resolved the overloaded function
6892/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006893/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006894Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006895 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006896 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006897 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6898 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006899 if (SubExpr == PE->getSubExpr())
6900 return PE->Retain();
6901
6902 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6903 }
6904
6905 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006906 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6907 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006908 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006909 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006910 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006911 if (SubExpr == ICE->getSubExpr())
6912 return ICE->Retain();
6913
6914 return new (Context) ImplicitCastExpr(ICE->getType(),
6915 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00006916 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006917 ICE->isLvalueCast());
6918 }
6919
6920 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006921 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006922 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006923 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6924 if (Method->isStatic()) {
6925 // Do nothing: static member functions aren't any different
6926 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006927 } else {
John McCalle66edc12009-11-24 19:00:30 +00006928 // Fix the sub expression, which really has to be an
6929 // UnresolvedLookupExpr holding an overloaded member function
6930 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006931 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6932 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006933 if (SubExpr == UnOp->getSubExpr())
6934 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006935
John McCalld14a8642009-11-21 08:51:07 +00006936 assert(isa<DeclRefExpr>(SubExpr)
6937 && "fixed to something other than a decl ref");
6938 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6939 && "fixed to a member ref with no nested name qualifier");
6940
6941 // We have taken the address of a pointer to member
6942 // function. Perform the computation here so that we get the
6943 // appropriate pointer to member type.
6944 QualType ClassType
6945 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6946 QualType MemPtrType
6947 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6948
6949 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6950 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006951 }
6952 }
John McCall16df1e52010-03-30 21:47:33 +00006953 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6954 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006955 if (SubExpr == UnOp->getSubExpr())
6956 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006957
Douglas Gregor51c538b2009-11-20 19:42:02 +00006958 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6959 Context.getPointerType(SubExpr->getType()),
6960 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006961 }
John McCalld14a8642009-11-21 08:51:07 +00006962
6963 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006964 // FIXME: avoid copy.
6965 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006966 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006967 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6968 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006969 }
6970
John McCalld14a8642009-11-21 08:51:07 +00006971 return DeclRefExpr::Create(Context,
6972 ULE->getQualifier(),
6973 ULE->getQualifierRange(),
6974 Fn,
6975 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006976 Fn->getType(),
6977 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006978 }
6979
John McCall10eae182009-11-30 22:42:35 +00006980 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006981 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006982 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6983 if (MemExpr->hasExplicitTemplateArgs()) {
6984 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6985 TemplateArgs = &TemplateArgsBuffer;
6986 }
John McCall6b51f282009-11-23 01:53:49 +00006987
John McCall2d74de92009-12-01 22:10:20 +00006988 Expr *Base;
6989
6990 // If we're filling in
6991 if (MemExpr->isImplicitAccess()) {
6992 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6993 return DeclRefExpr::Create(Context,
6994 MemExpr->getQualifier(),
6995 MemExpr->getQualifierRange(),
6996 Fn,
6997 MemExpr->getMemberLoc(),
6998 Fn->getType(),
6999 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007000 } else {
7001 SourceLocation Loc = MemExpr->getMemberLoc();
7002 if (MemExpr->getQualifier())
7003 Loc = MemExpr->getQualifierRange().getBegin();
7004 Base = new (Context) CXXThisExpr(Loc,
7005 MemExpr->getBaseType(),
7006 /*isImplicit=*/true);
7007 }
John McCall2d74de92009-12-01 22:10:20 +00007008 } else
7009 Base = MemExpr->getBase()->Retain();
7010
7011 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007012 MemExpr->isArrow(),
7013 MemExpr->getQualifier(),
7014 MemExpr->getQualifierRange(),
7015 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007016 Found,
John McCall6b51f282009-11-23 01:53:49 +00007017 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007018 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007019 Fn->getType());
7020 }
7021
Douglas Gregor51c538b2009-11-20 19:42:02 +00007022 assert(false && "Invalid reference to overloaded function");
7023 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007024}
7025
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007026Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007027 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007028 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007029 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007030}
7031
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007032} // end namespace clang