blob: 6ffca079897ac5d249812e799742d3ab4b258b5c [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 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
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() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000414}
415
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000439/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
440/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000451 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000452 return ICS;
453 }
454
455 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000456 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000457 return ICS;
458 }
459
460 OverloadCandidateSet Conversions(From->getExprLoc());
461 OverloadingResult UserDefResult
462 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
463 !SuppressUserConversions, AllowExplicit,
Douglas Gregor7b23e412010-04-16 17:25:05 +0000464 UserCast);
John McCallbc077cf2010-02-08 23:07:23 +0000465
466 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000467 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000468 // C++ [over.ics.user]p4:
469 // A conversion of an expression of class type to the same class
470 // type is given Exact Match rank, and a conversion of an
471 // expression of class type to a base class of that type is
472 // given Conversion rank, in spite of the fact that a copy
473 // constructor (i.e., a user-defined conversion function) is
474 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000475 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000476 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000477 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000478 = Context.getCanonicalType(From->getType().getUnqualifiedType());
479 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000480 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000481 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 // Turn this into a "standard" conversion sequence, so that it
483 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000484 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000485 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000486 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000487 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000488 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000489 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000490 ICS.Standard.Second = ICK_Derived_To_Base;
491 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000493
494 // C++ [over.best.ics]p4:
495 // However, when considering the argument of a user-defined
496 // conversion function that is a candidate by 13.3.1.3 when
497 // invoked for the copying of the temporary in the second step
498 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
499 // 13.3.1.6 in all cases, only standard conversion sequences and
500 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000501 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000502 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000503 }
John McCalle8c8cd22010-01-13 22:30:33 +0000504 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000505 ICS.setAmbiguous();
506 ICS.Ambiguous.setFromType(From->getType());
507 ICS.Ambiguous.setToType(ToType);
508 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
509 Cand != Conversions.end(); ++Cand)
510 if (Cand->Viable)
511 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000512 } else {
John McCall65eb8792010-02-25 01:37:24 +0000513 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000514 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000515
516 return ICS;
517}
518
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000519/// \brief Determine whether the conversion from FromType to ToType is a valid
520/// conversion that strips "noreturn" off the nested function type.
521static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
522 QualType ToType, QualType &ResultTy) {
523 if (Context.hasSameUnqualifiedType(FromType, ToType))
524 return false;
525
526 // Strip the noreturn off the type we're converting from; noreturn can
527 // safely be removed.
528 FromType = Context.getNoReturnType(FromType, false);
529 if (!Context.hasSameUnqualifiedType(FromType, ToType))
530 return false;
531
532 ResultTy = FromType;
533 return true;
534}
535
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000536/// IsStandardConversion - Determines whether there is a standard
537/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
538/// expression From to the type ToType. Standard conversion sequences
539/// only consider non-class types; for conversions that involve class
540/// types, use TryImplicitConversion. If a conversion exists, SCS will
541/// contain the standard conversion sequence required to perform this
542/// conversion and this routine will return true. Otherwise, this
543/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000544bool
545Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000546 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000547 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000548 QualType FromType = From->getType();
549
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000551 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000552 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000553 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000554 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000555 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000556
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000557 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000558 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000559 if (FromType->isRecordType() || ToType->isRecordType()) {
560 if (getLangOptions().CPlusPlus)
561 return false;
562
Mike Stump11289f42009-09-09 15:08:12 +0000563 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000564 }
565
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000566 // The first conversion can be an lvalue-to-rvalue conversion,
567 // array-to-pointer conversion, or function-to-pointer conversion
568 // (C++ 4p1).
569
John McCall16df1e52010-03-30 21:47:33 +0000570 DeclAccessPair AccessPair;
571
Mike Stump11289f42009-09-09 15:08:12 +0000572 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000573 // An lvalue (3.10) of a non-function, non-array type T can be
574 // converted to an rvalue.
575 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000576 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000577 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000578 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000579 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000580
581 // If T is a non-class type, the type of the rvalue is the
582 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000583 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
584 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000585 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000586 } else if (FromType->isArrayType()) {
587 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000588 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000589
590 // An lvalue or rvalue of type "array of N T" or "array of unknown
591 // bound of T" can be converted to an rvalue of type "pointer to
592 // T" (C++ 4.2p1).
593 FromType = Context.getArrayDecayedType(FromType);
594
595 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
596 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000597 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598
599 // For the purpose of ranking in overload resolution
600 // (13.3.3.1.1), this conversion is considered an
601 // array-to-pointer conversion followed by a qualification
602 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000603 SCS.Second = ICK_Identity;
604 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000605 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000606 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000607 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000608 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
609 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000610 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611
612 // An lvalue of function type T can be converted to an rvalue of
613 // type "pointer to T." The result is a pointer to the
614 // function. (C++ 4.3p1).
615 FromType = Context.getPointerType(FromType);
Douglas Gregor064fdb22010-04-14 23:11:21 +0000616 } else if (From->getType() == Context.OverloadTy) {
617 if (FunctionDecl *Fn
618 = ResolveAddressOfOverloadedFunction(From, ToType, false,
619 AccessPair)) {
620 // Address of overloaded function (C++ [over.over]).
621 SCS.First = ICK_Function_To_Pointer;
Douglas Gregorcd695e52008-11-10 20:40:00 +0000622
Douglas Gregor064fdb22010-04-14 23:11:21 +0000623 // We were able to resolve the address of the overloaded function,
624 // so we can convert to the type of that function.
625 FromType = Fn->getType();
626 if (ToType->isLValueReferenceType())
627 FromType = Context.getLValueReferenceType(FromType);
628 else if (ToType->isRValueReferenceType())
629 FromType = Context.getRValueReferenceType(FromType);
630 else if (ToType->isMemberPointerType()) {
631 // Resolve address only succeeds if both sides are member pointers,
632 // but it doesn't have to be the same class. See DR 247.
633 // Note that this means that the type of &Derived::fn can be
634 // Ret (Base::*)(Args) if the fn overload actually found is from the
635 // base class, even if it was brought into the derived class via a
636 // using declaration. The standard isn't clear on this issue at all.
637 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
638 FromType = Context.getMemberPointerType(FromType,
639 Context.getTypeDeclType(M->getParent()).getTypePtr());
640 } else {
641 FromType = Context.getPointerType(FromType);
642 }
643 } else {
644 return false;
645 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000646 } else {
647 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000648 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000649 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000650 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000651
652 // The second conversion can be an integral promotion, floating
653 // point promotion, integral conversion, floating point conversion,
654 // floating-integral conversion, pointer conversion,
655 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000656 // For overloading in C, this can also be a "compatible-type"
657 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000658 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000659 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000660 // The unqualified versions of the types are the same: there's no
661 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000662 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000663 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000664 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000665 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000667 } else if (IsFloatingPointPromotion(FromType, ToType)) {
668 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000669 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000670 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000671 } else if (IsComplexPromotion(FromType, ToType)) {
672 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000673 SCS.Second = ICK_Complex_Promotion;
674 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000675 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000676 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000677 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000678 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000679 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000680 } else if (FromType->isComplexType() && ToType->isComplexType()) {
681 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000682 SCS.Second = ICK_Complex_Conversion;
683 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000684 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
685 (ToType->isComplexType() && FromType->isArithmeticType())) {
686 // Complex-real conversions (C99 6.3.1.7)
687 SCS.Second = ICK_Complex_Real;
688 FromType = ToType.getUnqualifiedType();
689 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
690 // Floating point conversions (C++ 4.8).
691 SCS.Second = ICK_Floating_Conversion;
692 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000693 } else if ((FromType->isFloatingType() &&
694 ToType->isIntegralType() && (!ToType->isBooleanType() &&
695 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000696 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000697 ToType->isFloatingType())) {
698 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000699 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000700 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000701 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
702 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000703 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000704 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000705 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000706 } else if (IsMemberPointerConversion(From, FromType, ToType,
707 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000708 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000709 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000710 } else if (ToType->isBooleanType() &&
711 (FromType->isArithmeticType() ||
712 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000713 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000714 FromType->isBlockPointerType() ||
715 FromType->isMemberPointerType() ||
716 FromType->isNullPtrType())) {
717 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000718 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000719 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000720 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000721 Context.typesAreCompatible(ToType, FromType)) {
722 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000723 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000724 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
725 // Treat a conversion that strips "noreturn" as an identity conversion.
726 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000727 } else {
728 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000729 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000731 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000732
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000733 QualType CanonFrom;
734 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000735 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000736 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000737 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000738 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000739 CanonFrom = Context.getCanonicalType(FromType);
740 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000741 } else {
742 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000743 SCS.Third = ICK_Identity;
744
Mike Stump11289f42009-09-09 15:08:12 +0000745 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000746 // [...] Any difference in top-level cv-qualification is
747 // subsumed by the initialization itself and does not constitute
748 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000749 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000750 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000751 if (CanonFrom.getLocalUnqualifiedType()
752 == CanonTo.getLocalUnqualifiedType() &&
753 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000754 FromType = ToType;
755 CanonFrom = CanonTo;
756 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000758 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000759
760 // If we have not converted the argument type to the parameter type,
761 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000762 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000763 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000764
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000765 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000766}
767
768/// IsIntegralPromotion - Determines whether the conversion from the
769/// expression From (whose potentially-adjusted type is FromType) to
770/// ToType is an integral promotion (C++ 4.5). If so, returns true and
771/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000772bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000773 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000774 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000775 if (!To) {
776 return false;
777 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000778
779 // An rvalue of type char, signed char, unsigned char, short int, or
780 // unsigned short int can be converted to an rvalue of type int if
781 // int can represent all the values of the source type; otherwise,
782 // the source rvalue can be converted to an rvalue of type unsigned
783 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000784 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
785 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000786 if (// We can promote any signed, promotable integer type to an int
787 (FromType->isSignedIntegerType() ||
788 // We can promote any unsigned integer type whose size is
789 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000790 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000791 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000792 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000793 }
794
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000795 return To->getKind() == BuiltinType::UInt;
796 }
797
798 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
799 // can be converted to an rvalue of the first of the following types
800 // that can represent all the values of its underlying type: int,
801 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000802
803 // We pre-calculate the promotion type for enum types.
804 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
805 if (ToType->isIntegerType())
806 return Context.hasSameUnqualifiedType(ToType,
807 FromEnumType->getDecl()->getPromotionType());
808
809 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000810 // Determine whether the type we're converting from is signed or
811 // unsigned.
812 bool FromIsSigned;
813 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000814
815 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
816 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817
818 // The types we'll try to promote to, in the appropriate
819 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000820 QualType PromoteTypes[6] = {
821 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000822 Context.LongTy, Context.UnsignedLongTy ,
823 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000824 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000825 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000826 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
827 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000828 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000829 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
830 // We found the type that we can promote to. If this is the
831 // type we wanted, we have a promotion. Otherwise, no
832 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000833 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000834 }
835 }
836 }
837
838 // An rvalue for an integral bit-field (9.6) can be converted to an
839 // rvalue of type int if int can represent all the values of the
840 // bit-field; otherwise, it can be converted to unsigned int if
841 // unsigned int can represent all the values of the bit-field. If
842 // the bit-field is larger yet, no integral promotion applies to
843 // it. If the bit-field has an enumerated type, it is treated as any
844 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000845 // FIXME: We should delay checking of bit-fields until we actually perform the
846 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000847 using llvm::APSInt;
848 if (From)
849 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000850 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000851 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
852 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
853 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
854 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000855
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000856 // Are we promoting to an int from a bitfield that fits in an int?
857 if (BitWidth < ToSize ||
858 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
859 return To->getKind() == BuiltinType::Int;
860 }
Mike Stump11289f42009-09-09 15:08:12 +0000861
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000862 // Are we promoting to an unsigned int from an unsigned bitfield
863 // that fits into an unsigned int?
864 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
865 return To->getKind() == BuiltinType::UInt;
866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000868 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000869 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000870 }
Mike Stump11289f42009-09-09 15:08:12 +0000871
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872 // An rvalue of type bool can be converted to an rvalue of type int,
873 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000874 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000875 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000876 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000877
878 return false;
879}
880
881/// IsFloatingPointPromotion - Determines whether the conversion from
882/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
883/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000884bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000885 /// An rvalue of type float can be converted to an rvalue of type
886 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000887 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
888 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889 if (FromBuiltin->getKind() == BuiltinType::Float &&
890 ToBuiltin->getKind() == BuiltinType::Double)
891 return true;
892
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000893 // C99 6.3.1.5p1:
894 // When a float is promoted to double or long double, or a
895 // double is promoted to long double [...].
896 if (!getLangOptions().CPlusPlus &&
897 (FromBuiltin->getKind() == BuiltinType::Float ||
898 FromBuiltin->getKind() == BuiltinType::Double) &&
899 (ToBuiltin->getKind() == BuiltinType::LongDouble))
900 return true;
901 }
902
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000903 return false;
904}
905
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000906/// \brief Determine if a conversion is a complex promotion.
907///
908/// A complex promotion is defined as a complex -> complex conversion
909/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000910/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000911bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000912 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000913 if (!FromComplex)
914 return false;
915
John McCall9dd450b2009-09-21 23:43:11 +0000916 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000917 if (!ToComplex)
918 return false;
919
920 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000921 ToComplex->getElementType()) ||
922 IsIntegralPromotion(0, FromComplex->getElementType(),
923 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000924}
925
Douglas Gregor237f96c2008-11-26 23:31:11 +0000926/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
927/// the pointer type FromPtr to a pointer to type ToPointee, with the
928/// same type qualifiers as FromPtr has on its pointee type. ToType,
929/// if non-empty, will be a pointer to ToType that may or may not have
930/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000931static QualType
932BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000933 QualType ToPointee, QualType ToType,
934 ASTContext &Context) {
935 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
936 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000937 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000938
939 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000940 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000941 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000942 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000943 return ToType;
944
945 // Build a pointer to ToPointee. It has the right qualifiers
946 // already.
947 return Context.getPointerType(ToPointee);
948 }
949
950 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000951 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000952 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
953 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000954}
955
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000956/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
957/// the FromType, which is an objective-c pointer, to ToType, which may or may
958/// not have the right set of qualifiers.
959static QualType
960BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
961 QualType ToType,
962 ASTContext &Context) {
963 QualType CanonFromType = Context.getCanonicalType(FromType);
964 QualType CanonToType = Context.getCanonicalType(ToType);
965 Qualifiers Quals = CanonFromType.getQualifiers();
966
967 // Exact qualifier match -> return the pointer type we're converting to.
968 if (CanonToType.getLocalQualifiers() == Quals)
969 return ToType;
970
971 // Just build a canonical type that has the right qualifiers.
972 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
973}
974
Mike Stump11289f42009-09-09 15:08:12 +0000975static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000976 bool InOverloadResolution,
977 ASTContext &Context) {
978 // Handle value-dependent integral null pointer constants correctly.
979 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
980 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
981 Expr->getType()->isIntegralType())
982 return !InOverloadResolution;
983
Douglas Gregor56751b52009-09-25 04:25:58 +0000984 return Expr->isNullPointerConstant(Context,
985 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
986 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000987}
Mike Stump11289f42009-09-09 15:08:12 +0000988
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989/// IsPointerConversion - Determines whether the conversion of the
990/// expression From, which has the (possibly adjusted) type FromType,
991/// can be converted to the type ToType via a pointer conversion (C++
992/// 4.10). If so, returns true and places the converted type (that
993/// might differ from ToType in its cv-qualifiers at some level) into
994/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000995///
Douglas Gregora29dc052008-11-27 01:19:21 +0000996/// This routine also supports conversions to and from block pointers
997/// and conversions with Objective-C's 'id', 'id<protocols...>', and
998/// pointers to interfaces. FIXME: Once we've determined the
999/// appropriate overloading rules for Objective-C, we may want to
1000/// split the Objective-C checks into a different routine; however,
1001/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001002/// conversions, so for now they live here. IncompatibleObjC will be
1003/// set if the conversion is an allowed Objective-C conversion that
1004/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001006 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001007 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001008 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001009 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001010 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1011 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001012
Mike Stump11289f42009-09-09 15:08:12 +00001013 // Conversion from a null pointer constant to any Objective-C pointer type.
1014 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001015 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001016 ConvertedType = ToType;
1017 return true;
1018 }
1019
Douglas Gregor231d1c62008-11-27 00:15:41 +00001020 // Blocks: Block pointers can be converted to void*.
1021 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001022 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001023 ConvertedType = ToType;
1024 return true;
1025 }
1026 // Blocks: A null pointer constant can be converted to a block
1027 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001028 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033
Sebastian Redl576fd422009-05-10 18:38:11 +00001034 // If the left-hand-side is nullptr_t, the right side can be a null
1035 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001036 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001037 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001038 ConvertedType = ToType;
1039 return true;
1040 }
1041
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001042 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043 if (!ToTypePtr)
1044 return false;
1045
1046 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001047 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001048 ConvertedType = ToType;
1049 return true;
1050 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001051
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001052 // Beyond this point, both types need to be pointers
1053 // , including objective-c pointers.
1054 QualType ToPointeeType = ToTypePtr->getPointeeType();
1055 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1056 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1057 ToType, Context);
1058 return true;
1059
1060 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001062 if (!FromTypePtr)
1063 return false;
1064
1065 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001066
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001067 // An rvalue of type "pointer to cv T," where T is an object type,
1068 // can be converted to an rvalue of type "pointer to cv void" (C++
1069 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001070 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001071 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001072 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001073 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001074 return true;
1075 }
1076
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001077 // When we're overloading in C, we allow a special kind of pointer
1078 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001079 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001080 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001081 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001082 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001083 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001084 return true;
1085 }
1086
Douglas Gregor5c407d92008-10-23 00:40:37 +00001087 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001088 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001089 // An rvalue of type "pointer to cv D," where D is a class type,
1090 // can be converted to an rvalue of type "pointer to cv B," where
1091 // B is a base class (clause 10) of D. If B is an inaccessible
1092 // (clause 11) or ambiguous (10.2) base class of D, a program that
1093 // necessitates this conversion is ill-formed. The result of the
1094 // conversion is a pointer to the base class sub-object of the
1095 // derived class object. The null pointer value is converted to
1096 // the null pointer value of the destination type.
1097 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001098 // Note that we do not check for ambiguity or inaccessibility
1099 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001100 if (getLangOptions().CPlusPlus &&
1101 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001102 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001103 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001104 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001105 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001106 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001107 ToType, Context);
1108 return true;
1109 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001110
Douglas Gregora119f102008-12-19 19:13:09 +00001111 return false;
1112}
1113
1114/// isObjCPointerConversion - Determines whether this is an
1115/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1116/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001117bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001118 QualType& ConvertedType,
1119 bool &IncompatibleObjC) {
1120 if (!getLangOptions().ObjC1)
1121 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001122
Steve Naroff7cae42b2009-07-10 23:34:53 +00001123 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001124 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001125 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001126 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001127
Steve Naroff7cae42b2009-07-10 23:34:53 +00001128 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001129 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001130 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001131 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001132 ConvertedType = ToType;
1133 return true;
1134 }
1135 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001136 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001137 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001138 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001139 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001140 ConvertedType = ToType;
1141 return true;
1142 }
1143 // Objective C++: We're able to convert from a pointer to an
1144 // interface to a pointer to a different interface.
1145 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001146 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1147 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1148 if (getLangOptions().CPlusPlus && LHS && RHS &&
1149 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1150 FromObjCPtr->getPointeeType()))
1151 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001152 ConvertedType = ToType;
1153 return true;
1154 }
1155
1156 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1157 // Okay: this is some kind of implicit downcast of Objective-C
1158 // interfaces, which is permitted. However, we're going to
1159 // complain about it.
1160 IncompatibleObjC = true;
1161 ConvertedType = FromType;
1162 return true;
1163 }
Mike Stump11289f42009-09-09 15:08:12 +00001164 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001165 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001166 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001167 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001168 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001169 else if (const BlockPointerType *ToBlockPtr =
1170 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001171 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001172 // to a block pointer type.
1173 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1174 ConvertedType = ToType;
1175 return true;
1176 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001177 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001178 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001179 else if (FromType->getAs<BlockPointerType>() &&
1180 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1181 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001182 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001183 ConvertedType = ToType;
1184 return true;
1185 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001186 else
Douglas Gregora119f102008-12-19 19:13:09 +00001187 return false;
1188
Douglas Gregor033f56d2008-12-23 00:53:59 +00001189 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001190 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001191 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001192 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001193 FromPointeeType = FromBlockPtr->getPointeeType();
1194 else
Douglas Gregora119f102008-12-19 19:13:09 +00001195 return false;
1196
Douglas Gregora119f102008-12-19 19:13:09 +00001197 // If we have pointers to pointers, recursively check whether this
1198 // is an Objective-C conversion.
1199 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1200 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1201 IncompatibleObjC)) {
1202 // We always complain about this conversion.
1203 IncompatibleObjC = true;
1204 ConvertedType = ToType;
1205 return true;
1206 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001207 // Allow conversion of pointee being objective-c pointer to another one;
1208 // as in I* to id.
1209 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1210 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1211 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1212 IncompatibleObjC)) {
1213 ConvertedType = ToType;
1214 return true;
1215 }
1216
Douglas Gregor033f56d2008-12-23 00:53:59 +00001217 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001218 // differences in the argument and result types are in Objective-C
1219 // pointer conversions. If so, we permit the conversion (but
1220 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001221 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001222 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001223 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001224 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001225 if (FromFunctionType && ToFunctionType) {
1226 // If the function types are exactly the same, this isn't an
1227 // Objective-C pointer conversion.
1228 if (Context.getCanonicalType(FromPointeeType)
1229 == Context.getCanonicalType(ToPointeeType))
1230 return false;
1231
1232 // Perform the quick checks that will tell us whether these
1233 // function types are obviously different.
1234 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1235 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1236 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1237 return false;
1238
1239 bool HasObjCConversion = false;
1240 if (Context.getCanonicalType(FromFunctionType->getResultType())
1241 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1242 // Okay, the types match exactly. Nothing to do.
1243 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1244 ToFunctionType->getResultType(),
1245 ConvertedType, IncompatibleObjC)) {
1246 // Okay, we have an Objective-C pointer conversion.
1247 HasObjCConversion = true;
1248 } else {
1249 // Function types are too different. Abort.
1250 return false;
1251 }
Mike Stump11289f42009-09-09 15:08:12 +00001252
Douglas Gregora119f102008-12-19 19:13:09 +00001253 // Check argument types.
1254 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1255 ArgIdx != NumArgs; ++ArgIdx) {
1256 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1257 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1258 if (Context.getCanonicalType(FromArgType)
1259 == Context.getCanonicalType(ToArgType)) {
1260 // Okay, the types match exactly. Nothing to do.
1261 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1262 ConvertedType, IncompatibleObjC)) {
1263 // Okay, we have an Objective-C pointer conversion.
1264 HasObjCConversion = true;
1265 } else {
1266 // Argument types are too different. Abort.
1267 return false;
1268 }
1269 }
1270
1271 if (HasObjCConversion) {
1272 // We had an Objective-C conversion. Allow this pointer
1273 // conversion, but complain about it.
1274 ConvertedType = ToType;
1275 IncompatibleObjC = true;
1276 return true;
1277 }
1278 }
1279
Sebastian Redl72b597d2009-01-25 19:43:20 +00001280 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001281}
1282
Douglas Gregor39c16d42008-10-24 04:54:22 +00001283/// CheckPointerConversion - Check the pointer conversion from the
1284/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001285/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001286/// conversions for which IsPointerConversion has already returned
1287/// true. It returns true and produces a diagnostic if there was an
1288/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001289bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001290 CastExpr::CastKind &Kind,
1291 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001292 QualType FromType = From->getType();
1293
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001294 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1295 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001296 QualType FromPointeeType = FromPtrType->getPointeeType(),
1297 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001298
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001299 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1300 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001301 // We must have a derived-to-base conversion. Check an
1302 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001303 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1304 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001305 From->getSourceRange(),
1306 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001307 return true;
1308
1309 // The conversion was successful.
1310 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001311 }
1312 }
Mike Stump11289f42009-09-09 15:08:12 +00001313 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001314 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001315 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001316 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001317 // Objective-C++ conversions are always okay.
1318 // FIXME: We should have a different class of conversions for the
1319 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001320 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001321 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001322
Steve Naroff7cae42b2009-07-10 23:34:53 +00001323 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001324 return false;
1325}
1326
Sebastian Redl72b597d2009-01-25 19:43:20 +00001327/// IsMemberPointerConversion - Determines whether the conversion of the
1328/// expression From, which has the (possibly adjusted) type FromType, can be
1329/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1330/// If so, returns true and places the converted type (that might differ from
1331/// ToType in its cv-qualifiers at some level) into ConvertedType.
1332bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001333 QualType ToType,
1334 bool InOverloadResolution,
1335 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001336 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001337 if (!ToTypePtr)
1338 return false;
1339
1340 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001341 if (From->isNullPointerConstant(Context,
1342 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1343 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001344 ConvertedType = ToType;
1345 return true;
1346 }
1347
1348 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001349 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001350 if (!FromTypePtr)
1351 return false;
1352
1353 // A pointer to member of B can be converted to a pointer to member of D,
1354 // where D is derived from B (C++ 4.11p2).
1355 QualType FromClass(FromTypePtr->getClass(), 0);
1356 QualType ToClass(ToTypePtr->getClass(), 0);
1357 // FIXME: What happens when these are dependent? Is this function even called?
1358
1359 if (IsDerivedFrom(ToClass, FromClass)) {
1360 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1361 ToClass.getTypePtr());
1362 return true;
1363 }
1364
1365 return false;
1366}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001367
Sebastian Redl72b597d2009-01-25 19:43:20 +00001368/// CheckMemberPointerConversion - Check the member pointer conversion from the
1369/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001370/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001371/// for which IsMemberPointerConversion has already returned true. It returns
1372/// true and produces a diagnostic if there was an error, or returns false
1373/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001374bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001375 CastExpr::CastKind &Kind,
1376 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001377 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001378 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001379 if (!FromPtrType) {
1380 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001381 assert(From->isNullPointerConstant(Context,
1382 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001383 "Expr must be null pointer constant!");
1384 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001385 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001386 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001387
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001388 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001389 assert(ToPtrType && "No member pointer cast has a target type "
1390 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001391
Sebastian Redled8f2002009-01-28 18:33:18 +00001392 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1393 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001394
Sebastian Redled8f2002009-01-28 18:33:18 +00001395 // FIXME: What about dependent types?
1396 assert(FromClass->isRecordType() && "Pointer into non-class.");
1397 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001398
John McCall5b0829a2010-02-10 09:31:12 +00001399 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001400 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001401 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1402 assert(DerivationOkay &&
1403 "Should not have been called if derivation isn't OK.");
1404 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001405
Sebastian Redled8f2002009-01-28 18:33:18 +00001406 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1407 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001408 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1409 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1410 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1411 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001412 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001413
Douglas Gregor89ee6822009-02-28 01:32:25 +00001414 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001415 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1416 << FromClass << ToClass << QualType(VBase, 0)
1417 << From->getSourceRange();
1418 return true;
1419 }
1420
John McCall5b0829a2010-02-10 09:31:12 +00001421 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001422 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1423 Paths.front(),
1424 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001425
Anders Carlssond7923c62009-08-22 23:33:40 +00001426 // Must be a base to derived member conversion.
1427 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001428 return false;
1429}
1430
Douglas Gregor9a657932008-10-21 23:43:52 +00001431/// IsQualificationConversion - Determines whether the conversion from
1432/// an rvalue of type FromType to ToType is a qualification conversion
1433/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001434bool
1435Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001436 FromType = Context.getCanonicalType(FromType);
1437 ToType = Context.getCanonicalType(ToType);
1438
1439 // If FromType and ToType are the same type, this is not a
1440 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001441 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001442 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001443
Douglas Gregor9a657932008-10-21 23:43:52 +00001444 // (C++ 4.4p4):
1445 // A conversion can add cv-qualifiers at levels other than the first
1446 // in multi-level pointers, subject to the following rules: [...]
1447 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001448 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001449 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001450 // Within each iteration of the loop, we check the qualifiers to
1451 // determine if this still looks like a qualification
1452 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001453 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001454 // until there are no more pointers or pointers-to-members left to
1455 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001456 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001457
1458 // -- for every j > 0, if const is in cv 1,j then const is in cv
1459 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001460 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001461 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001462
Douglas Gregor9a657932008-10-21 23:43:52 +00001463 // -- if the cv 1,j and cv 2,j are different, then const is in
1464 // every cv for 0 < k < j.
1465 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001466 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001467 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001468
Douglas Gregor9a657932008-10-21 23:43:52 +00001469 // Keep track of whether all prior cv-qualifiers in the "to" type
1470 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001471 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001472 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001473 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001474
1475 // We are left with FromType and ToType being the pointee types
1476 // after unwrapping the original FromType and ToType the same number
1477 // of types. If we unwrapped any pointers, and if FromType and
1478 // ToType have the same unqualified type (since we checked
1479 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001480 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001481}
1482
Douglas Gregor576e98c2009-01-30 23:27:23 +00001483/// Determines whether there is a user-defined conversion sequence
1484/// (C++ [over.ics.user]) that converts expression From to the type
1485/// ToType. If such a conversion exists, User will contain the
1486/// user-defined conversion sequence that performs such a conversion
1487/// and this routine will return true. Otherwise, this routine returns
1488/// false and User is unspecified.
1489///
1490/// \param AllowConversionFunctions true if the conversion should
1491/// consider conversion functions at all. If false, only constructors
1492/// will be considered.
1493///
1494/// \param AllowExplicit true if the conversion should consider C++0x
1495/// "explicit" conversion functions as well as non-explicit conversion
1496/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001497///
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001498/// \param UserCast true if looking for user defined conversion for a static
1499/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001500OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1501 UserDefinedConversionSequence& User,
1502 OverloadCandidateSet& CandidateSet,
1503 bool AllowConversionFunctions,
1504 bool AllowExplicit,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001505 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001506 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001507 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1508 // We're not going to find any constructors.
1509 } else if (CXXRecordDecl *ToRecordDecl
1510 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001511 // C++ [over.match.ctor]p1:
1512 // When objects of class type are direct-initialized (8.5), or
1513 // copy-initialized from an expression of the same or a
1514 // derived class type (8.5), overload resolution selects the
1515 // constructor. [...] For copy-initialization, the candidate
1516 // functions are all the converting constructors (12.3.1) of
1517 // that class. The argument list is the expression-list within
1518 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001519 bool SuppressUserConversions = !UserCast;
1520 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1521 IsDerivedFrom(From->getType(), ToType)) {
1522 SuppressUserConversions = false;
1523 AllowConversionFunctions = false;
1524 }
1525
Mike Stump11289f42009-09-09 15:08:12 +00001526 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001527 = Context.DeclarationNames.getCXXConstructorName(
1528 Context.getCanonicalType(ToType).getUnqualifiedType());
1529 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001530 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001531 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001532 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001533 NamedDecl *D = *Con;
1534 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1535
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001536 // Find the constructor (which may be a template).
1537 CXXConstructorDecl *Constructor = 0;
1538 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001539 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001540 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001541 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001542 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1543 else
John McCalla0296f72010-03-19 07:35:19 +00001544 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001545
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001546 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001547 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001548 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001549 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001550 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001551 &From, 1, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00001552 SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001553 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001554 // Allow one user-defined conversion when user specifies a
1555 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001556 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001557 &From, 1, CandidateSet,
Douglas Gregor7b23e412010-04-16 17:25:05 +00001558 SuppressUserConversions, false);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001559 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001560 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001561 }
1562 }
1563
Douglas Gregor576e98c2009-01-30 23:27:23 +00001564 if (!AllowConversionFunctions) {
1565 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001566 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1567 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001568 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001569 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001570 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001571 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001572 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001573 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1574 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001575 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001576 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001577 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001578 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001579 DeclAccessPair FoundDecl = I.getPair();
1580 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001581 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1582 if (isa<UsingShadowDecl>(D))
1583 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1584
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001585 CXXConversionDecl *Conv;
1586 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001587 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1588 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001589 else
John McCallda4458e2010-03-31 01:36:47 +00001590 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001591
1592 if (AllowExplicit || !Conv->isExplicit()) {
1593 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001594 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001595 ActingContext, From, ToType,
1596 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001597 else
John McCalla0296f72010-03-19 07:35:19 +00001598 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001599 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001600 }
1601 }
1602 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001603 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001604
1605 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001606 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001607 case OR_Success:
1608 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001609 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001610 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1611 // C++ [over.ics.user]p1:
1612 // If the user-defined conversion is specified by a
1613 // constructor (12.3.1), the initial standard conversion
1614 // sequence converts the source type to the type required by
1615 // the argument of the constructor.
1616 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001617 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001618 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001619 User.EllipsisConversion = true;
1620 else {
1621 User.Before = Best->Conversions[0].Standard;
1622 User.EllipsisConversion = false;
1623 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001624 User.ConversionFunction = Constructor;
1625 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001626 User.After.setFromType(
1627 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001628 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001629 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001630 } else if (CXXConversionDecl *Conversion
1631 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1632 // C++ [over.ics.user]p1:
1633 //
1634 // [...] If the user-defined conversion is specified by a
1635 // conversion function (12.3.2), the initial standard
1636 // conversion sequence converts the source type to the
1637 // implicit object parameter of the conversion function.
1638 User.Before = Best->Conversions[0].Standard;
1639 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001640 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001641
1642 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001643 // The second standard conversion sequence converts the
1644 // result of the user-defined conversion to the target type
1645 // for the sequence. Since an implicit conversion sequence
1646 // is an initialization, the special rules for
1647 // initialization by user-defined conversion apply when
1648 // selecting the best user-defined conversion for a
1649 // user-defined conversion sequence (see 13.3.3 and
1650 // 13.3.3.1).
1651 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001652 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001653 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001654 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001655 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001658 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001659 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001660 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001661 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001662 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001663
1664 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001665 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001666 }
1667
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001668 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001669}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001670
1671bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001672Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001673 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001674 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001675 OverloadingResult OvResult =
1676 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor7b23e412010-04-16 17:25:05 +00001677 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001678 if (OvResult == OR_Ambiguous)
1679 Diag(From->getSourceRange().getBegin(),
1680 diag::err_typecheck_ambiguous_condition)
1681 << From->getType() << ToType << From->getSourceRange();
1682 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1683 Diag(From->getSourceRange().getBegin(),
1684 diag::err_typecheck_nonviable_condition)
1685 << From->getType() << ToType << From->getSourceRange();
1686 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001687 return false;
John McCallad907772010-01-12 07:18:19 +00001688 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001689 return true;
1690}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001691
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692/// CompareImplicitConversionSequences - Compare two implicit
1693/// conversion sequences to determine whether one is better than the
1694/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001695ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001696Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1697 const ImplicitConversionSequence& ICS2)
1698{
1699 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1700 // conversion sequences (as defined in 13.3.3.1)
1701 // -- a standard conversion sequence (13.3.3.1.1) is a better
1702 // conversion sequence than a user-defined conversion sequence or
1703 // an ellipsis conversion sequence, and
1704 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1705 // conversion sequence than an ellipsis conversion sequence
1706 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001707 //
John McCall0d1da222010-01-12 00:44:57 +00001708 // C++0x [over.best.ics]p10:
1709 // For the purpose of ranking implicit conversion sequences as
1710 // described in 13.3.3.2, the ambiguous conversion sequence is
1711 // treated as a user-defined sequence that is indistinguishable
1712 // from any other user-defined conversion sequence.
1713 if (ICS1.getKind() < ICS2.getKind()) {
1714 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1715 return ImplicitConversionSequence::Better;
1716 } else if (ICS2.getKind() < ICS1.getKind()) {
1717 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1718 return ImplicitConversionSequence::Worse;
1719 }
1720
1721 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1722 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723
1724 // Two implicit conversion sequences of the same form are
1725 // indistinguishable conversion sequences unless one of the
1726 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001727 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001728 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001729 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730 // User-defined conversion sequence U1 is a better conversion
1731 // sequence than another user-defined conversion sequence U2 if
1732 // they contain the same user-defined conversion function or
1733 // constructor and if the second standard conversion sequence of
1734 // U1 is better than the second standard conversion sequence of
1735 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001736 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001737 ICS2.UserDefined.ConversionFunction)
1738 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1739 ICS2.UserDefined.After);
1740 }
1741
1742 return ImplicitConversionSequence::Indistinguishable;
1743}
1744
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001745// Per 13.3.3.2p3, compare the given standard conversion sequences to
1746// determine if one is a proper subset of the other.
1747static ImplicitConversionSequence::CompareKind
1748compareStandardConversionSubsets(ASTContext &Context,
1749 const StandardConversionSequence& SCS1,
1750 const StandardConversionSequence& SCS2) {
1751 ImplicitConversionSequence::CompareKind Result
1752 = ImplicitConversionSequence::Indistinguishable;
1753
1754 if (SCS1.Second != SCS2.Second) {
1755 if (SCS1.Second == ICK_Identity)
1756 Result = ImplicitConversionSequence::Better;
1757 else if (SCS2.Second == ICK_Identity)
1758 Result = ImplicitConversionSequence::Worse;
1759 else
1760 return ImplicitConversionSequence::Indistinguishable;
1761 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1762 return ImplicitConversionSequence::Indistinguishable;
1763
1764 if (SCS1.Third == SCS2.Third) {
1765 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1766 : ImplicitConversionSequence::Indistinguishable;
1767 }
1768
1769 if (SCS1.Third == ICK_Identity)
1770 return Result == ImplicitConversionSequence::Worse
1771 ? ImplicitConversionSequence::Indistinguishable
1772 : ImplicitConversionSequence::Better;
1773
1774 if (SCS2.Third == ICK_Identity)
1775 return Result == ImplicitConversionSequence::Better
1776 ? ImplicitConversionSequence::Indistinguishable
1777 : ImplicitConversionSequence::Worse;
1778
1779 return ImplicitConversionSequence::Indistinguishable;
1780}
1781
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001782/// CompareStandardConversionSequences - Compare two standard
1783/// conversion sequences to determine whether one is better than the
1784/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001785ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001786Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1787 const StandardConversionSequence& SCS2)
1788{
1789 // Standard conversion sequence S1 is a better conversion sequence
1790 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1791
1792 // -- S1 is a proper subsequence of S2 (comparing the conversion
1793 // sequences in the canonical form defined by 13.3.3.1.1,
1794 // excluding any Lvalue Transformation; the identity conversion
1795 // sequence is considered to be a subsequence of any
1796 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001797 if (ImplicitConversionSequence::CompareKind CK
1798 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1799 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800
1801 // -- the rank of S1 is better than the rank of S2 (by the rules
1802 // defined below), or, if not that,
1803 ImplicitConversionRank Rank1 = SCS1.getRank();
1804 ImplicitConversionRank Rank2 = SCS2.getRank();
1805 if (Rank1 < Rank2)
1806 return ImplicitConversionSequence::Better;
1807 else if (Rank2 < Rank1)
1808 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001809
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001810 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1811 // are indistinguishable unless one of the following rules
1812 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001813
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001814 // A conversion that is not a conversion of a pointer, or
1815 // pointer to member, to bool is better than another conversion
1816 // that is such a conversion.
1817 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1818 return SCS2.isPointerConversionToBool()
1819 ? ImplicitConversionSequence::Better
1820 : ImplicitConversionSequence::Worse;
1821
Douglas Gregor5c407d92008-10-23 00:40:37 +00001822 // C++ [over.ics.rank]p4b2:
1823 //
1824 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001825 // conversion of B* to A* is better than conversion of B* to
1826 // void*, and conversion of A* to void* is better than conversion
1827 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001828 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001829 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001830 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001831 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001832 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1833 // Exactly one of the conversion sequences is a conversion to
1834 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001835 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1836 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001837 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1838 // Neither conversion sequence converts to a void pointer; compare
1839 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001840 if (ImplicitConversionSequence::CompareKind DerivedCK
1841 = CompareDerivedToBaseConversions(SCS1, SCS2))
1842 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001843 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1844 // Both conversion sequences are conversions to void
1845 // pointers. Compare the source types to determine if there's an
1846 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001847 QualType FromType1 = SCS1.getFromType();
1848 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001849
1850 // Adjust the types we're converting from via the array-to-pointer
1851 // conversion, if we need to.
1852 if (SCS1.First == ICK_Array_To_Pointer)
1853 FromType1 = Context.getArrayDecayedType(FromType1);
1854 if (SCS2.First == ICK_Array_To_Pointer)
1855 FromType2 = Context.getArrayDecayedType(FromType2);
1856
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001857 QualType FromPointee1
1858 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1859 QualType FromPointee2
1860 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001861
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001862 if (IsDerivedFrom(FromPointee2, FromPointee1))
1863 return ImplicitConversionSequence::Better;
1864 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1865 return ImplicitConversionSequence::Worse;
1866
1867 // Objective-C++: If one interface is more specific than the
1868 // other, it is the better one.
1869 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1870 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1871 if (FromIface1 && FromIface1) {
1872 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1873 return ImplicitConversionSequence::Better;
1874 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1875 return ImplicitConversionSequence::Worse;
1876 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001877 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001878
1879 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1880 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001881 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001882 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001883 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001884
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001885 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001886 // C++0x [over.ics.rank]p3b4:
1887 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1888 // implicit object parameter of a non-static member function declared
1889 // without a ref-qualifier, and S1 binds an rvalue reference to an
1890 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001891 // FIXME: We don't know if we're dealing with the implicit object parameter,
1892 // or if the member function in this case has a ref qualifier.
1893 // (Of course, we don't have ref qualifiers yet.)
1894 if (SCS1.RRefBinding != SCS2.RRefBinding)
1895 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1896 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001897
1898 // C++ [over.ics.rank]p3b4:
1899 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1900 // which the references refer are the same type except for
1901 // top-level cv-qualifiers, and the type to which the reference
1902 // initialized by S2 refers is more cv-qualified than the type
1903 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001904 QualType T1 = SCS1.getToType(2);
1905 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001906 T1 = Context.getCanonicalType(T1);
1907 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001908 Qualifiers T1Quals, T2Quals;
1909 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1910 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1911 if (UnqualT1 == UnqualT2) {
1912 // If the type is an array type, promote the element qualifiers to the type
1913 // for comparison.
1914 if (isa<ArrayType>(T1) && T1Quals)
1915 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1916 if (isa<ArrayType>(T2) && T2Quals)
1917 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001918 if (T2.isMoreQualifiedThan(T1))
1919 return ImplicitConversionSequence::Better;
1920 else if (T1.isMoreQualifiedThan(T2))
1921 return ImplicitConversionSequence::Worse;
1922 }
1923 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001924
1925 return ImplicitConversionSequence::Indistinguishable;
1926}
1927
1928/// CompareQualificationConversions - Compares two standard conversion
1929/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001930/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1931ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001932Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001933 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001934 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001935 // -- S1 and S2 differ only in their qualification conversion and
1936 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1937 // cv-qualification signature of type T1 is a proper subset of
1938 // the cv-qualification signature of type T2, and S1 is not the
1939 // deprecated string literal array-to-pointer conversion (4.2).
1940 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1941 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1942 return ImplicitConversionSequence::Indistinguishable;
1943
1944 // FIXME: the example in the standard doesn't use a qualification
1945 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001946 QualType T1 = SCS1.getToType(2);
1947 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001948 T1 = Context.getCanonicalType(T1);
1949 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001950 Qualifiers T1Quals, T2Quals;
1951 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1952 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001953
1954 // If the types are the same, we won't learn anything by unwrapped
1955 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001956 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001957 return ImplicitConversionSequence::Indistinguishable;
1958
Chandler Carruth607f38e2009-12-29 07:16:59 +00001959 // If the type is an array type, promote the element qualifiers to the type
1960 // for comparison.
1961 if (isa<ArrayType>(T1) && T1Quals)
1962 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1963 if (isa<ArrayType>(T2) && T2Quals)
1964 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1965
Mike Stump11289f42009-09-09 15:08:12 +00001966 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001967 = ImplicitConversionSequence::Indistinguishable;
1968 while (UnwrapSimilarPointerTypes(T1, T2)) {
1969 // Within each iteration of the loop, we check the qualifiers to
1970 // determine if this still looks like a qualification
1971 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001972 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001973 // until there are no more pointers or pointers-to-members left
1974 // to unwrap. This essentially mimics what
1975 // IsQualificationConversion does, but here we're checking for a
1976 // strict subset of qualifiers.
1977 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1978 // The qualifiers are the same, so this doesn't tell us anything
1979 // about how the sequences rank.
1980 ;
1981 else if (T2.isMoreQualifiedThan(T1)) {
1982 // T1 has fewer qualifiers, so it could be the better sequence.
1983 if (Result == ImplicitConversionSequence::Worse)
1984 // Neither has qualifiers that are a subset of the other's
1985 // qualifiers.
1986 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001988 Result = ImplicitConversionSequence::Better;
1989 } else if (T1.isMoreQualifiedThan(T2)) {
1990 // T2 has fewer qualifiers, so it could be the better sequence.
1991 if (Result == ImplicitConversionSequence::Better)
1992 // Neither has qualifiers that are a subset of the other's
1993 // qualifiers.
1994 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001995
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001996 Result = ImplicitConversionSequence::Worse;
1997 } else {
1998 // Qualifiers are disjoint.
1999 return ImplicitConversionSequence::Indistinguishable;
2000 }
2001
2002 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002003 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002004 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002005 }
2006
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002007 // Check that the winning standard conversion sequence isn't using
2008 // the deprecated string literal array to pointer conversion.
2009 switch (Result) {
2010 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002011 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002012 Result = ImplicitConversionSequence::Indistinguishable;
2013 break;
2014
2015 case ImplicitConversionSequence::Indistinguishable:
2016 break;
2017
2018 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002019 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002020 Result = ImplicitConversionSequence::Indistinguishable;
2021 break;
2022 }
2023
2024 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002025}
2026
Douglas Gregor5c407d92008-10-23 00:40:37 +00002027/// CompareDerivedToBaseConversions - Compares two standard conversion
2028/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002029/// various kinds of derived-to-base conversions (C++
2030/// [over.ics.rank]p4b3). As part of these checks, we also look at
2031/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002032ImplicitConversionSequence::CompareKind
2033Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2034 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002035 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002036 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002037 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002038 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002039
2040 // Adjust the types we're converting from via the array-to-pointer
2041 // conversion, if we need to.
2042 if (SCS1.First == ICK_Array_To_Pointer)
2043 FromType1 = Context.getArrayDecayedType(FromType1);
2044 if (SCS2.First == ICK_Array_To_Pointer)
2045 FromType2 = Context.getArrayDecayedType(FromType2);
2046
2047 // Canonicalize all of the types.
2048 FromType1 = Context.getCanonicalType(FromType1);
2049 ToType1 = Context.getCanonicalType(ToType1);
2050 FromType2 = Context.getCanonicalType(FromType2);
2051 ToType2 = Context.getCanonicalType(ToType2);
2052
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002053 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002054 //
2055 // If class B is derived directly or indirectly from class A and
2056 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002057 //
2058 // For Objective-C, we let A, B, and C also be Objective-C
2059 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002060
2061 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002062 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002063 SCS2.Second == ICK_Pointer_Conversion &&
2064 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2065 FromType1->isPointerType() && FromType2->isPointerType() &&
2066 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002067 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002068 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002069 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002070 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002071 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002072 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002073 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002074 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002075
John McCall9dd450b2009-09-21 23:43:11 +00002076 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2077 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2078 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2079 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002080
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002081 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002082 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2083 if (IsDerivedFrom(ToPointee1, ToPointee2))
2084 return ImplicitConversionSequence::Better;
2085 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2086 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002087
2088 if (ToIface1 && ToIface2) {
2089 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2090 return ImplicitConversionSequence::Better;
2091 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2092 return ImplicitConversionSequence::Worse;
2093 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002094 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002095
2096 // -- conversion of B* to A* is better than conversion of C* to A*,
2097 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2098 if (IsDerivedFrom(FromPointee2, FromPointee1))
2099 return ImplicitConversionSequence::Better;
2100 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2101 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002102
Douglas Gregor237f96c2008-11-26 23:31:11 +00002103 if (FromIface1 && FromIface2) {
2104 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2105 return ImplicitConversionSequence::Better;
2106 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2107 return ImplicitConversionSequence::Worse;
2108 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002109 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002110 }
2111
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002112 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002113 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2114 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2115 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2116 const MemberPointerType * FromMemPointer1 =
2117 FromType1->getAs<MemberPointerType>();
2118 const MemberPointerType * ToMemPointer1 =
2119 ToType1->getAs<MemberPointerType>();
2120 const MemberPointerType * FromMemPointer2 =
2121 FromType2->getAs<MemberPointerType>();
2122 const MemberPointerType * ToMemPointer2 =
2123 ToType2->getAs<MemberPointerType>();
2124 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2125 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2126 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2127 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2128 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2129 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2130 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2131 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002132 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002133 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2134 if (IsDerivedFrom(ToPointee1, ToPointee2))
2135 return ImplicitConversionSequence::Worse;
2136 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2137 return ImplicitConversionSequence::Better;
2138 }
2139 // conversion of B::* to C::* is better than conversion of A::* to C::*
2140 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2141 if (IsDerivedFrom(FromPointee1, FromPointee2))
2142 return ImplicitConversionSequence::Better;
2143 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2144 return ImplicitConversionSequence::Worse;
2145 }
2146 }
2147
Douglas Gregor83af86a2010-02-25 19:01:05 +00002148 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2149 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor2fe98832008-11-03 19:09:14 +00002150 SCS1.Second == ICK_Derived_To_Base) {
2151 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002152 // -- binding of an expression of type C to a reference of type
2153 // B& is better than binding an expression of type C to a
2154 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002155 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2156 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002157 if (IsDerivedFrom(ToType1, ToType2))
2158 return ImplicitConversionSequence::Better;
2159 else if (IsDerivedFrom(ToType2, ToType1))
2160 return ImplicitConversionSequence::Worse;
2161 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002162
Douglas Gregor2fe98832008-11-03 19:09:14 +00002163 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002164 // -- binding of an expression of type B to a reference of type
2165 // A& is better than binding an expression of type C to a
2166 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002167 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2168 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002169 if (IsDerivedFrom(FromType2, FromType1))
2170 return ImplicitConversionSequence::Better;
2171 else if (IsDerivedFrom(FromType1, FromType2))
2172 return ImplicitConversionSequence::Worse;
2173 }
2174 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002175
Douglas Gregor5c407d92008-10-23 00:40:37 +00002176 return ImplicitConversionSequence::Indistinguishable;
2177}
2178
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002179/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2180/// determine whether they are reference-related,
2181/// reference-compatible, reference-compatible with added
2182/// qualification, or incompatible, for use in C++ initialization by
2183/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2184/// type, and the first type (T1) is the pointee type of the reference
2185/// type being initialized.
2186Sema::ReferenceCompareResult
2187Sema::CompareReferenceRelationship(SourceLocation Loc,
2188 QualType OrigT1, QualType OrigT2,
2189 bool& DerivedToBase) {
2190 assert(!OrigT1->isReferenceType() &&
2191 "T1 must be the pointee type of the reference type");
2192 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2193
2194 QualType T1 = Context.getCanonicalType(OrigT1);
2195 QualType T2 = Context.getCanonicalType(OrigT2);
2196 Qualifiers T1Quals, T2Quals;
2197 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2198 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2199
2200 // C++ [dcl.init.ref]p4:
2201 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2202 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2203 // T1 is a base class of T2.
2204 if (UnqualT1 == UnqualT2)
2205 DerivedToBase = false;
2206 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2207 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2208 IsDerivedFrom(UnqualT2, UnqualT1))
2209 DerivedToBase = true;
2210 else
2211 return Ref_Incompatible;
2212
2213 // At this point, we know that T1 and T2 are reference-related (at
2214 // least).
2215
2216 // If the type is an array type, promote the element qualifiers to the type
2217 // for comparison.
2218 if (isa<ArrayType>(T1) && T1Quals)
2219 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2220 if (isa<ArrayType>(T2) && T2Quals)
2221 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2222
2223 // C++ [dcl.init.ref]p4:
2224 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2225 // reference-related to T2 and cv1 is the same cv-qualification
2226 // as, or greater cv-qualification than, cv2. For purposes of
2227 // overload resolution, cases for which cv1 is greater
2228 // cv-qualification than cv2 are identified as
2229 // reference-compatible with added qualification (see 13.3.3.2).
2230 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2231 return Ref_Compatible;
2232 else if (T1.isMoreQualifiedThan(T2))
2233 return Ref_Compatible_With_Added_Qualification;
2234 else
2235 return Ref_Related;
2236}
2237
2238/// \brief Compute an implicit conversion sequence for reference
2239/// initialization.
2240static ImplicitConversionSequence
2241TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2242 SourceLocation DeclLoc,
2243 bool SuppressUserConversions,
2244 bool AllowExplicit, bool ForceRValue) {
2245 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2246
2247 // Most paths end in a failed conversion.
2248 ImplicitConversionSequence ICS;
2249 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2250
2251 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2252 QualType T2 = Init->getType();
2253
2254 // If the initializer is the address of an overloaded function, try
2255 // to resolve the overloaded function. If all goes well, T2 is the
2256 // type of the resulting function.
2257 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2258 DeclAccessPair Found;
2259 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2260 false, Found))
2261 T2 = Fn->getType();
2262 }
2263
2264 // Compute some basic properties of the types and the initializer.
2265 bool isRValRef = DeclType->isRValueReferenceType();
2266 bool DerivedToBase = false;
2267 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2268 Init->isLvalue(S.Context);
2269 Sema::ReferenceCompareResult RefRelationship
2270 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2271
2272 // C++ [dcl.init.ref]p5:
2273 // A reference to type "cv1 T1" is initialized by an expression
2274 // of type "cv2 T2" as follows:
2275
2276 // -- If the initializer expression
2277
2278 // C++ [over.ics.ref]p3:
2279 // Except for an implicit object parameter, for which see 13.3.1,
2280 // a standard conversion sequence cannot be formed if it requires
2281 // binding an lvalue reference to non-const to an rvalue or
2282 // binding an rvalue reference to an lvalue.
2283 if (isRValRef && InitLvalue == Expr::LV_Valid)
2284 return ICS;
2285
2286 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2287 // reference-compatible with "cv2 T2," or
2288 //
2289 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2290 if (InitLvalue == Expr::LV_Valid &&
2291 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2292 // C++ [over.ics.ref]p1:
2293 // When a parameter of reference type binds directly (8.5.3)
2294 // to an argument expression, the implicit conversion sequence
2295 // is the identity conversion, unless the argument expression
2296 // has a type that is a derived class of the parameter type,
2297 // in which case the implicit conversion sequence is a
2298 // derived-to-base Conversion (13.3.3.1).
2299 ICS.setStandard();
2300 ICS.Standard.First = ICK_Identity;
2301 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2302 ICS.Standard.Third = ICK_Identity;
2303 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2304 ICS.Standard.setToType(0, T2);
2305 ICS.Standard.setToType(1, T1);
2306 ICS.Standard.setToType(2, T1);
2307 ICS.Standard.ReferenceBinding = true;
2308 ICS.Standard.DirectBinding = true;
2309 ICS.Standard.RRefBinding = false;
2310 ICS.Standard.CopyConstructor = 0;
2311
2312 // Nothing more to do: the inaccessibility/ambiguity check for
2313 // derived-to-base conversions is suppressed when we're
2314 // computing the implicit conversion sequence (C++
2315 // [over.best.ics]p2).
2316 return ICS;
2317 }
2318
2319 // -- has a class type (i.e., T2 is a class type), where T1 is
2320 // not reference-related to T2, and can be implicitly
2321 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2322 // is reference-compatible with "cv3 T3" 92) (this
2323 // conversion is selected by enumerating the applicable
2324 // conversion functions (13.3.1.6) and choosing the best
2325 // one through overload resolution (13.3)),
2326 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2327 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2328 RefRelationship == Sema::Ref_Incompatible) {
2329 CXXRecordDecl *T2RecordDecl
2330 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2331
2332 OverloadCandidateSet CandidateSet(DeclLoc);
2333 const UnresolvedSetImpl *Conversions
2334 = T2RecordDecl->getVisibleConversionFunctions();
2335 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2336 E = Conversions->end(); I != E; ++I) {
2337 NamedDecl *D = *I;
2338 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2339 if (isa<UsingShadowDecl>(D))
2340 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2341
2342 FunctionTemplateDecl *ConvTemplate
2343 = dyn_cast<FunctionTemplateDecl>(D);
2344 CXXConversionDecl *Conv;
2345 if (ConvTemplate)
2346 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2347 else
2348 Conv = cast<CXXConversionDecl>(D);
2349
2350 // If the conversion function doesn't return a reference type,
2351 // it can't be considered for this conversion.
2352 if (Conv->getConversionType()->isLValueReferenceType() &&
2353 (AllowExplicit || !Conv->isExplicit())) {
2354 if (ConvTemplate)
2355 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2356 Init, DeclType, CandidateSet);
2357 else
2358 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2359 DeclType, CandidateSet);
2360 }
2361 }
2362
2363 OverloadCandidateSet::iterator Best;
2364 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2365 case OR_Success:
2366 // C++ [over.ics.ref]p1:
2367 //
2368 // [...] If the parameter binds directly to the result of
2369 // applying a conversion function to the argument
2370 // expression, the implicit conversion sequence is a
2371 // user-defined conversion sequence (13.3.3.1.2), with the
2372 // second standard conversion sequence either an identity
2373 // conversion or, if the conversion function returns an
2374 // entity of a type that is a derived class of the parameter
2375 // type, a derived-to-base Conversion.
2376 if (!Best->FinalConversion.DirectBinding)
2377 break;
2378
2379 ICS.setUserDefined();
2380 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2381 ICS.UserDefined.After = Best->FinalConversion;
2382 ICS.UserDefined.ConversionFunction = Best->Function;
2383 ICS.UserDefined.EllipsisConversion = false;
2384 assert(ICS.UserDefined.After.ReferenceBinding &&
2385 ICS.UserDefined.After.DirectBinding &&
2386 "Expected a direct reference binding!");
2387 return ICS;
2388
2389 case OR_Ambiguous:
2390 ICS.setAmbiguous();
2391 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2392 Cand != CandidateSet.end(); ++Cand)
2393 if (Cand->Viable)
2394 ICS.Ambiguous.addConversion(Cand->Function);
2395 return ICS;
2396
2397 case OR_No_Viable_Function:
2398 case OR_Deleted:
2399 // There was no suitable conversion, or we found a deleted
2400 // conversion; continue with other checks.
2401 break;
2402 }
2403 }
2404
2405 // -- Otherwise, the reference shall be to a non-volatile const
2406 // type (i.e., cv1 shall be const), or the reference shall be an
2407 // rvalue reference and the initializer expression shall be an rvalue.
2408 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const)
2409 return ICS;
2410
2411 // -- If the initializer expression is an rvalue, with T2 a
2412 // class type, and "cv1 T1" is reference-compatible with
2413 // "cv2 T2," the reference is bound in one of the
2414 // following ways (the choice is implementation-defined):
2415 //
2416 // -- The reference is bound to the object represented by
2417 // the rvalue (see 3.10) or to a sub-object within that
2418 // object.
2419 //
2420 // -- A temporary of type "cv1 T2" [sic] is created, and
2421 // a constructor is called to copy the entire rvalue
2422 // object into the temporary. The reference is bound to
2423 // the temporary or to a sub-object within the
2424 // temporary.
2425 //
2426 // The constructor that would be used to make the copy
2427 // shall be callable whether or not the copy is actually
2428 // done.
2429 //
2430 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2431 // freedom, so we will always take the first option and never build
2432 // a temporary in this case.
2433 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2434 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2435 ICS.setStandard();
2436 ICS.Standard.First = ICK_Identity;
2437 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2438 ICS.Standard.Third = ICK_Identity;
2439 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2440 ICS.Standard.setToType(0, T2);
2441 ICS.Standard.setToType(1, T1);
2442 ICS.Standard.setToType(2, T1);
2443 ICS.Standard.ReferenceBinding = true;
2444 ICS.Standard.DirectBinding = false;
2445 ICS.Standard.RRefBinding = isRValRef;
2446 ICS.Standard.CopyConstructor = 0;
2447 return ICS;
2448 }
2449
2450 // -- Otherwise, a temporary of type "cv1 T1" is created and
2451 // initialized from the initializer expression using the
2452 // rules for a non-reference copy initialization (8.5). The
2453 // reference is then bound to the temporary. If T1 is
2454 // reference-related to T2, cv1 must be the same
2455 // cv-qualification as, or greater cv-qualification than,
2456 // cv2; otherwise, the program is ill-formed.
2457 if (RefRelationship == Sema::Ref_Related) {
2458 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2459 // we would be reference-compatible or reference-compatible with
2460 // added qualification. But that wasn't the case, so the reference
2461 // initialization fails.
2462 return ICS;
2463 }
2464
2465 // If at least one of the types is a class type, the types are not
2466 // related, and we aren't allowed any user conversions, the
2467 // reference binding fails. This case is important for breaking
2468 // recursion, since TryImplicitConversion below will attempt to
2469 // create a temporary through the use of a copy constructor.
2470 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2471 (T1->isRecordType() || T2->isRecordType()))
2472 return ICS;
2473
2474 // C++ [over.ics.ref]p2:
2475 //
2476 // When a parameter of reference type is not bound directly to
2477 // an argument expression, the conversion sequence is the one
2478 // required to convert the argument expression to the
2479 // underlying type of the reference according to
2480 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2481 // to copy-initializing a temporary of the underlying type with
2482 // the argument expression. Any difference in top-level
2483 // cv-qualification is subsumed by the initialization itself
2484 // and does not constitute a conversion.
2485 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2486 /*AllowExplicit=*/false,
2487 /*ForceRValue=*/false,
2488 /*InOverloadResolution=*/false);
2489
2490 // Of course, that's still a reference binding.
2491 if (ICS.isStandard()) {
2492 ICS.Standard.ReferenceBinding = true;
2493 ICS.Standard.RRefBinding = isRValRef;
2494 } else if (ICS.isUserDefined()) {
2495 ICS.UserDefined.After.ReferenceBinding = true;
2496 ICS.UserDefined.After.RRefBinding = isRValRef;
2497 }
2498 return ICS;
2499}
2500
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002501/// TryCopyInitialization - Try to copy-initialize a value of type
2502/// ToType from the expression From. Return the implicit conversion
2503/// sequence required to pass this argument, which may be a bad
2504/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002505/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002506/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2507/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002508ImplicitConversionSequence
2509Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002510 bool SuppressUserConversions, bool ForceRValue,
2511 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002512 if (ToType->isReferenceType())
2513 return TryReferenceInit(*this, From, ToType,
2514 /*FIXME:*/From->getLocStart(),
2515 SuppressUserConversions,
2516 /*AllowExplicit=*/false,
2517 ForceRValue);
2518
2519 return TryImplicitConversion(From, ToType,
2520 SuppressUserConversions,
2521 /*AllowExplicit=*/false,
2522 ForceRValue,
2523 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002524}
2525
Douglas Gregor436424c2008-11-18 23:14:02 +00002526/// TryObjectArgumentInitialization - Try to initialize the object
2527/// parameter of the given member function (@c Method) from the
2528/// expression @p From.
2529ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002530Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002531 CXXMethodDecl *Method,
2532 CXXRecordDecl *ActingContext) {
2533 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002534 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2535 // const volatile object.
2536 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2537 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2538 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002539
2540 // Set up the conversion sequence as a "bad" conversion, to allow us
2541 // to exit early.
2542 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002543
2544 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002545 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002546 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002547 FromType = PT->getPointeeType();
2548
2549 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002550
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002551 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002552 // where X is the class of which the function is a member
2553 // (C++ [over.match.funcs]p4). However, when finding an implicit
2554 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002555 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002556 // (C++ [over.match.funcs]p5). We perform a simplified version of
2557 // reference binding here, that allows class rvalues to bind to
2558 // non-constant references.
2559
2560 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2561 // with the implicit object parameter (C++ [over.match.funcs]p5).
2562 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002563 if (ImplicitParamType.getCVRQualifiers()
2564 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002565 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002566 ICS.setBad(BadConversionSequence::bad_qualifiers,
2567 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002568 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002569 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002570
2571 // Check that we have either the same type or a derived type. It
2572 // affects the conversion rank.
2573 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002574 ImplicitConversionKind SecondKind;
2575 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2576 SecondKind = ICK_Identity;
2577 } else if (IsDerivedFrom(FromType, ClassType))
2578 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002579 else {
John McCall65eb8792010-02-25 01:37:24 +00002580 ICS.setBad(BadConversionSequence::unrelated_class,
2581 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002582 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002583 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002584
2585 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002586 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002587 ICS.Standard.setAsIdentityConversion();
2588 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002589 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002590 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002591 ICS.Standard.ReferenceBinding = true;
2592 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002593 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002594 return ICS;
2595}
2596
2597/// PerformObjectArgumentInitialization - Perform initialization of
2598/// the implicit object parameter for the given Method with the given
2599/// expression.
2600bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002601Sema::PerformObjectArgumentInitialization(Expr *&From,
2602 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002603 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002604 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002605 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002606 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002607 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002608
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002609 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002610 FromRecordType = PT->getPointeeType();
2611 DestType = Method->getThisType(Context);
2612 } else {
2613 FromRecordType = From->getType();
2614 DestType = ImplicitParamRecordType;
2615 }
2616
John McCall6e9f8f62009-12-03 04:06:58 +00002617 // Note that we always use the true parent context when performing
2618 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002619 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002620 = TryObjectArgumentInitialization(From->getType(), Method,
2621 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002622 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002623 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002624 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002625 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002626
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002627 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002628 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002629
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002630 if (!Context.hasSameType(From->getType(), DestType))
2631 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2632 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002633 return false;
2634}
2635
Douglas Gregor5fb53972009-01-14 15:45:31 +00002636/// TryContextuallyConvertToBool - Attempt to contextually convert the
2637/// expression From to bool (C++0x [conv]p3).
2638ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002639 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002640 // FIXME: Are these flags correct?
2641 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002642 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002643 /*ForceRValue=*/false,
2644 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002645}
2646
2647/// PerformContextuallyConvertToBool - Perform a contextual conversion
2648/// of the expression From to bool (C++0x [conv]p3).
2649bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2650 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002651 if (!ICS.isBad())
2652 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002653
Fariborz Jahanian76197412009-11-18 18:26:29 +00002654 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002655 return Diag(From->getSourceRange().getBegin(),
2656 diag::err_typecheck_bool_condition)
2657 << From->getType() << From->getSourceRange();
2658 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002659}
2660
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002661/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002662/// candidate functions, using the given function call arguments. If
2663/// @p SuppressUserConversions, then don't allow user-defined
2664/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002665/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2666/// hacky way to implement the overloading rules for elidable copy
2667/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002668///
2669/// \para PartialOverloading true if we are performing "partial" overloading
2670/// based on an incomplete set of function arguments. This feature is used by
2671/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002672void
2673Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002674 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002675 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002676 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002677 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002678 bool ForceRValue,
2679 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002680 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002681 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002682 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002683 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002684 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002685
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002687 if (!isa<CXXConstructorDecl>(Method)) {
2688 // If we get here, it's because we're calling a member function
2689 // that is named without a member access expression (e.g.,
2690 // "this->f") that was either written explicitly or created
2691 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002692 // function, e.g., X::f(). We use an empty type for the implied
2693 // object argument (C++ [over.call.func]p3), and the acting context
2694 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002695 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002696 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002697 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002698 return;
2699 }
2700 // We treat a constructor like a non-member function, since its object
2701 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002702 }
2703
Douglas Gregorff7028a2009-11-13 23:59:09 +00002704 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002705 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002706
Douglas Gregor27381f32009-11-23 12:27:39 +00002707 // Overload resolution is always an unevaluated context.
2708 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2709
Douglas Gregorffe14e32009-11-14 01:20:54 +00002710 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2711 // C++ [class.copy]p3:
2712 // A member function template is never instantiated to perform the copy
2713 // of a class object to an object of its class type.
2714 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2715 if (NumArgs == 1 &&
2716 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002717 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2718 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002719 return;
2720 }
2721
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002722 // Add this candidate
2723 CandidateSet.push_back(OverloadCandidate());
2724 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002725 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002726 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002727 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002728 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002729 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002730
2731 unsigned NumArgsInProto = Proto->getNumArgs();
2732
2733 // (C++ 13.3.2p2): A candidate function having fewer than m
2734 // parameters is viable only if it has an ellipsis in its parameter
2735 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002736 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2737 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002738 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002739 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002740 return;
2741 }
2742
2743 // (C++ 13.3.2p2): A candidate function having more than m parameters
2744 // is viable only if the (m+1)st parameter has a default argument
2745 // (8.3.6). For the purposes of overload resolution, the
2746 // parameter list is truncated on the right, so that there are
2747 // exactly m parameters.
2748 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002749 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002750 // Not enough arguments.
2751 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002752 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002753 return;
2754 }
2755
2756 // Determine the implicit conversion sequences for each of the
2757 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002758 Candidate.Conversions.resize(NumArgs);
2759 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2760 if (ArgIdx < NumArgsInProto) {
2761 // (C++ 13.3.2p3): for F to be a viable function, there shall
2762 // exist for each argument an implicit conversion sequence
2763 // (13.3.3.1) that converts that argument to the corresponding
2764 // parameter of F.
2765 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002766 Candidate.Conversions[ArgIdx]
2767 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002768 SuppressUserConversions, ForceRValue,
2769 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002770 if (Candidate.Conversions[ArgIdx].isBad()) {
2771 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002772 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002773 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002774 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002775 } else {
2776 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2777 // argument for which there is no corresponding parameter is
2778 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002779 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002780 }
2781 }
2782}
2783
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002784/// \brief Add all of the function declarations in the given function set to
2785/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002786void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002787 Expr **Args, unsigned NumArgs,
2788 OverloadCandidateSet& CandidateSet,
2789 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002790 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002791 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2792 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002793 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002794 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002795 cast<CXXMethodDecl>(FD)->getParent(),
2796 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002797 CandidateSet, SuppressUserConversions);
2798 else
John McCalla0296f72010-03-19 07:35:19 +00002799 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002800 SuppressUserConversions);
2801 } else {
John McCalla0296f72010-03-19 07:35:19 +00002802 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002803 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2804 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002805 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002806 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002807 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002808 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002809 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002810 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002811 else
John McCalla0296f72010-03-19 07:35:19 +00002812 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002813 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002814 Args, NumArgs, CandidateSet,
2815 SuppressUserConversions);
2816 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002817 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002818}
2819
John McCallf0f1cf02009-11-17 07:50:12 +00002820/// AddMethodCandidate - Adds a named decl (which is some kind of
2821/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002822void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002823 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002824 Expr **Args, unsigned NumArgs,
2825 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002826 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002827 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002828 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002829
2830 if (isa<UsingShadowDecl>(Decl))
2831 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2832
2833 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2834 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2835 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002836 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2837 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002838 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002839 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002840 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002841 } else {
John McCalla0296f72010-03-19 07:35:19 +00002842 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002843 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002844 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002845 }
2846}
2847
Douglas Gregor436424c2008-11-18 23:14:02 +00002848/// AddMethodCandidate - Adds the given C++ member function to the set
2849/// of candidate functions, using the given function call arguments
2850/// and the object argument (@c Object). For example, in a call
2851/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2852/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2853/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002854/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002855void
John McCalla0296f72010-03-19 07:35:19 +00002856Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002857 CXXRecordDecl *ActingContext, QualType ObjectType,
2858 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002859 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002860 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002861 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002862 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002863 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002864 assert(!isa<CXXConstructorDecl>(Method) &&
2865 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002866
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002867 if (!CandidateSet.isNewCandidate(Method))
2868 return;
2869
Douglas Gregor27381f32009-11-23 12:27:39 +00002870 // Overload resolution is always an unevaluated context.
2871 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2872
Douglas Gregor436424c2008-11-18 23:14:02 +00002873 // Add this candidate
2874 CandidateSet.push_back(OverloadCandidate());
2875 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002876 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002877 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002878 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002879 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002880
2881 unsigned NumArgsInProto = Proto->getNumArgs();
2882
2883 // (C++ 13.3.2p2): A candidate function having fewer than m
2884 // parameters is viable only if it has an ellipsis in its parameter
2885 // list (8.3.5).
2886 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2887 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002888 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002889 return;
2890 }
2891
2892 // (C++ 13.3.2p2): A candidate function having more than m parameters
2893 // is viable only if the (m+1)st parameter has a default argument
2894 // (8.3.6). For the purposes of overload resolution, the
2895 // parameter list is truncated on the right, so that there are
2896 // exactly m parameters.
2897 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2898 if (NumArgs < MinRequiredArgs) {
2899 // Not enough arguments.
2900 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002901 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002902 return;
2903 }
2904
2905 Candidate.Viable = true;
2906 Candidate.Conversions.resize(NumArgs + 1);
2907
John McCall6e9f8f62009-12-03 04:06:58 +00002908 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002909 // The implicit object argument is ignored.
2910 Candidate.IgnoreObjectArgument = true;
2911 else {
2912 // Determine the implicit conversion sequence for the object
2913 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002914 Candidate.Conversions[0]
2915 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002916 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002917 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002918 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002919 return;
2920 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002921 }
2922
2923 // Determine the implicit conversion sequences for each of the
2924 // arguments.
2925 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2926 if (ArgIdx < NumArgsInProto) {
2927 // (C++ 13.3.2p3): for F to be a viable function, there shall
2928 // exist for each argument an implicit conversion sequence
2929 // (13.3.3.1) that converts that argument to the corresponding
2930 // parameter of F.
2931 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002932 Candidate.Conversions[ArgIdx + 1]
2933 = TryCopyInitialization(Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002934 SuppressUserConversions,
2935 /*ForceRValue=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002936 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002937 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002938 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002939 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002940 break;
2941 }
2942 } else {
2943 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2944 // argument for which there is no corresponding parameter is
2945 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002946 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002947 }
2948 }
2949}
2950
Douglas Gregor97628d62009-08-21 00:16:32 +00002951/// \brief Add a C++ member function template as a candidate to the candidate
2952/// set, using template argument deduction to produce an appropriate member
2953/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002954void
Douglas Gregor97628d62009-08-21 00:16:32 +00002955Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00002956 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002957 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002958 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002959 QualType ObjectType,
2960 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002961 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002962 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002963 if (!CandidateSet.isNewCandidate(MethodTmpl))
2964 return;
2965
Douglas Gregor97628d62009-08-21 00:16:32 +00002966 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002967 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002968 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002969 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002970 // candidate functions in the usual way.113) A given name can refer to one
2971 // or more function templates and also to a set of overloaded non-template
2972 // functions. In such a case, the candidate functions generated from each
2973 // function template are combined with the set of non-template candidate
2974 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002975 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002976 FunctionDecl *Specialization = 0;
2977 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002978 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002979 Args, NumArgs, Specialization, Info)) {
2980 // FIXME: Record what happened with template argument deduction, so
2981 // that we can give the user a beautiful diagnostic.
2982 (void)Result;
2983 return;
2984 }
Mike Stump11289f42009-09-09 15:08:12 +00002985
Douglas Gregor97628d62009-08-21 00:16:32 +00002986 // Add the function template specialization produced by template argument
2987 // deduction as a candidate.
2988 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002989 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002990 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00002991 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002992 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002993 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00002994}
2995
Douglas Gregor05155d82009-08-21 23:19:43 +00002996/// \brief Add a C++ function template specialization as a candidate
2997/// in the candidate set, using template argument deduction to produce
2998/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002999void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003000Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003001 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003002 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003003 Expr **Args, unsigned NumArgs,
3004 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003005 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003006 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3007 return;
3008
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003009 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003010 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003011 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003012 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003013 // candidate functions in the usual way.113) A given name can refer to one
3014 // or more function templates and also to a set of overloaded non-template
3015 // functions. In such a case, the candidate functions generated from each
3016 // function template are combined with the set of non-template candidate
3017 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003018 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003019 FunctionDecl *Specialization = 0;
3020 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003021 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003022 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003023 CandidateSet.push_back(OverloadCandidate());
3024 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003025 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003026 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3027 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003028 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003029 Candidate.IsSurrogate = false;
3030 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003031
3032 // TODO: record more information about failed template arguments
3033 Candidate.DeductionFailure.Result = Result;
3034 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003035 return;
3036 }
Mike Stump11289f42009-09-09 15:08:12 +00003037
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003038 // Add the function template specialization produced by template argument
3039 // deduction as a candidate.
3040 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003041 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003042 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003043}
Mike Stump11289f42009-09-09 15:08:12 +00003044
Douglas Gregora1f013e2008-11-07 22:36:19 +00003045/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003046/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003047/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003048/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003049/// (which may or may not be the same type as the type that the
3050/// conversion function produces).
3051void
3052Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003053 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003054 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003055 Expr *From, QualType ToType,
3056 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003057 assert(!Conversion->getDescribedFunctionTemplate() &&
3058 "Conversion function templates use AddTemplateConversionCandidate");
3059
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003060 if (!CandidateSet.isNewCandidate(Conversion))
3061 return;
3062
Douglas Gregor27381f32009-11-23 12:27:39 +00003063 // Overload resolution is always an unevaluated context.
3064 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3065
Douglas Gregora1f013e2008-11-07 22:36:19 +00003066 // Add this candidate
3067 CandidateSet.push_back(OverloadCandidate());
3068 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003069 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003070 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003071 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003072 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003073 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00003074 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003075 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003076
Douglas Gregor436424c2008-11-18 23:14:02 +00003077 // Determine the implicit conversion sequence for the implicit
3078 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003079 Candidate.Viable = true;
3080 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003081 Candidate.Conversions[0]
3082 = TryObjectArgumentInitialization(From->getType(), Conversion,
3083 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003084 // Conversion functions to a different type in the base class is visible in
3085 // the derived class. So, a derived to base conversion should not participate
3086 // in overload resolution.
3087 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3088 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003089 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003090 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003091 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003092 return;
3093 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003094
3095 // We won't go through a user-define type conversion function to convert a
3096 // derived to base as such conversions are given Conversion Rank. They only
3097 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3098 QualType FromCanon
3099 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3100 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3101 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3102 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003103 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003104 return;
3105 }
3106
Douglas Gregora1f013e2008-11-07 22:36:19 +00003107
3108 // To determine what the conversion from the result of calling the
3109 // conversion function to the type we're eventually trying to
3110 // convert to (ToType), we need to synthesize a call to the
3111 // conversion function and attempt copy initialization from it. This
3112 // makes sure that we get the right semantics with respect to
3113 // lvalues/rvalues and the type. Fortunately, we can allocate this
3114 // call on the stack and we don't need its arguments to be
3115 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003116 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003117 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003118 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003119 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00003120 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00003121
3122 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003123 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3124 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003125 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003126 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003127 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003128 ImplicitConversionSequence ICS =
3129 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003130 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003131 /*ForceRValue=*/false,
3132 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003133
John McCall0d1da222010-01-12 00:44:57 +00003134 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003135 case ImplicitConversionSequence::StandardConversion:
3136 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003137
3138 // C++ [over.ics.user]p3:
3139 // If the user-defined conversion is specified by a specialization of a
3140 // conversion function template, the second standard conversion sequence
3141 // shall have exact match rank.
3142 if (Conversion->getPrimaryTemplate() &&
3143 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3144 Candidate.Viable = false;
3145 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3146 }
3147
Douglas Gregora1f013e2008-11-07 22:36:19 +00003148 break;
3149
3150 case ImplicitConversionSequence::BadConversion:
3151 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003152 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003153 break;
3154
3155 default:
Mike Stump11289f42009-09-09 15:08:12 +00003156 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003157 "Can only end up with a standard conversion sequence or failure");
3158 }
3159}
3160
Douglas Gregor05155d82009-08-21 23:19:43 +00003161/// \brief Adds a conversion function template specialization
3162/// candidate to the overload set, using template argument deduction
3163/// to deduce the template arguments of the conversion function
3164/// template from the type that we are converting to (C++
3165/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003166void
Douglas Gregor05155d82009-08-21 23:19:43 +00003167Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003168 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003169 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003170 Expr *From, QualType ToType,
3171 OverloadCandidateSet &CandidateSet) {
3172 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3173 "Only conversion function templates permitted here");
3174
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003175 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3176 return;
3177
John McCallbc077cf2010-02-08 23:07:23 +00003178 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003179 CXXConversionDecl *Specialization = 0;
3180 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003181 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003182 Specialization, Info)) {
3183 // FIXME: Record what happened with template argument deduction, so
3184 // that we can give the user a beautiful diagnostic.
3185 (void)Result;
3186 return;
3187 }
Mike Stump11289f42009-09-09 15:08:12 +00003188
Douglas Gregor05155d82009-08-21 23:19:43 +00003189 // Add the conversion function template specialization produced by
3190 // template argument deduction as a candidate.
3191 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003192 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003193 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003194}
3195
Douglas Gregorab7897a2008-11-19 22:57:39 +00003196/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3197/// converts the given @c Object to a function pointer via the
3198/// conversion function @c Conversion, and then attempts to call it
3199/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3200/// the type of function that we'll eventually be calling.
3201void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003202 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003203 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003204 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003205 QualType ObjectType,
3206 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003207 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003208 if (!CandidateSet.isNewCandidate(Conversion))
3209 return;
3210
Douglas Gregor27381f32009-11-23 12:27:39 +00003211 // Overload resolution is always an unevaluated context.
3212 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3213
Douglas Gregorab7897a2008-11-19 22:57:39 +00003214 CandidateSet.push_back(OverloadCandidate());
3215 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003216 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003217 Candidate.Function = 0;
3218 Candidate.Surrogate = Conversion;
3219 Candidate.Viable = true;
3220 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003221 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003222 Candidate.Conversions.resize(NumArgs + 1);
3223
3224 // Determine the implicit conversion sequence for the implicit
3225 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003226 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003227 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003228 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003229 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003230 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003231 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003232 return;
3233 }
3234
3235 // The first conversion is actually a user-defined conversion whose
3236 // first conversion is ObjectInit's standard conversion (which is
3237 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003238 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003239 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003240 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003241 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003242 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003243 = Candidate.Conversions[0].UserDefined.Before;
3244 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3245
Mike Stump11289f42009-09-09 15:08:12 +00003246 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003247 unsigned NumArgsInProto = Proto->getNumArgs();
3248
3249 // (C++ 13.3.2p2): A candidate function having fewer than m
3250 // parameters is viable only if it has an ellipsis in its parameter
3251 // list (8.3.5).
3252 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3253 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003254 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003255 return;
3256 }
3257
3258 // Function types don't have any default arguments, so just check if
3259 // we have enough arguments.
3260 if (NumArgs < NumArgsInProto) {
3261 // Not enough arguments.
3262 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003263 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003264 return;
3265 }
3266
3267 // Determine the implicit conversion sequences for each of the
3268 // arguments.
3269 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3270 if (ArgIdx < NumArgsInProto) {
3271 // (C++ 13.3.2p3): for F to be a viable function, there shall
3272 // exist for each argument an implicit conversion sequence
3273 // (13.3.3.1) that converts that argument to the corresponding
3274 // parameter of F.
3275 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003276 Candidate.Conversions[ArgIdx + 1]
3277 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003278 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003279 /*ForceRValue=*/false,
3280 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003281 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003282 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003283 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003284 break;
3285 }
3286 } else {
3287 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3288 // argument for which there is no corresponding parameter is
3289 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003290 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003291 }
3292 }
3293}
3294
Mike Stump87c57ac2009-05-16 07:39:55 +00003295// FIXME: This will eventually be removed, once we've migrated all of the
3296// operator overloading logic over to the scheme used by binary operators, which
3297// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003298void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003299 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003300 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003301 OverloadCandidateSet& CandidateSet,
3302 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003303 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003304
3305 QualType T1 = Args[0]->getType();
3306 QualType T2;
3307 if (NumArgs > 1)
3308 T2 = Args[1]->getType();
3309
3310 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003311 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003312 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3313 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3314 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3315 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003316 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003317 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003318}
3319
3320/// \brief Add overload candidates for overloaded operators that are
3321/// member functions.
3322///
3323/// Add the overloaded operator candidates that are member functions
3324/// for the operator Op that was used in an operator expression such
3325/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3326/// CandidateSet will store the added overload candidates. (C++
3327/// [over.match.oper]).
3328void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3329 SourceLocation OpLoc,
3330 Expr **Args, unsigned NumArgs,
3331 OverloadCandidateSet& CandidateSet,
3332 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003333 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3334
3335 // C++ [over.match.oper]p3:
3336 // For a unary operator @ with an operand of a type whose
3337 // cv-unqualified version is T1, and for a binary operator @ with
3338 // a left operand of a type whose cv-unqualified version is T1 and
3339 // a right operand of a type whose cv-unqualified version is T2,
3340 // three sets of candidate functions, designated member
3341 // candidates, non-member candidates and built-in candidates, are
3342 // constructed as follows:
3343 QualType T1 = Args[0]->getType();
3344 QualType T2;
3345 if (NumArgs > 1)
3346 T2 = Args[1]->getType();
3347
3348 // -- If T1 is a class type, the set of member candidates is the
3349 // result of the qualified lookup of T1::operator@
3350 // (13.3.1.1.1); otherwise, the set of member candidates is
3351 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003352 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003353 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003354 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003355 return;
Mike Stump11289f42009-09-09 15:08:12 +00003356
John McCall27b18f82009-11-17 02:14:36 +00003357 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3358 LookupQualifiedName(Operators, T1Rec->getDecl());
3359 Operators.suppressDiagnostics();
3360
Mike Stump11289f42009-09-09 15:08:12 +00003361 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003362 OperEnd = Operators.end();
3363 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003364 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003365 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003366 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003367 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003368 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003369}
3370
Douglas Gregora11693b2008-11-12 17:17:38 +00003371/// AddBuiltinCandidate - Add a candidate for a built-in
3372/// operator. ResultTy and ParamTys are the result and parameter types
3373/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003374/// arguments being passed to the candidate. IsAssignmentOperator
3375/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003376/// operator. NumContextualBoolArguments is the number of arguments
3377/// (at the beginning of the argument list) that will be contextually
3378/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003379void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003380 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003381 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003382 bool IsAssignmentOperator,
3383 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003384 // Overload resolution is always an unevaluated context.
3385 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3386
Douglas Gregora11693b2008-11-12 17:17:38 +00003387 // Add this candidate
3388 CandidateSet.push_back(OverloadCandidate());
3389 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003390 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003391 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003392 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003393 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003394 Candidate.BuiltinTypes.ResultTy = ResultTy;
3395 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3396 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3397
3398 // Determine the implicit conversion sequences for each of the
3399 // arguments.
3400 Candidate.Viable = true;
3401 Candidate.Conversions.resize(NumArgs);
3402 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003403 // C++ [over.match.oper]p4:
3404 // For the built-in assignment operators, conversions of the
3405 // left operand are restricted as follows:
3406 // -- no temporaries are introduced to hold the left operand, and
3407 // -- no user-defined conversions are applied to the left
3408 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003409 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003410 //
3411 // We block these conversions by turning off user-defined
3412 // conversions, since that is the only way that initialization of
3413 // a reference to a non-class type can occur from something that
3414 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003415 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003416 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003417 "Contextual conversion to bool requires bool type");
3418 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3419 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003420 Candidate.Conversions[ArgIdx]
3421 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003422 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003423 /*ForceRValue=*/false,
3424 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003425 }
John McCall0d1da222010-01-12 00:44:57 +00003426 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003427 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003428 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003429 break;
3430 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003431 }
3432}
3433
3434/// BuiltinCandidateTypeSet - A set of types that will be used for the
3435/// candidate operator functions for built-in operators (C++
3436/// [over.built]). The types are separated into pointer types and
3437/// enumeration types.
3438class BuiltinCandidateTypeSet {
3439 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003440 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003441
3442 /// PointerTypes - The set of pointer types that will be used in the
3443 /// built-in candidates.
3444 TypeSet PointerTypes;
3445
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003446 /// MemberPointerTypes - The set of member pointer types that will be
3447 /// used in the built-in candidates.
3448 TypeSet MemberPointerTypes;
3449
Douglas Gregora11693b2008-11-12 17:17:38 +00003450 /// EnumerationTypes - The set of enumeration types that will be
3451 /// used in the built-in candidates.
3452 TypeSet EnumerationTypes;
3453
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003454 /// Sema - The semantic analysis instance where we are building the
3455 /// candidate type set.
3456 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003457
Douglas Gregora11693b2008-11-12 17:17:38 +00003458 /// Context - The AST context in which we will build the type sets.
3459 ASTContext &Context;
3460
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003461 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3462 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003463 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003464
3465public:
3466 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003467 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003468
Mike Stump11289f42009-09-09 15:08:12 +00003469 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003470 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003471
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003472 void AddTypesConvertedFrom(QualType Ty,
3473 SourceLocation Loc,
3474 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003475 bool AllowExplicitConversions,
3476 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003477
3478 /// pointer_begin - First pointer type found;
3479 iterator pointer_begin() { return PointerTypes.begin(); }
3480
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003481 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003482 iterator pointer_end() { return PointerTypes.end(); }
3483
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003484 /// member_pointer_begin - First member pointer type found;
3485 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3486
3487 /// member_pointer_end - Past the last member pointer type found;
3488 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3489
Douglas Gregora11693b2008-11-12 17:17:38 +00003490 /// enumeration_begin - First enumeration type found;
3491 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3492
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003493 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003494 iterator enumeration_end() { return EnumerationTypes.end(); }
3495};
3496
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003497/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003498/// the set of pointer types along with any more-qualified variants of
3499/// that type. For example, if @p Ty is "int const *", this routine
3500/// will add "int const *", "int const volatile *", "int const
3501/// restrict *", and "int const volatile restrict *" to the set of
3502/// pointer types. Returns true if the add of @p Ty itself succeeded,
3503/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003504///
3505/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003506bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003507BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3508 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003509
Douglas Gregora11693b2008-11-12 17:17:38 +00003510 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003511 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003512 return false;
3513
John McCall8ccfcb52009-09-24 19:53:00 +00003514 const PointerType *PointerTy = Ty->getAs<PointerType>();
3515 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003516
John McCall8ccfcb52009-09-24 19:53:00 +00003517 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003518 // Don't add qualified variants of arrays. For one, they're not allowed
3519 // (the qualifier would sink to the element type), and for another, the
3520 // only overload situation where it matters is subscript or pointer +- int,
3521 // and those shouldn't have qualifier variants anyway.
3522 if (PointeeTy->isArrayType())
3523 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003524 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003525 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003526 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003527 bool hasVolatile = VisibleQuals.hasVolatile();
3528 bool hasRestrict = VisibleQuals.hasRestrict();
3529
John McCall8ccfcb52009-09-24 19:53:00 +00003530 // Iterate through all strict supersets of BaseCVR.
3531 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3532 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003533 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3534 // in the types.
3535 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3536 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003537 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3538 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003539 }
3540
3541 return true;
3542}
3543
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003544/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3545/// to the set of pointer types along with any more-qualified variants of
3546/// that type. For example, if @p Ty is "int const *", this routine
3547/// will add "int const *", "int const volatile *", "int const
3548/// restrict *", and "int const volatile restrict *" to the set of
3549/// pointer types. Returns true if the add of @p Ty itself succeeded,
3550/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003551///
3552/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003553bool
3554BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3555 QualType Ty) {
3556 // Insert this type.
3557 if (!MemberPointerTypes.insert(Ty))
3558 return false;
3559
John McCall8ccfcb52009-09-24 19:53:00 +00003560 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3561 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003562
John McCall8ccfcb52009-09-24 19:53:00 +00003563 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003564 // Don't add qualified variants of arrays. For one, they're not allowed
3565 // (the qualifier would sink to the element type), and for another, the
3566 // only overload situation where it matters is subscript or pointer +- int,
3567 // and those shouldn't have qualifier variants anyway.
3568 if (PointeeTy->isArrayType())
3569 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003570 const Type *ClassTy = PointerTy->getClass();
3571
3572 // Iterate through all strict supersets of the pointee type's CVR
3573 // qualifiers.
3574 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3575 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3576 if ((CVR | BaseCVR) != CVR) continue;
3577
3578 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3579 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003580 }
3581
3582 return true;
3583}
3584
Douglas Gregora11693b2008-11-12 17:17:38 +00003585/// AddTypesConvertedFrom - Add each of the types to which the type @p
3586/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003587/// primarily interested in pointer types and enumeration types. We also
3588/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003589/// AllowUserConversions is true if we should look at the conversion
3590/// functions of a class type, and AllowExplicitConversions if we
3591/// should also include the explicit conversion functions of a class
3592/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003593void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003594BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003595 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003596 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003597 bool AllowExplicitConversions,
3598 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003599 // Only deal with canonical types.
3600 Ty = Context.getCanonicalType(Ty);
3601
3602 // Look through reference types; they aren't part of the type of an
3603 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003604 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003605 Ty = RefTy->getPointeeType();
3606
3607 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003608 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003609
Sebastian Redl65ae2002009-11-05 16:36:20 +00003610 // If we're dealing with an array type, decay to the pointer.
3611 if (Ty->isArrayType())
3612 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3613
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003614 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003615 QualType PointeeTy = PointerTy->getPointeeType();
3616
3617 // Insert our type, and its more-qualified variants, into the set
3618 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003619 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003620 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003621 } else if (Ty->isMemberPointerType()) {
3622 // Member pointers are far easier, since the pointee can't be converted.
3623 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3624 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003625 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003626 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003627 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003628 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003629 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003630 // No conversion functions in incomplete types.
3631 return;
3632 }
Mike Stump11289f42009-09-09 15:08:12 +00003633
Douglas Gregora11693b2008-11-12 17:17:38 +00003634 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003635 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003636 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003637 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003638 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003639 NamedDecl *D = I.getDecl();
3640 if (isa<UsingShadowDecl>(D))
3641 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003642
Mike Stump11289f42009-09-09 15:08:12 +00003643 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003644 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003645 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003646 continue;
3647
John McCallda4458e2010-03-31 01:36:47 +00003648 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003649 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003650 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003651 VisibleQuals);
3652 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003653 }
3654 }
3655 }
3656}
3657
Douglas Gregor84605ae2009-08-24 13:43:27 +00003658/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3659/// the volatile- and non-volatile-qualified assignment operators for the
3660/// given type to the candidate set.
3661static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3662 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003663 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003664 unsigned NumArgs,
3665 OverloadCandidateSet &CandidateSet) {
3666 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003667
Douglas Gregor84605ae2009-08-24 13:43:27 +00003668 // T& operator=(T&, T)
3669 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3670 ParamTypes[1] = T;
3671 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3672 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003673
Douglas Gregor84605ae2009-08-24 13:43:27 +00003674 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3675 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003676 ParamTypes[0]
3677 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003678 ParamTypes[1] = T;
3679 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003680 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003681 }
3682}
Mike Stump11289f42009-09-09 15:08:12 +00003683
Sebastian Redl1054fae2009-10-25 17:03:50 +00003684/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3685/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003686static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3687 Qualifiers VRQuals;
3688 const RecordType *TyRec;
3689 if (const MemberPointerType *RHSMPType =
3690 ArgExpr->getType()->getAs<MemberPointerType>())
3691 TyRec = cast<RecordType>(RHSMPType->getClass());
3692 else
3693 TyRec = ArgExpr->getType()->getAs<RecordType>();
3694 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003695 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003696 VRQuals.addVolatile();
3697 VRQuals.addRestrict();
3698 return VRQuals;
3699 }
3700
3701 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003702 if (!ClassDecl->hasDefinition())
3703 return VRQuals;
3704
John McCallad371252010-01-20 00:46:10 +00003705 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003706 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003707
John McCallad371252010-01-20 00:46:10 +00003708 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003709 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003710 NamedDecl *D = I.getDecl();
3711 if (isa<UsingShadowDecl>(D))
3712 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3713 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003714 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3715 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3716 CanTy = ResTypeRef->getPointeeType();
3717 // Need to go down the pointer/mempointer chain and add qualifiers
3718 // as see them.
3719 bool done = false;
3720 while (!done) {
3721 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3722 CanTy = ResTypePtr->getPointeeType();
3723 else if (const MemberPointerType *ResTypeMPtr =
3724 CanTy->getAs<MemberPointerType>())
3725 CanTy = ResTypeMPtr->getPointeeType();
3726 else
3727 done = true;
3728 if (CanTy.isVolatileQualified())
3729 VRQuals.addVolatile();
3730 if (CanTy.isRestrictQualified())
3731 VRQuals.addRestrict();
3732 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3733 return VRQuals;
3734 }
3735 }
3736 }
3737 return VRQuals;
3738}
3739
Douglas Gregord08452f2008-11-19 15:42:04 +00003740/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3741/// operator overloads to the candidate set (C++ [over.built]), based
3742/// on the operator @p Op and the arguments given. For example, if the
3743/// operator is a binary '+', this routine might add "int
3744/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003745void
Mike Stump11289f42009-09-09 15:08:12 +00003746Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003747 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003748 Expr **Args, unsigned NumArgs,
3749 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003750 // The set of "promoted arithmetic types", which are the arithmetic
3751 // types are that preserved by promotion (C++ [over.built]p2). Note
3752 // that the first few of these types are the promoted integral
3753 // types; these types need to be first.
3754 // FIXME: What about complex?
3755 const unsigned FirstIntegralType = 0;
3756 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003757 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003758 LastPromotedIntegralType = 13;
3759 const unsigned FirstPromotedArithmeticType = 7,
3760 LastPromotedArithmeticType = 16;
3761 const unsigned NumArithmeticTypes = 16;
3762 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003763 Context.BoolTy, Context.CharTy, Context.WCharTy,
3764// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003765 Context.SignedCharTy, Context.ShortTy,
3766 Context.UnsignedCharTy, Context.UnsignedShortTy,
3767 Context.IntTy, Context.LongTy, Context.LongLongTy,
3768 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3769 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3770 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003771 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3772 "Invalid first promoted integral type");
3773 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3774 == Context.UnsignedLongLongTy &&
3775 "Invalid last promoted integral type");
3776 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3777 "Invalid first promoted arithmetic type");
3778 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3779 == Context.LongDoubleTy &&
3780 "Invalid last promoted arithmetic type");
3781
Douglas Gregora11693b2008-11-12 17:17:38 +00003782 // Find all of the types that the arguments can convert to, but only
3783 // if the operator we're looking at has built-in operator candidates
3784 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003785 Qualifiers VisibleTypeConversionsQuals;
3786 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003787 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3788 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3789
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003790 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003791 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3792 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003793 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003794 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003795 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003796 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003797 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003798 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003799 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003800 true,
3801 (Op == OO_Exclaim ||
3802 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003803 Op == OO_PipePipe),
3804 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003805 }
3806
3807 bool isComparison = false;
3808 switch (Op) {
3809 case OO_None:
3810 case NUM_OVERLOADED_OPERATORS:
3811 assert(false && "Expected an overloaded operator");
3812 break;
3813
Douglas Gregord08452f2008-11-19 15:42:04 +00003814 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003815 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003816 goto UnaryStar;
3817 else
3818 goto BinaryStar;
3819 break;
3820
3821 case OO_Plus: // '+' is either unary or binary
3822 if (NumArgs == 1)
3823 goto UnaryPlus;
3824 else
3825 goto BinaryPlus;
3826 break;
3827
3828 case OO_Minus: // '-' is either unary or binary
3829 if (NumArgs == 1)
3830 goto UnaryMinus;
3831 else
3832 goto BinaryMinus;
3833 break;
3834
3835 case OO_Amp: // '&' is either unary or binary
3836 if (NumArgs == 1)
3837 goto UnaryAmp;
3838 else
3839 goto BinaryAmp;
3840
3841 case OO_PlusPlus:
3842 case OO_MinusMinus:
3843 // C++ [over.built]p3:
3844 //
3845 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3846 // is either volatile or empty, there exist candidate operator
3847 // functions of the form
3848 //
3849 // VQ T& operator++(VQ T&);
3850 // T operator++(VQ T&, int);
3851 //
3852 // C++ [over.built]p4:
3853 //
3854 // For every pair (T, VQ), where T is an arithmetic type other
3855 // than bool, and VQ is either volatile or empty, there exist
3856 // candidate operator functions of the form
3857 //
3858 // VQ T& operator--(VQ T&);
3859 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003860 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003861 Arith < NumArithmeticTypes; ++Arith) {
3862 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003863 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003864 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003865
3866 // Non-volatile version.
3867 if (NumArgs == 1)
3868 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3869 else
3870 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003871 // heuristic to reduce number of builtin candidates in the set.
3872 // Add volatile version only if there are conversions to a volatile type.
3873 if (VisibleTypeConversionsQuals.hasVolatile()) {
3874 // Volatile version
3875 ParamTypes[0]
3876 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3877 if (NumArgs == 1)
3878 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3879 else
3880 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3881 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003882 }
3883
3884 // C++ [over.built]p5:
3885 //
3886 // For every pair (T, VQ), where T is a cv-qualified or
3887 // cv-unqualified object type, and VQ is either volatile or
3888 // empty, there exist candidate operator functions of the form
3889 //
3890 // T*VQ& operator++(T*VQ&);
3891 // T*VQ& operator--(T*VQ&);
3892 // T* operator++(T*VQ&, int);
3893 // T* operator--(T*VQ&, int);
3894 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3895 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3896 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003897 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003898 continue;
3899
Mike Stump11289f42009-09-09 15:08:12 +00003900 QualType ParamTypes[2] = {
3901 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003902 };
Mike Stump11289f42009-09-09 15:08:12 +00003903
Douglas Gregord08452f2008-11-19 15:42:04 +00003904 // Without volatile
3905 if (NumArgs == 1)
3906 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3907 else
3908 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3909
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003910 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3911 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003912 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003913 ParamTypes[0]
3914 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003915 if (NumArgs == 1)
3916 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3917 else
3918 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3919 }
3920 }
3921 break;
3922
3923 UnaryStar:
3924 // C++ [over.built]p6:
3925 // For every cv-qualified or cv-unqualified object type T, there
3926 // exist candidate operator functions of the form
3927 //
3928 // T& operator*(T*);
3929 //
3930 // C++ [over.built]p7:
3931 // For every function type T, there exist candidate operator
3932 // functions of the form
3933 // T& operator*(T*);
3934 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3935 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3936 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003937 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003938 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003939 &ParamTy, Args, 1, CandidateSet);
3940 }
3941 break;
3942
3943 UnaryPlus:
3944 // C++ [over.built]p8:
3945 // For every type T, there exist candidate operator functions of
3946 // the form
3947 //
3948 // T* operator+(T*);
3949 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3950 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3951 QualType ParamTy = *Ptr;
3952 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3953 }
Mike Stump11289f42009-09-09 15:08:12 +00003954
Douglas Gregord08452f2008-11-19 15:42:04 +00003955 // Fall through
3956
3957 UnaryMinus:
3958 // C++ [over.built]p9:
3959 // For every promoted arithmetic type T, there exist candidate
3960 // operator functions of the form
3961 //
3962 // T operator+(T);
3963 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003964 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003965 Arith < LastPromotedArithmeticType; ++Arith) {
3966 QualType ArithTy = ArithmeticTypes[Arith];
3967 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3968 }
3969 break;
3970
3971 case OO_Tilde:
3972 // C++ [over.built]p10:
3973 // For every promoted integral type T, there exist candidate
3974 // operator functions of the form
3975 //
3976 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003977 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003978 Int < LastPromotedIntegralType; ++Int) {
3979 QualType IntTy = ArithmeticTypes[Int];
3980 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3981 }
3982 break;
3983
Douglas Gregora11693b2008-11-12 17:17:38 +00003984 case OO_New:
3985 case OO_Delete:
3986 case OO_Array_New:
3987 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003988 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003989 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003990 break;
3991
3992 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003993 UnaryAmp:
3994 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003995 // C++ [over.match.oper]p3:
3996 // -- For the operator ',', the unary operator '&', or the
3997 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003998 break;
3999
Douglas Gregor84605ae2009-08-24 13:43:27 +00004000 case OO_EqualEqual:
4001 case OO_ExclaimEqual:
4002 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004003 // For every pointer to member type T, there exist candidate operator
4004 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004005 //
4006 // bool operator==(T,T);
4007 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004008 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004009 MemPtr = CandidateTypes.member_pointer_begin(),
4010 MemPtrEnd = CandidateTypes.member_pointer_end();
4011 MemPtr != MemPtrEnd;
4012 ++MemPtr) {
4013 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4014 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4015 }
Mike Stump11289f42009-09-09 15:08:12 +00004016
Douglas Gregor84605ae2009-08-24 13:43:27 +00004017 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004018
Douglas Gregora11693b2008-11-12 17:17:38 +00004019 case OO_Less:
4020 case OO_Greater:
4021 case OO_LessEqual:
4022 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004023 // C++ [over.built]p15:
4024 //
4025 // For every pointer or enumeration type T, there exist
4026 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004027 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004028 // bool operator<(T, T);
4029 // bool operator>(T, T);
4030 // bool operator<=(T, T);
4031 // bool operator>=(T, T);
4032 // bool operator==(T, T);
4033 // bool operator!=(T, T);
4034 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4035 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4036 QualType ParamTypes[2] = { *Ptr, *Ptr };
4037 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4038 }
Mike Stump11289f42009-09-09 15:08:12 +00004039 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004040 = CandidateTypes.enumeration_begin();
4041 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4042 QualType ParamTypes[2] = { *Enum, *Enum };
4043 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4044 }
4045
4046 // Fall through.
4047 isComparison = true;
4048
Douglas Gregord08452f2008-11-19 15:42:04 +00004049 BinaryPlus:
4050 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004051 if (!isComparison) {
4052 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4053
4054 // C++ [over.built]p13:
4055 //
4056 // For every cv-qualified or cv-unqualified object type T
4057 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004058 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004059 // T* operator+(T*, ptrdiff_t);
4060 // T& operator[](T*, ptrdiff_t); [BELOW]
4061 // T* operator-(T*, ptrdiff_t);
4062 // T* operator+(ptrdiff_t, T*);
4063 // T& operator[](ptrdiff_t, T*); [BELOW]
4064 //
4065 // C++ [over.built]p14:
4066 //
4067 // For every T, where T is a pointer to object type, there
4068 // exist candidate operator functions of the form
4069 //
4070 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004071 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004072 = CandidateTypes.pointer_begin();
4073 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4074 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4075
4076 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4077 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4078
4079 if (Op == OO_Plus) {
4080 // T* operator+(ptrdiff_t, T*);
4081 ParamTypes[0] = ParamTypes[1];
4082 ParamTypes[1] = *Ptr;
4083 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4084 } else {
4085 // ptrdiff_t operator-(T, T);
4086 ParamTypes[1] = *Ptr;
4087 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4088 Args, 2, CandidateSet);
4089 }
4090 }
4091 }
4092 // Fall through
4093
Douglas Gregora11693b2008-11-12 17:17:38 +00004094 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004095 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004096 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004097 // C++ [over.built]p12:
4098 //
4099 // For every pair of promoted arithmetic types L and R, there
4100 // exist candidate operator functions of the form
4101 //
4102 // LR operator*(L, R);
4103 // LR operator/(L, R);
4104 // LR operator+(L, R);
4105 // LR operator-(L, R);
4106 // bool operator<(L, R);
4107 // bool operator>(L, R);
4108 // bool operator<=(L, R);
4109 // bool operator>=(L, R);
4110 // bool operator==(L, R);
4111 // bool operator!=(L, R);
4112 //
4113 // where LR is the result of the usual arithmetic conversions
4114 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004115 //
4116 // C++ [over.built]p24:
4117 //
4118 // For every pair of promoted arithmetic types L and R, there exist
4119 // candidate operator functions of the form
4120 //
4121 // LR operator?(bool, L, R);
4122 //
4123 // where LR is the result of the usual arithmetic conversions
4124 // between types L and R.
4125 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004126 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004127 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004128 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004129 Right < LastPromotedArithmeticType; ++Right) {
4130 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004131 QualType Result
4132 = isComparison
4133 ? Context.BoolTy
4134 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004135 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4136 }
4137 }
4138 break;
4139
4140 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004141 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004142 case OO_Caret:
4143 case OO_Pipe:
4144 case OO_LessLess:
4145 case OO_GreaterGreater:
4146 // C++ [over.built]p17:
4147 //
4148 // For every pair of promoted integral types L and R, there
4149 // exist candidate operator functions of the form
4150 //
4151 // LR operator%(L, R);
4152 // LR operator&(L, R);
4153 // LR operator^(L, R);
4154 // LR operator|(L, R);
4155 // L operator<<(L, R);
4156 // L operator>>(L, R);
4157 //
4158 // where LR is the result of the usual arithmetic conversions
4159 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004160 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004161 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004162 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004163 Right < LastPromotedIntegralType; ++Right) {
4164 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4165 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4166 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004167 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004168 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4169 }
4170 }
4171 break;
4172
4173 case OO_Equal:
4174 // C++ [over.built]p20:
4175 //
4176 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004177 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004178 // empty, there exist candidate operator functions of the form
4179 //
4180 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004181 for (BuiltinCandidateTypeSet::iterator
4182 Enum = CandidateTypes.enumeration_begin(),
4183 EnumEnd = CandidateTypes.enumeration_end();
4184 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004185 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004186 CandidateSet);
4187 for (BuiltinCandidateTypeSet::iterator
4188 MemPtr = CandidateTypes.member_pointer_begin(),
4189 MemPtrEnd = CandidateTypes.member_pointer_end();
4190 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004191 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004192 CandidateSet);
4193 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004194
4195 case OO_PlusEqual:
4196 case OO_MinusEqual:
4197 // C++ [over.built]p19:
4198 //
4199 // For every pair (T, VQ), where T is any type and VQ is either
4200 // volatile or empty, there exist candidate operator functions
4201 // of the form
4202 //
4203 // T*VQ& operator=(T*VQ&, T*);
4204 //
4205 // C++ [over.built]p21:
4206 //
4207 // For every pair (T, VQ), where T is a cv-qualified or
4208 // cv-unqualified object type and VQ is either volatile or
4209 // empty, there exist candidate operator functions of the form
4210 //
4211 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4212 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4213 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4214 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4215 QualType ParamTypes[2];
4216 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4217
4218 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004219 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004220 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4221 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004222
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004223 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4224 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004225 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004226 ParamTypes[0]
4227 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004228 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4229 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004230 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004231 }
4232 // Fall through.
4233
4234 case OO_StarEqual:
4235 case OO_SlashEqual:
4236 // C++ [over.built]p18:
4237 //
4238 // For every triple (L, VQ, R), where L is an arithmetic type,
4239 // VQ is either volatile or empty, and R is a promoted
4240 // arithmetic type, there exist candidate operator functions of
4241 // the form
4242 //
4243 // VQ L& operator=(VQ L&, R);
4244 // VQ L& operator*=(VQ L&, R);
4245 // VQ L& operator/=(VQ L&, R);
4246 // VQ L& operator+=(VQ L&, R);
4247 // VQ L& operator-=(VQ L&, R);
4248 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004249 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004250 Right < LastPromotedArithmeticType; ++Right) {
4251 QualType ParamTypes[2];
4252 ParamTypes[1] = ArithmeticTypes[Right];
4253
4254 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004255 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004256 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4257 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004258
4259 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004260 if (VisibleTypeConversionsQuals.hasVolatile()) {
4261 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4262 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4263 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4264 /*IsAssigmentOperator=*/Op == OO_Equal);
4265 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004266 }
4267 }
4268 break;
4269
4270 case OO_PercentEqual:
4271 case OO_LessLessEqual:
4272 case OO_GreaterGreaterEqual:
4273 case OO_AmpEqual:
4274 case OO_CaretEqual:
4275 case OO_PipeEqual:
4276 // C++ [over.built]p22:
4277 //
4278 // For every triple (L, VQ, R), where L is an integral type, VQ
4279 // is either volatile or empty, and R is a promoted integral
4280 // type, there exist candidate operator functions of the form
4281 //
4282 // VQ L& operator%=(VQ L&, R);
4283 // VQ L& operator<<=(VQ L&, R);
4284 // VQ L& operator>>=(VQ L&, R);
4285 // VQ L& operator&=(VQ L&, R);
4286 // VQ L& operator^=(VQ L&, R);
4287 // VQ L& operator|=(VQ L&, R);
4288 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004289 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004290 Right < LastPromotedIntegralType; ++Right) {
4291 QualType ParamTypes[2];
4292 ParamTypes[1] = ArithmeticTypes[Right];
4293
4294 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004295 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004296 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004297 if (VisibleTypeConversionsQuals.hasVolatile()) {
4298 // Add this built-in operator as a candidate (VQ is 'volatile').
4299 ParamTypes[0] = ArithmeticTypes[Left];
4300 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4301 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4302 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4303 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004304 }
4305 }
4306 break;
4307
Douglas Gregord08452f2008-11-19 15:42:04 +00004308 case OO_Exclaim: {
4309 // C++ [over.operator]p23:
4310 //
4311 // There also exist candidate operator functions of the form
4312 //
Mike Stump11289f42009-09-09 15:08:12 +00004313 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004314 // bool operator&&(bool, bool); [BELOW]
4315 // bool operator||(bool, bool); [BELOW]
4316 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004317 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4318 /*IsAssignmentOperator=*/false,
4319 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004320 break;
4321 }
4322
Douglas Gregora11693b2008-11-12 17:17:38 +00004323 case OO_AmpAmp:
4324 case OO_PipePipe: {
4325 // C++ [over.operator]p23:
4326 //
4327 // There also exist candidate operator functions of the form
4328 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004329 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004330 // bool operator&&(bool, bool);
4331 // bool operator||(bool, bool);
4332 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004333 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4334 /*IsAssignmentOperator=*/false,
4335 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004336 break;
4337 }
4338
4339 case OO_Subscript:
4340 // C++ [over.built]p13:
4341 //
4342 // For every cv-qualified or cv-unqualified object type T there
4343 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004344 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004345 // T* operator+(T*, ptrdiff_t); [ABOVE]
4346 // T& operator[](T*, ptrdiff_t);
4347 // T* operator-(T*, ptrdiff_t); [ABOVE]
4348 // T* operator+(ptrdiff_t, T*); [ABOVE]
4349 // T& operator[](ptrdiff_t, T*);
4350 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4351 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4352 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004353 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004354 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004355
4356 // T& operator[](T*, ptrdiff_t)
4357 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4358
4359 // T& operator[](ptrdiff_t, T*);
4360 ParamTypes[0] = ParamTypes[1];
4361 ParamTypes[1] = *Ptr;
4362 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4363 }
4364 break;
4365
4366 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004367 // C++ [over.built]p11:
4368 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4369 // C1 is the same type as C2 or is a derived class of C2, T is an object
4370 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4371 // there exist candidate operator functions of the form
4372 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4373 // where CV12 is the union of CV1 and CV2.
4374 {
4375 for (BuiltinCandidateTypeSet::iterator Ptr =
4376 CandidateTypes.pointer_begin();
4377 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4378 QualType C1Ty = (*Ptr);
4379 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004380 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004381 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004382 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004383 if (!isa<RecordType>(C1))
4384 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004385 // heuristic to reduce number of builtin candidates in the set.
4386 // Add volatile/restrict version only if there are conversions to a
4387 // volatile/restrict type.
4388 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4389 continue;
4390 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4391 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004392 }
4393 for (BuiltinCandidateTypeSet::iterator
4394 MemPtr = CandidateTypes.member_pointer_begin(),
4395 MemPtrEnd = CandidateTypes.member_pointer_end();
4396 MemPtr != MemPtrEnd; ++MemPtr) {
4397 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4398 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004399 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004400 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4401 break;
4402 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4403 // build CV12 T&
4404 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004405 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4406 T.isVolatileQualified())
4407 continue;
4408 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4409 T.isRestrictQualified())
4410 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004411 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004412 QualType ResultTy = Context.getLValueReferenceType(T);
4413 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4414 }
4415 }
4416 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004417 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004418
4419 case OO_Conditional:
4420 // Note that we don't consider the first argument, since it has been
4421 // contextually converted to bool long ago. The candidates below are
4422 // therefore added as binary.
4423 //
4424 // C++ [over.built]p24:
4425 // For every type T, where T is a pointer or pointer-to-member type,
4426 // there exist candidate operator functions of the form
4427 //
4428 // T operator?(bool, T, T);
4429 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004430 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4431 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4432 QualType ParamTypes[2] = { *Ptr, *Ptr };
4433 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4434 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004435 for (BuiltinCandidateTypeSet::iterator Ptr =
4436 CandidateTypes.member_pointer_begin(),
4437 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4438 QualType ParamTypes[2] = { *Ptr, *Ptr };
4439 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4440 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004441 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004442 }
4443}
4444
Douglas Gregore254f902009-02-04 00:32:51 +00004445/// \brief Add function candidates found via argument-dependent lookup
4446/// to the set of overloading candidates.
4447///
4448/// This routine performs argument-dependent name lookup based on the
4449/// given function name (which may also be an operator name) and adds
4450/// all of the overload candidates found by ADL to the overload
4451/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004452void
Douglas Gregore254f902009-02-04 00:32:51 +00004453Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004454 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004455 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004456 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004457 OverloadCandidateSet& CandidateSet,
4458 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004459 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004460
John McCall91f61fc2010-01-26 06:04:06 +00004461 // FIXME: This approach for uniquing ADL results (and removing
4462 // redundant candidates from the set) relies on pointer-equality,
4463 // which means we need to key off the canonical decl. However,
4464 // always going back to the canonical decl might not get us the
4465 // right set of default arguments. What default arguments are
4466 // we supposed to consider on ADL candidates, anyway?
4467
Douglas Gregorcabea402009-09-22 15:41:20 +00004468 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004469 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004470
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004471 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004472 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4473 CandEnd = CandidateSet.end();
4474 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004475 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004476 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004477 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004478 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004479 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004480
4481 // For each of the ADL candidates we found, add it to the overload
4482 // set.
John McCall8fe68082010-01-26 07:16:45 +00004483 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004484 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004485 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004486 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004487 continue;
4488
John McCalla0296f72010-03-19 07:35:19 +00004489 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004490 false, false, PartialOverloading);
4491 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004492 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004493 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004494 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004495 }
Douglas Gregore254f902009-02-04 00:32:51 +00004496}
4497
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004498/// isBetterOverloadCandidate - Determines whether the first overload
4499/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004500bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004501Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004502 const OverloadCandidate& Cand2,
4503 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004504 // Define viable functions to be better candidates than non-viable
4505 // functions.
4506 if (!Cand2.Viable)
4507 return Cand1.Viable;
4508 else if (!Cand1.Viable)
4509 return false;
4510
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004511 // C++ [over.match.best]p1:
4512 //
4513 // -- if F is a static member function, ICS1(F) is defined such
4514 // that ICS1(F) is neither better nor worse than ICS1(G) for
4515 // any function G, and, symmetrically, ICS1(G) is neither
4516 // better nor worse than ICS1(F).
4517 unsigned StartArg = 0;
4518 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4519 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004520
Douglas Gregord3cb3562009-07-07 23:38:56 +00004521 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004522 // A viable function F1 is defined to be a better function than another
4523 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004524 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004525 unsigned NumArgs = Cand1.Conversions.size();
4526 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4527 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004528 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004529 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4530 Cand2.Conversions[ArgIdx])) {
4531 case ImplicitConversionSequence::Better:
4532 // Cand1 has a better conversion sequence.
4533 HasBetterConversion = true;
4534 break;
4535
4536 case ImplicitConversionSequence::Worse:
4537 // Cand1 can't be better than Cand2.
4538 return false;
4539
4540 case ImplicitConversionSequence::Indistinguishable:
4541 // Do nothing.
4542 break;
4543 }
4544 }
4545
Mike Stump11289f42009-09-09 15:08:12 +00004546 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004547 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004548 if (HasBetterConversion)
4549 return true;
4550
Mike Stump11289f42009-09-09 15:08:12 +00004551 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004552 // specialization, or, if not that,
4553 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4554 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4555 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004556
4557 // -- F1 and F2 are function template specializations, and the function
4558 // template for F1 is more specialized than the template for F2
4559 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004560 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004561 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4562 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004563 if (FunctionTemplateDecl *BetterTemplate
4564 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4565 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004566 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004567 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4568 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004569 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004570
Douglas Gregora1f013e2008-11-07 22:36:19 +00004571 // -- the context is an initialization by user-defined conversion
4572 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4573 // from the return type of F1 to the destination type (i.e.,
4574 // the type of the entity being initialized) is a better
4575 // conversion sequence than the standard conversion sequence
4576 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004577 if (Cand1.Function && Cand2.Function &&
4578 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004579 isa<CXXConversionDecl>(Cand2.Function)) {
4580 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4581 Cand2.FinalConversion)) {
4582 case ImplicitConversionSequence::Better:
4583 // Cand1 has a better conversion sequence.
4584 return true;
4585
4586 case ImplicitConversionSequence::Worse:
4587 // Cand1 can't be better than Cand2.
4588 return false;
4589
4590 case ImplicitConversionSequence::Indistinguishable:
4591 // Do nothing
4592 break;
4593 }
4594 }
4595
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004596 return false;
4597}
4598
Mike Stump11289f42009-09-09 15:08:12 +00004599/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004600/// within an overload candidate set.
4601///
4602/// \param CandidateSet the set of candidate functions.
4603///
4604/// \param Loc the location of the function name (or operator symbol) for
4605/// which overload resolution occurs.
4606///
Mike Stump11289f42009-09-09 15:08:12 +00004607/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004608/// function, Best points to the candidate function found.
4609///
4610/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004611OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4612 SourceLocation Loc,
4613 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004614 // Find the best viable function.
4615 Best = CandidateSet.end();
4616 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4617 Cand != CandidateSet.end(); ++Cand) {
4618 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004619 if (Best == CandidateSet.end() ||
4620 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004621 Best = Cand;
4622 }
4623 }
4624
4625 // If we didn't find any viable functions, abort.
4626 if (Best == CandidateSet.end())
4627 return OR_No_Viable_Function;
4628
4629 // Make sure that this function is better than every other viable
4630 // function. If not, we have an ambiguity.
4631 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4632 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004633 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004634 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004635 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004636 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004637 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004638 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004639 }
Mike Stump11289f42009-09-09 15:08:12 +00004640
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004641 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004642 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004643 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004644 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004645 return OR_Deleted;
4646
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004647 // C++ [basic.def.odr]p2:
4648 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004649 // when referred to from a potentially-evaluated expression. [Note: this
4650 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004651 // (clause 13), user-defined conversions (12.3.2), allocation function for
4652 // placement new (5.3.4), as well as non-default initialization (8.5).
4653 if (Best->Function)
4654 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004655 return OR_Success;
4656}
4657
John McCall53262c92010-01-12 02:15:36 +00004658namespace {
4659
4660enum OverloadCandidateKind {
4661 oc_function,
4662 oc_method,
4663 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004664 oc_function_template,
4665 oc_method_template,
4666 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004667 oc_implicit_default_constructor,
4668 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004669 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004670};
4671
John McCalle1ac8d12010-01-13 00:25:19 +00004672OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4673 FunctionDecl *Fn,
4674 std::string &Description) {
4675 bool isTemplate = false;
4676
4677 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4678 isTemplate = true;
4679 Description = S.getTemplateArgumentBindingsText(
4680 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4681 }
John McCallfd0b2f82010-01-06 09:43:14 +00004682
4683 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004684 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004685 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004686
John McCall53262c92010-01-12 02:15:36 +00004687 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4688 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004689 }
4690
4691 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4692 // This actually gets spelled 'candidate function' for now, but
4693 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004694 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004695 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004696
4697 assert(Meth->isCopyAssignment()
4698 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004699 return oc_implicit_copy_assignment;
4700 }
4701
John McCalle1ac8d12010-01-13 00:25:19 +00004702 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004703}
4704
4705} // end anonymous namespace
4706
4707// Notes the location of an overload candidate.
4708void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004709 std::string FnDesc;
4710 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4711 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4712 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004713}
4714
John McCall0d1da222010-01-12 00:44:57 +00004715/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4716/// "lead" diagnostic; it will be given two arguments, the source and
4717/// target types of the conversion.
4718void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4719 SourceLocation CaretLoc,
4720 const PartialDiagnostic &PDiag) {
4721 Diag(CaretLoc, PDiag)
4722 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4723 for (AmbiguousConversionSequence::const_iterator
4724 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4725 NoteOverloadCandidate(*I);
4726 }
John McCall12f97bc2010-01-08 04:41:39 +00004727}
4728
John McCall0d1da222010-01-12 00:44:57 +00004729namespace {
4730
John McCall6a61b522010-01-13 09:16:55 +00004731void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4732 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4733 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004734 assert(Cand->Function && "for now, candidate must be a function");
4735 FunctionDecl *Fn = Cand->Function;
4736
4737 // There's a conversion slot for the object argument if this is a
4738 // non-constructor method. Note that 'I' corresponds the
4739 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004740 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004741 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004742 if (I == 0)
4743 isObjectArgument = true;
4744 else
4745 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004746 }
4747
John McCalle1ac8d12010-01-13 00:25:19 +00004748 std::string FnDesc;
4749 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4750
John McCall6a61b522010-01-13 09:16:55 +00004751 Expr *FromExpr = Conv.Bad.FromExpr;
4752 QualType FromTy = Conv.Bad.getFromType();
4753 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004754
John McCallfb7ad0f2010-02-02 02:42:52 +00004755 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004756 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004757 Expr *E = FromExpr->IgnoreParens();
4758 if (isa<UnaryOperator>(E))
4759 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004760 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004761
4762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4763 << (unsigned) FnKind << FnDesc
4764 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4765 << ToTy << Name << I+1;
4766 return;
4767 }
4768
John McCall6d174642010-01-23 08:10:49 +00004769 // Do some hand-waving analysis to see if the non-viability is due
4770 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004771 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4772 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4773 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4774 CToTy = RT->getPointeeType();
4775 else {
4776 // TODO: detect and diagnose the full richness of const mismatches.
4777 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4778 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4779 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4780 }
4781
4782 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4783 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4784 // It is dumb that we have to do this here.
4785 while (isa<ArrayType>(CFromTy))
4786 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4787 while (isa<ArrayType>(CToTy))
4788 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4789
4790 Qualifiers FromQs = CFromTy.getQualifiers();
4791 Qualifiers ToQs = CToTy.getQualifiers();
4792
4793 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4794 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4795 << (unsigned) FnKind << FnDesc
4796 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4797 << FromTy
4798 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4799 << (unsigned) isObjectArgument << I+1;
4800 return;
4801 }
4802
4803 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4804 assert(CVR && "unexpected qualifiers mismatch");
4805
4806 if (isObjectArgument) {
4807 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4808 << (unsigned) FnKind << FnDesc
4809 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4810 << FromTy << (CVR - 1);
4811 } else {
4812 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4813 << (unsigned) FnKind << FnDesc
4814 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4815 << FromTy << (CVR - 1) << I+1;
4816 }
4817 return;
4818 }
4819
John McCall6d174642010-01-23 08:10:49 +00004820 // Diagnose references or pointers to incomplete types differently,
4821 // since it's far from impossible that the incompleteness triggered
4822 // the failure.
4823 QualType TempFromTy = FromTy.getNonReferenceType();
4824 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4825 TempFromTy = PTy->getPointeeType();
4826 if (TempFromTy->isIncompleteType()) {
4827 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4828 << (unsigned) FnKind << FnDesc
4829 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4830 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4831 return;
4832 }
4833
John McCall47000992010-01-14 03:28:57 +00004834 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004835 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4836 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004837 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004838 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004839}
4840
4841void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4842 unsigned NumFormalArgs) {
4843 // TODO: treat calls to a missing default constructor as a special case
4844
4845 FunctionDecl *Fn = Cand->Function;
4846 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4847
4848 unsigned MinParams = Fn->getMinRequiredArguments();
4849
4850 // at least / at most / exactly
4851 unsigned mode, modeCount;
4852 if (NumFormalArgs < MinParams) {
4853 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4854 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4855 mode = 0; // "at least"
4856 else
4857 mode = 2; // "exactly"
4858 modeCount = MinParams;
4859 } else {
4860 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4861 if (MinParams != FnTy->getNumArgs())
4862 mode = 1; // "at most"
4863 else
4864 mode = 2; // "exactly"
4865 modeCount = FnTy->getNumArgs();
4866 }
4867
4868 std::string Description;
4869 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4870
4871 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4872 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004873}
4874
John McCall8b9ed552010-02-01 18:53:26 +00004875/// Diagnose a failed template-argument deduction.
4876void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4877 Expr **Args, unsigned NumArgs) {
4878 FunctionDecl *Fn = Cand->Function; // pattern
4879
4880 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4881 Cand->DeductionFailure.TemplateParameter);
4882
4883 switch (Cand->DeductionFailure.Result) {
4884 case Sema::TDK_Success:
4885 llvm_unreachable("TDK_success while diagnosing bad deduction");
4886
4887 case Sema::TDK_Incomplete: {
4888 NamedDecl *ParamD;
4889 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4890 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4891 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4892 assert(ParamD && "no parameter found for incomplete deduction result");
4893 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4894 << ParamD->getDeclName();
4895 return;
4896 }
4897
4898 // TODO: diagnose these individually, then kill off
4899 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4900 case Sema::TDK_InstantiationDepth:
4901 case Sema::TDK_Inconsistent:
4902 case Sema::TDK_InconsistentQuals:
4903 case Sema::TDK_SubstitutionFailure:
4904 case Sema::TDK_NonDeducedMismatch:
4905 case Sema::TDK_TooManyArguments:
4906 case Sema::TDK_TooFewArguments:
4907 case Sema::TDK_InvalidExplicitArguments:
4908 case Sema::TDK_FailedOverloadResolution:
4909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4910 return;
4911 }
4912}
4913
4914/// Generates a 'note' diagnostic for an overload candidate. We've
4915/// already generated a primary error at the call site.
4916///
4917/// It really does need to be a single diagnostic with its caret
4918/// pointed at the candidate declaration. Yes, this creates some
4919/// major challenges of technical writing. Yes, this makes pointing
4920/// out problems with specific arguments quite awkward. It's still
4921/// better than generating twenty screens of text for every failed
4922/// overload.
4923///
4924/// It would be great to be able to express per-candidate problems
4925/// more richly for those diagnostic clients that cared, but we'd
4926/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004927void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4928 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004929 FunctionDecl *Fn = Cand->Function;
4930
John McCall12f97bc2010-01-08 04:41:39 +00004931 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004932 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004933 std::string FnDesc;
4934 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004935
4936 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004937 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004938 return;
John McCall12f97bc2010-01-08 04:41:39 +00004939 }
4940
John McCalle1ac8d12010-01-13 00:25:19 +00004941 // We don't really have anything else to say about viable candidates.
4942 if (Cand->Viable) {
4943 S.NoteOverloadCandidate(Fn);
4944 return;
4945 }
John McCall0d1da222010-01-12 00:44:57 +00004946
John McCall6a61b522010-01-13 09:16:55 +00004947 switch (Cand->FailureKind) {
4948 case ovl_fail_too_many_arguments:
4949 case ovl_fail_too_few_arguments:
4950 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004951
John McCall6a61b522010-01-13 09:16:55 +00004952 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004953 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4954
John McCallfe796dd2010-01-23 05:17:32 +00004955 case ovl_fail_trivial_conversion:
4956 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004957 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00004958 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004959
John McCall65eb8792010-02-25 01:37:24 +00004960 case ovl_fail_bad_conversion: {
4961 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4962 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004963 if (Cand->Conversions[I].isBad())
4964 return DiagnoseBadConversion(S, Cand, I);
4965
4966 // FIXME: this currently happens when we're called from SemaInit
4967 // when user-conversion overload fails. Figure out how to handle
4968 // those conditions and diagnose them well.
4969 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004970 }
John McCall65eb8792010-02-25 01:37:24 +00004971 }
John McCalld3224162010-01-08 00:58:21 +00004972}
4973
4974void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4975 // Desugar the type of the surrogate down to a function type,
4976 // retaining as many typedefs as possible while still showing
4977 // the function type (and, therefore, its parameter types).
4978 QualType FnType = Cand->Surrogate->getConversionType();
4979 bool isLValueReference = false;
4980 bool isRValueReference = false;
4981 bool isPointer = false;
4982 if (const LValueReferenceType *FnTypeRef =
4983 FnType->getAs<LValueReferenceType>()) {
4984 FnType = FnTypeRef->getPointeeType();
4985 isLValueReference = true;
4986 } else if (const RValueReferenceType *FnTypeRef =
4987 FnType->getAs<RValueReferenceType>()) {
4988 FnType = FnTypeRef->getPointeeType();
4989 isRValueReference = true;
4990 }
4991 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4992 FnType = FnTypePtr->getPointeeType();
4993 isPointer = true;
4994 }
4995 // Desugar down to a function type.
4996 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4997 // Reconstruct the pointer/reference as appropriate.
4998 if (isPointer) FnType = S.Context.getPointerType(FnType);
4999 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5000 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5001
5002 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5003 << FnType;
5004}
5005
5006void NoteBuiltinOperatorCandidate(Sema &S,
5007 const char *Opc,
5008 SourceLocation OpLoc,
5009 OverloadCandidate *Cand) {
5010 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5011 std::string TypeStr("operator");
5012 TypeStr += Opc;
5013 TypeStr += "(";
5014 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5015 if (Cand->Conversions.size() == 1) {
5016 TypeStr += ")";
5017 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5018 } else {
5019 TypeStr += ", ";
5020 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5021 TypeStr += ")";
5022 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5023 }
5024}
5025
5026void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5027 OverloadCandidate *Cand) {
5028 unsigned NoOperands = Cand->Conversions.size();
5029 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5030 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005031 if (ICS.isBad()) break; // all meaningless after first invalid
5032 if (!ICS.isAmbiguous()) continue;
5033
5034 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005035 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005036 }
5037}
5038
John McCall3712d9e2010-01-15 23:32:50 +00005039SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5040 if (Cand->Function)
5041 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005042 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005043 return Cand->Surrogate->getLocation();
5044 return SourceLocation();
5045}
5046
John McCallad2587a2010-01-12 00:48:53 +00005047struct CompareOverloadCandidatesForDisplay {
5048 Sema &S;
5049 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005050
5051 bool operator()(const OverloadCandidate *L,
5052 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005053 // Fast-path this check.
5054 if (L == R) return false;
5055
John McCall12f97bc2010-01-08 04:41:39 +00005056 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005057 if (L->Viable) {
5058 if (!R->Viable) return true;
5059
5060 // TODO: introduce a tri-valued comparison for overload
5061 // candidates. Would be more worthwhile if we had a sort
5062 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005063 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5064 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005065 } else if (R->Viable)
5066 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005067
John McCall3712d9e2010-01-15 23:32:50 +00005068 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005069
John McCall3712d9e2010-01-15 23:32:50 +00005070 // Criteria by which we can sort non-viable candidates:
5071 if (!L->Viable) {
5072 // 1. Arity mismatches come after other candidates.
5073 if (L->FailureKind == ovl_fail_too_many_arguments ||
5074 L->FailureKind == ovl_fail_too_few_arguments)
5075 return false;
5076 if (R->FailureKind == ovl_fail_too_many_arguments ||
5077 R->FailureKind == ovl_fail_too_few_arguments)
5078 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005079
John McCallfe796dd2010-01-23 05:17:32 +00005080 // 2. Bad conversions come first and are ordered by the number
5081 // of bad conversions and quality of good conversions.
5082 if (L->FailureKind == ovl_fail_bad_conversion) {
5083 if (R->FailureKind != ovl_fail_bad_conversion)
5084 return true;
5085
5086 // If there's any ordering between the defined conversions...
5087 // FIXME: this might not be transitive.
5088 assert(L->Conversions.size() == R->Conversions.size());
5089
5090 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005091 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5092 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005093 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5094 R->Conversions[I])) {
5095 case ImplicitConversionSequence::Better:
5096 leftBetter++;
5097 break;
5098
5099 case ImplicitConversionSequence::Worse:
5100 leftBetter--;
5101 break;
5102
5103 case ImplicitConversionSequence::Indistinguishable:
5104 break;
5105 }
5106 }
5107 if (leftBetter > 0) return true;
5108 if (leftBetter < 0) return false;
5109
5110 } else if (R->FailureKind == ovl_fail_bad_conversion)
5111 return false;
5112
John McCall3712d9e2010-01-15 23:32:50 +00005113 // TODO: others?
5114 }
5115
5116 // Sort everything else by location.
5117 SourceLocation LLoc = GetLocationForCandidate(L);
5118 SourceLocation RLoc = GetLocationForCandidate(R);
5119
5120 // Put candidates without locations (e.g. builtins) at the end.
5121 if (LLoc.isInvalid()) return false;
5122 if (RLoc.isInvalid()) return true;
5123
5124 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005125 }
5126};
5127
John McCallfe796dd2010-01-23 05:17:32 +00005128/// CompleteNonViableCandidate - Normally, overload resolution only
5129/// computes up to the first
5130void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5131 Expr **Args, unsigned NumArgs) {
5132 assert(!Cand->Viable);
5133
5134 // Don't do anything on failures other than bad conversion.
5135 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5136
5137 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005138 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005139 unsigned ConvCount = Cand->Conversions.size();
5140 while (true) {
5141 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5142 ConvIdx++;
5143 if (Cand->Conversions[ConvIdx - 1].isBad())
5144 break;
5145 }
5146
5147 if (ConvIdx == ConvCount)
5148 return;
5149
John McCall65eb8792010-02-25 01:37:24 +00005150 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5151 "remaining conversion is initialized?");
5152
John McCallfe796dd2010-01-23 05:17:32 +00005153 // FIXME: these should probably be preserved from the overload
5154 // operation somehow.
5155 bool SuppressUserConversions = false;
5156 bool ForceRValue = false;
5157
5158 const FunctionProtoType* Proto;
5159 unsigned ArgIdx = ConvIdx;
5160
5161 if (Cand->IsSurrogate) {
5162 QualType ConvType
5163 = Cand->Surrogate->getConversionType().getNonReferenceType();
5164 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5165 ConvType = ConvPtrType->getPointeeType();
5166 Proto = ConvType->getAs<FunctionProtoType>();
5167 ArgIdx--;
5168 } else if (Cand->Function) {
5169 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5170 if (isa<CXXMethodDecl>(Cand->Function) &&
5171 !isa<CXXConstructorDecl>(Cand->Function))
5172 ArgIdx--;
5173 } else {
5174 // Builtin binary operator with a bad first conversion.
5175 assert(ConvCount <= 3);
5176 for (; ConvIdx != ConvCount; ++ConvIdx)
5177 Cand->Conversions[ConvIdx]
5178 = S.TryCopyInitialization(Args[ConvIdx],
5179 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5180 SuppressUserConversions, ForceRValue,
5181 /*InOverloadResolution*/ true);
5182 return;
5183 }
5184
5185 // Fill in the rest of the conversions.
5186 unsigned NumArgsInProto = Proto->getNumArgs();
5187 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5188 if (ArgIdx < NumArgsInProto)
5189 Cand->Conversions[ConvIdx]
5190 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
5191 SuppressUserConversions, ForceRValue,
5192 /*InOverloadResolution=*/true);
5193 else
5194 Cand->Conversions[ConvIdx].setEllipsis();
5195 }
5196}
5197
John McCalld3224162010-01-08 00:58:21 +00005198} // end anonymous namespace
5199
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005200/// PrintOverloadCandidates - When overload resolution fails, prints
5201/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005202/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005203void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005204Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005205 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005206 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005207 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005208 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005209 // Sort the candidates by viability and position. Sorting directly would
5210 // be prohibitive, so we make a set of pointers and sort those.
5211 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5212 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5213 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5214 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005215 Cand != LastCand; ++Cand) {
5216 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005217 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005218 else if (OCD == OCD_AllCandidates) {
5219 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5220 Cands.push_back(Cand);
5221 }
5222 }
5223
John McCallad2587a2010-01-12 00:48:53 +00005224 std::sort(Cands.begin(), Cands.end(),
5225 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005226
John McCall0d1da222010-01-12 00:44:57 +00005227 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005228
John McCall12f97bc2010-01-08 04:41:39 +00005229 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5230 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5231 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005232
John McCalld3224162010-01-08 00:58:21 +00005233 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005234 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005235 else if (Cand->IsSurrogate)
5236 NoteSurrogateCandidate(*this, Cand);
5237
5238 // This a builtin candidate. We do not, in general, want to list
5239 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005240 else if (Cand->Viable) {
5241 // Generally we only see ambiguities including viable builtin
5242 // operators if overload resolution got screwed up by an
5243 // ambiguous user-defined conversion.
5244 //
5245 // FIXME: It's quite possible for different conversions to see
5246 // different ambiguities, though.
5247 if (!ReportedAmbiguousConversions) {
5248 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5249 ReportedAmbiguousConversions = true;
5250 }
John McCalld3224162010-01-08 00:58:21 +00005251
John McCall0d1da222010-01-12 00:44:57 +00005252 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005253 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005254 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005255 }
5256}
5257
John McCalla0296f72010-03-19 07:35:19 +00005258static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005259 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005260 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005261
John McCalla0296f72010-03-19 07:35:19 +00005262 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005263}
5264
Douglas Gregorcd695e52008-11-10 20:40:00 +00005265/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5266/// an overloaded function (C++ [over.over]), where @p From is an
5267/// expression with overloaded function type and @p ToType is the type
5268/// we're trying to resolve to. For example:
5269///
5270/// @code
5271/// int f(double);
5272/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005273///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005274/// int (*pfd)(double) = f; // selects f(double)
5275/// @endcode
5276///
5277/// This routine returns the resulting FunctionDecl if it could be
5278/// resolved, and NULL otherwise. When @p Complain is true, this
5279/// routine will emit diagnostics if there is an error.
5280FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005281Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005282 bool Complain,
5283 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005284 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005285 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005286 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005287 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005288 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005289 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005290 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005291 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005292 FunctionType = MemTypePtr->getPointeeType();
5293 IsMember = true;
5294 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005295
Douglas Gregorcd695e52008-11-10 20:40:00 +00005296 // C++ [over.over]p1:
5297 // [...] [Note: any redundant set of parentheses surrounding the
5298 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005299 // C++ [over.over]p1:
5300 // [...] The overloaded function name can be preceded by the &
5301 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005302 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5303 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5304 if (OvlExpr->hasExplicitTemplateArgs()) {
5305 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5306 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005307 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005308
5309 // We expect a pointer or reference to function, or a function pointer.
5310 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5311 if (!FunctionType->isFunctionType()) {
5312 if (Complain)
5313 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5314 << OvlExpr->getName() << ToType;
5315
5316 return 0;
5317 }
5318
5319 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005320
Douglas Gregorcd695e52008-11-10 20:40:00 +00005321 // Look through all of the overloaded functions, searching for one
5322 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005323 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005324 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5325
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005326 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005327 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5328 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005329 // Look through any using declarations to find the underlying function.
5330 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5331
Douglas Gregorcd695e52008-11-10 20:40:00 +00005332 // C++ [over.over]p3:
5333 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005334 // targets of type "pointer-to-function" or "reference-to-function."
5335 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005336 // type "pointer-to-member-function."
5337 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005338
Mike Stump11289f42009-09-09 15:08:12 +00005339 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005340 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005341 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005342 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005343 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005344 // static when converting to member pointer.
5345 if (Method->isStatic() == IsMember)
5346 continue;
5347 } else if (IsMember)
5348 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005349
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005350 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005351 // If the name is a function template, template argument deduction is
5352 // done (14.8.2.2), and if the argument deduction succeeds, the
5353 // resulting template argument list is used to generate a single
5354 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005355 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005356 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005357 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005358 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005359 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005360 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005361 FunctionType, Specialization, Info)) {
5362 // FIXME: make a note of the failed deduction for diagnostics.
5363 (void)Result;
5364 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005365 // FIXME: If the match isn't exact, shouldn't we just drop this as
5366 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005367 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005368 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005369 Matches.push_back(std::make_pair(I.getPair(),
5370 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005371 }
John McCalld14a8642009-11-21 08:51:07 +00005372
5373 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005374 }
Mike Stump11289f42009-09-09 15:08:12 +00005375
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005377 // Skip non-static functions when converting to pointer, and static
5378 // when converting to member pointer.
5379 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005380 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005381
5382 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005383 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005384 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005385 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005386 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005387
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005388 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005389 QualType ResultTy;
5390 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5391 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5392 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005393 Matches.push_back(std::make_pair(I.getPair(),
5394 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005395 FoundNonTemplateFunction = true;
5396 }
Mike Stump11289f42009-09-09 15:08:12 +00005397 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005398 }
5399
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005400 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005401 if (Matches.empty()) {
5402 if (Complain) {
5403 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5404 << OvlExpr->getName() << FunctionType;
5405 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5406 E = OvlExpr->decls_end();
5407 I != E; ++I)
5408 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5409 NoteOverloadCandidate(F);
5410 }
5411
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005412 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005413 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005414 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005415 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005416 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005417 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005418 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005419 return Result;
5420 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005421
5422 // C++ [over.over]p4:
5423 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005424 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005425 // [...] and any given function template specialization F1 is
5426 // eliminated if the set contains a second function template
5427 // specialization whose function template is more specialized
5428 // than the function template of F1 according to the partial
5429 // ordering rules of 14.5.5.2.
5430
5431 // The algorithm specified above is quadratic. We instead use a
5432 // two-pass algorithm (similar to the one used to identify the
5433 // best viable function in an overload set) that identifies the
5434 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005435
5436 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5437 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5438 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005439
5440 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005441 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005442 TPOC_Other, From->getLocStart(),
5443 PDiag(),
5444 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005445 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005446 PDiag(diag::note_ovl_candidate)
5447 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005448 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005449 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005450 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5451 if (Complain)
5452 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00005453 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005454 }
Mike Stump11289f42009-09-09 15:08:12 +00005455
Douglas Gregorfae1d712009-09-26 03:56:17 +00005456 // [...] any function template specializations in the set are
5457 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005458 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005459 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005460 ++I;
5461 else {
John McCalla0296f72010-03-19 07:35:19 +00005462 Matches[I] = Matches[--N];
5463 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005464 }
5465 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005466
Mike Stump11289f42009-09-09 15:08:12 +00005467 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005468 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005469 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005470 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005471 FoundResult = Matches[0].first;
John McCall58cc69d2010-01-27 01:50:18 +00005472 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00005473 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5474 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005475 }
Mike Stump11289f42009-09-09 15:08:12 +00005476
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005477 // FIXME: We should probably return the same thing that BestViableFunction
5478 // returns (even if we issue the diagnostics here).
5479 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005480 << Matches[0].second->getDeclName();
5481 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5482 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005483 return 0;
5484}
5485
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005486/// \brief Given an expression that refers to an overloaded function, try to
5487/// resolve that overloaded function expression down to a single function.
5488///
5489/// This routine can only resolve template-ids that refer to a single function
5490/// template, where that template-id refers to a single template whose template
5491/// arguments are either provided by the template-id or have defaults,
5492/// as described in C++0x [temp.arg.explicit]p3.
5493FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5494 // C++ [over.over]p1:
5495 // [...] [Note: any redundant set of parentheses surrounding the
5496 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005497 // C++ [over.over]p1:
5498 // [...] The overloaded function name can be preceded by the &
5499 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005500
5501 if (From->getType() != Context.OverloadTy)
5502 return 0;
5503
5504 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005505
5506 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005507 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005508 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005509
5510 TemplateArgumentListInfo ExplicitTemplateArgs;
5511 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005512
5513 // Look through all of the overloaded functions, searching for one
5514 // whose type matches exactly.
5515 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005516 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5517 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005518 // C++0x [temp.arg.explicit]p3:
5519 // [...] In contexts where deduction is done and fails, or in contexts
5520 // where deduction is not done, if a template argument list is
5521 // specified and it, along with any default template arguments,
5522 // identifies a single function template specialization, then the
5523 // template-id is an lvalue for the function template specialization.
5524 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5525
5526 // C++ [over.over]p2:
5527 // If the name is a function template, template argument deduction is
5528 // done (14.8.2.2), and if the argument deduction succeeds, the
5529 // resulting template argument list is used to generate a single
5530 // function template specialization, which is added to the set of
5531 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005532 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005533 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005534 if (TemplateDeductionResult Result
5535 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5536 Specialization, Info)) {
5537 // FIXME: make a note of the failed deduction for diagnostics.
5538 (void)Result;
5539 continue;
5540 }
5541
5542 // Multiple matches; we can't resolve to a single declaration.
5543 if (Matched)
5544 return 0;
5545
5546 Matched = Specialization;
5547 }
5548
5549 return Matched;
5550}
5551
Douglas Gregorcabea402009-09-22 15:41:20 +00005552/// \brief Add a single candidate to the overload set.
5553static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005554 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005555 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005556 Expr **Args, unsigned NumArgs,
5557 OverloadCandidateSet &CandidateSet,
5558 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005559 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005560 if (isa<UsingShadowDecl>(Callee))
5561 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5562
Douglas Gregorcabea402009-09-22 15:41:20 +00005563 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005564 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005565 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
John McCallb89836b2010-01-26 01:37:31 +00005566 false, false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005567 return;
John McCalld14a8642009-11-21 08:51:07 +00005568 }
5569
5570 if (FunctionTemplateDecl *FuncTemplate
5571 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005572 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5573 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005574 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005575 return;
5576 }
5577
5578 assert(false && "unhandled case in overloaded call candidate");
5579
5580 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005581}
5582
5583/// \brief Add the overload candidates named by callee and/or found by argument
5584/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005585void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005586 Expr **Args, unsigned NumArgs,
5587 OverloadCandidateSet &CandidateSet,
5588 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005589
5590#ifndef NDEBUG
5591 // Verify that ArgumentDependentLookup is consistent with the rules
5592 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005593 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005594 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5595 // and let Y be the lookup set produced by argument dependent
5596 // lookup (defined as follows). If X contains
5597 //
5598 // -- a declaration of a class member, or
5599 //
5600 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005601 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005602 //
5603 // -- a declaration that is neither a function or a function
5604 // template
5605 //
5606 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005607
John McCall57500772009-12-16 12:17:52 +00005608 if (ULE->requiresADL()) {
5609 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5610 E = ULE->decls_end(); I != E; ++I) {
5611 assert(!(*I)->getDeclContext()->isRecord());
5612 assert(isa<UsingShadowDecl>(*I) ||
5613 !(*I)->getDeclContext()->isFunctionOrMethod());
5614 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005615 }
5616 }
5617#endif
5618
John McCall57500772009-12-16 12:17:52 +00005619 // It would be nice to avoid this copy.
5620 TemplateArgumentListInfo TABuffer;
5621 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5622 if (ULE->hasExplicitTemplateArgs()) {
5623 ULE->copyTemplateArgumentsInto(TABuffer);
5624 ExplicitTemplateArgs = &TABuffer;
5625 }
5626
5627 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5628 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005629 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005630 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005631 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005632
John McCall57500772009-12-16 12:17:52 +00005633 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005634 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5635 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005636 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005637 CandidateSet,
5638 PartialOverloading);
5639}
John McCalld681c392009-12-16 08:11:27 +00005640
John McCall57500772009-12-16 12:17:52 +00005641static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5642 Expr **Args, unsigned NumArgs) {
5643 Fn->Destroy(SemaRef.Context);
5644 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5645 Args[Arg]->Destroy(SemaRef.Context);
5646 return SemaRef.ExprError();
5647}
5648
John McCalld681c392009-12-16 08:11:27 +00005649/// Attempts to recover from a call where no functions were found.
5650///
5651/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005652static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005653BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005654 UnresolvedLookupExpr *ULE,
5655 SourceLocation LParenLoc,
5656 Expr **Args, unsigned NumArgs,
5657 SourceLocation *CommaLocs,
5658 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005659
5660 CXXScopeSpec SS;
5661 if (ULE->getQualifier()) {
5662 SS.setScopeRep(ULE->getQualifier());
5663 SS.setRange(ULE->getQualifierRange());
5664 }
5665
John McCall57500772009-12-16 12:17:52 +00005666 TemplateArgumentListInfo TABuffer;
5667 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5668 if (ULE->hasExplicitTemplateArgs()) {
5669 ULE->copyTemplateArgumentsInto(TABuffer);
5670 ExplicitTemplateArgs = &TABuffer;
5671 }
5672
John McCalld681c392009-12-16 08:11:27 +00005673 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5674 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005675 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005676 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005677
John McCall57500772009-12-16 12:17:52 +00005678 assert(!R.empty() && "lookup results empty despite recovery");
5679
5680 // Build an implicit member call if appropriate. Just drop the
5681 // casts and such from the call, we don't really care.
5682 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5683 if ((*R.begin())->isCXXClassMember())
5684 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5685 else if (ExplicitTemplateArgs)
5686 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5687 else
5688 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5689
5690 if (NewFn.isInvalid())
5691 return Destroy(SemaRef, Fn, Args, NumArgs);
5692
5693 Fn->Destroy(SemaRef.Context);
5694
5695 // This shouldn't cause an infinite loop because we're giving it
5696 // an expression with non-empty lookup results, which should never
5697 // end up here.
5698 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5699 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5700 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005701}
Douglas Gregorcabea402009-09-22 15:41:20 +00005702
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005703/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005704/// (which eventually refers to the declaration Func) and the call
5705/// arguments Args/NumArgs, attempt to resolve the function call down
5706/// to a specific function. If overload resolution succeeds, returns
5707/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005708/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005709/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005710Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005711Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005712 SourceLocation LParenLoc,
5713 Expr **Args, unsigned NumArgs,
5714 SourceLocation *CommaLocs,
5715 SourceLocation RParenLoc) {
5716#ifndef NDEBUG
5717 if (ULE->requiresADL()) {
5718 // To do ADL, we must have found an unqualified name.
5719 assert(!ULE->getQualifier() && "qualified name with ADL");
5720
5721 // We don't perform ADL for implicit declarations of builtins.
5722 // Verify that this was correctly set up.
5723 FunctionDecl *F;
5724 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5725 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5726 F->getBuiltinID() && F->isImplicit())
5727 assert(0 && "performing ADL for builtin");
5728
5729 // We don't perform ADL in C.
5730 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5731 }
5732#endif
5733
John McCallbc077cf2010-02-08 23:07:23 +00005734 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005735
John McCall57500772009-12-16 12:17:52 +00005736 // Add the functions denoted by the callee to the set of candidate
5737 // functions, including those from argument-dependent lookup.
5738 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005739
5740 // If we found nothing, try to recover.
5741 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5742 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005743 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005744 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005745 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005746
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005747 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005748 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005749 case OR_Success: {
5750 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005751 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall16df1e52010-03-30 21:47:33 +00005752 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005753 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5754 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005755
5756 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005757 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005758 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005759 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005760 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005761 break;
5762
5763 case OR_Ambiguous:
5764 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005765 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005766 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005767 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005768
5769 case OR_Deleted:
5770 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5771 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005772 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005773 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005774 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005775 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005776 }
5777
5778 // Overload resolution failed. Destroy all of the subexpressions and
5779 // return NULL.
5780 Fn->Destroy(Context);
5781 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5782 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005783 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005784}
5785
John McCall4c4c1df2010-01-26 03:27:55 +00005786static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005787 return Functions.size() > 1 ||
5788 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5789}
5790
Douglas Gregor084d8552009-03-13 23:49:33 +00005791/// \brief Create a unary operation that may resolve to an overloaded
5792/// operator.
5793///
5794/// \param OpLoc The location of the operator itself (e.g., '*').
5795///
5796/// \param OpcIn The UnaryOperator::Opcode that describes this
5797/// operator.
5798///
5799/// \param Functions The set of non-member functions that will be
5800/// considered by overload resolution. The caller needs to build this
5801/// set based on the context using, e.g.,
5802/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5803/// set should not contain any member functions; those will be added
5804/// by CreateOverloadedUnaryOp().
5805///
5806/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005807Sema::OwningExprResult
5808Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5809 const UnresolvedSetImpl &Fns,
5810 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005811 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5812 Expr *Input = (Expr *)input.get();
5813
5814 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5815 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5816 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5817
5818 Expr *Args[2] = { Input, 0 };
5819 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005820
Douglas Gregor084d8552009-03-13 23:49:33 +00005821 // For post-increment and post-decrement, add the implicit '0' as
5822 // the second argument, so that we know this is a post-increment or
5823 // post-decrement.
5824 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5825 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005826 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005827 SourceLocation());
5828 NumArgs = 2;
5829 }
5830
5831 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005832 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005833 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005834 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005835 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005836 /*ADL*/ true, IsOverloaded(Fns));
5837 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005838
Douglas Gregor084d8552009-03-13 23:49:33 +00005839 input.release();
5840 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5841 &Args[0], NumArgs,
5842 Context.DependentTy,
5843 OpLoc));
5844 }
5845
5846 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005847 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005848
5849 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005850 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005851
5852 // Add operator candidates that are member functions.
5853 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5854
John McCall4c4c1df2010-01-26 03:27:55 +00005855 // Add candidates from ADL.
5856 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005857 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005858 /*ExplicitTemplateArgs*/ 0,
5859 CandidateSet);
5860
Douglas Gregor084d8552009-03-13 23:49:33 +00005861 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005862 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005863
5864 // Perform overload resolution.
5865 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005866 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005867 case OR_Success: {
5868 // We found a built-in operator or an overloaded operator.
5869 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005870
Douglas Gregor084d8552009-03-13 23:49:33 +00005871 if (FnDecl) {
5872 // We matched an overloaded operator. Build a call to that
5873 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005874
Douglas Gregor084d8552009-03-13 23:49:33 +00005875 // Convert the arguments.
5876 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005877 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005878
John McCall16df1e52010-03-30 21:47:33 +00005879 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5880 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005881 return ExprError();
5882 } else {
5883 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005884 OwningExprResult InputInit
5885 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005886 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005887 SourceLocation(),
5888 move(input));
5889 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005890 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005891
Douglas Gregore6600372009-12-23 17:40:29 +00005892 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005893 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005894 }
5895
5896 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005897 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005898
Douglas Gregor084d8552009-03-13 23:49:33 +00005899 // Build the actual expression node.
5900 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5901 SourceLocation());
5902 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005903
Douglas Gregor084d8552009-03-13 23:49:33 +00005904 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005905 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005906 ExprOwningPtr<CallExpr> TheCall(this,
5907 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005908 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005909
5910 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5911 FnDecl))
5912 return ExprError();
5913
5914 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005915 } else {
5916 // We matched a built-in operator. Convert the arguments, then
5917 // break out so that we will build the appropriate built-in
5918 // operator node.
5919 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005920 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005921 return ExprError();
5922
5923 break;
5924 }
5925 }
5926
5927 case OR_No_Viable_Function:
5928 // No viable function; fall through to handling this as a
5929 // built-in operator, which will produce an error message for us.
5930 break;
5931
5932 case OR_Ambiguous:
5933 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5934 << UnaryOperator::getOpcodeStr(Opc)
5935 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005936 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005937 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005938 return ExprError();
5939
5940 case OR_Deleted:
5941 Diag(OpLoc, diag::err_ovl_deleted_oper)
5942 << Best->Function->isDeleted()
5943 << UnaryOperator::getOpcodeStr(Opc)
5944 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005945 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005946 return ExprError();
5947 }
5948
5949 // Either we found no viable overloaded operator or we matched a
5950 // built-in operator. In either case, fall through to trying to
5951 // build a built-in operation.
5952 input.release();
5953 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5954}
5955
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005956/// \brief Create a binary operation that may resolve to an overloaded
5957/// operator.
5958///
5959/// \param OpLoc The location of the operator itself (e.g., '+').
5960///
5961/// \param OpcIn The BinaryOperator::Opcode that describes this
5962/// operator.
5963///
5964/// \param Functions The set of non-member functions that will be
5965/// considered by overload resolution. The caller needs to build this
5966/// set based on the context using, e.g.,
5967/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5968/// set should not contain any member functions; those will be added
5969/// by CreateOverloadedBinOp().
5970///
5971/// \param LHS Left-hand argument.
5972/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005973Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005974Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005975 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005976 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005977 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005978 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005979 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005980
5981 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5982 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5983 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5984
5985 // If either side is type-dependent, create an appropriate dependent
5986 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005987 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005988 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005989 // If there are no functions to store, just build a dependent
5990 // BinaryOperator or CompoundAssignment.
5991 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5992 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5993 Context.DependentTy, OpLoc));
5994
5995 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5996 Context.DependentTy,
5997 Context.DependentTy,
5998 Context.DependentTy,
5999 OpLoc));
6000 }
John McCall4c4c1df2010-01-26 03:27:55 +00006001
6002 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006003 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006004 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006005 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006006 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006007 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006008
John McCall4c4c1df2010-01-26 03:27:55 +00006009 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006010 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006011 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006012 Context.DependentTy,
6013 OpLoc));
6014 }
6015
6016 // If this is the .* operator, which is not overloadable, just
6017 // create a built-in binary operator.
6018 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006019 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006020
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006021 // If this is the assignment operator, we only perform overload resolution
6022 // if the left-hand side is a class or enumeration type. This is actually
6023 // a hack. The standard requires that we do overload resolution between the
6024 // various built-in candidates, but as DR507 points out, this can lead to
6025 // problems. So we do it this way, which pretty much follows what GCC does.
6026 // Note that we go the traditional code path for compound assignment forms.
6027 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006028 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006029
Douglas Gregor084d8552009-03-13 23:49:33 +00006030 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006031 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006032
6033 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006034 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006035
6036 // Add operator candidates that are member functions.
6037 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6038
John McCall4c4c1df2010-01-26 03:27:55 +00006039 // Add candidates from ADL.
6040 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6041 Args, 2,
6042 /*ExplicitTemplateArgs*/ 0,
6043 CandidateSet);
6044
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006045 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006046 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006047
6048 // Perform overload resolution.
6049 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006050 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006051 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006052 // We found a built-in operator or an overloaded operator.
6053 FunctionDecl *FnDecl = Best->Function;
6054
6055 if (FnDecl) {
6056 // We matched an overloaded operator. Build a call to that
6057 // operator.
6058
6059 // Convert the arguments.
6060 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006061 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006062 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006063
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006064 OwningExprResult Arg1
6065 = PerformCopyInitialization(
6066 InitializedEntity::InitializeParameter(
6067 FnDecl->getParamDecl(0)),
6068 SourceLocation(),
6069 Owned(Args[1]));
6070 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006071 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006072
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006073 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006074 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006075 return ExprError();
6076
6077 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006078 } else {
6079 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006080 OwningExprResult Arg0
6081 = PerformCopyInitialization(
6082 InitializedEntity::InitializeParameter(
6083 FnDecl->getParamDecl(0)),
6084 SourceLocation(),
6085 Owned(Args[0]));
6086 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006087 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006088
6089 OwningExprResult Arg1
6090 = PerformCopyInitialization(
6091 InitializedEntity::InitializeParameter(
6092 FnDecl->getParamDecl(1)),
6093 SourceLocation(),
6094 Owned(Args[1]));
6095 if (Arg1.isInvalid())
6096 return ExprError();
6097 Args[0] = LHS = Arg0.takeAs<Expr>();
6098 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006099 }
6100
6101 // Determine the result type
6102 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006103 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006104 ResultTy = ResultTy.getNonReferenceType();
6105
6106 // Build the actual expression node.
6107 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006108 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006109 UsualUnaryConversions(FnExpr);
6110
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006111 ExprOwningPtr<CXXOperatorCallExpr>
6112 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6113 Args, 2, ResultTy,
6114 OpLoc));
6115
6116 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6117 FnDecl))
6118 return ExprError();
6119
6120 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006121 } else {
6122 // We matched a built-in operator. Convert the arguments, then
6123 // break out so that we will build the appropriate built-in
6124 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006125 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006126 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006127 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006128 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006129 return ExprError();
6130
6131 break;
6132 }
6133 }
6134
Douglas Gregor66950a32009-09-30 21:46:01 +00006135 case OR_No_Viable_Function: {
6136 // C++ [over.match.oper]p9:
6137 // If the operator is the operator , [...] and there are no
6138 // viable functions, then the operator is assumed to be the
6139 // built-in operator and interpreted according to clause 5.
6140 if (Opc == BinaryOperator::Comma)
6141 break;
6142
Sebastian Redl027de2a2009-05-21 11:50:50 +00006143 // For class as left operand for assignment or compound assigment operator
6144 // do not fall through to handling in built-in, but report that no overloaded
6145 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006146 OwningExprResult Result = ExprError();
6147 if (Args[0]->getType()->isRecordType() &&
6148 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006149 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6150 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006151 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006152 } else {
6153 // No viable function; try to create a built-in operation, which will
6154 // produce an error. Then, show the non-viable candidates.
6155 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006156 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006157 assert(Result.isInvalid() &&
6158 "C++ binary operator overloading is missing candidates!");
6159 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006160 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006161 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006162 return move(Result);
6163 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006164
6165 case OR_Ambiguous:
6166 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6167 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006168 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006169 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006170 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006171 return ExprError();
6172
6173 case OR_Deleted:
6174 Diag(OpLoc, diag::err_ovl_deleted_oper)
6175 << Best->Function->isDeleted()
6176 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006177 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006178 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006179 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006180 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006181
Douglas Gregor66950a32009-09-30 21:46:01 +00006182 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006183 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006184}
6185
Sebastian Redladba46e2009-10-29 20:17:01 +00006186Action::OwningExprResult
6187Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6188 SourceLocation RLoc,
6189 ExprArg Base, ExprArg Idx) {
6190 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6191 static_cast<Expr*>(Idx.get()) };
6192 DeclarationName OpName =
6193 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6194
6195 // If either side is type-dependent, create an appropriate dependent
6196 // expression.
6197 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6198
John McCall58cc69d2010-01-27 01:50:18 +00006199 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006200 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006201 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006202 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006203 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006204 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006205
6206 Base.release();
6207 Idx.release();
6208 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6209 Args, 2,
6210 Context.DependentTy,
6211 RLoc));
6212 }
6213
6214 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006215 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006216
6217 // Subscript can only be overloaded as a member function.
6218
6219 // Add operator candidates that are member functions.
6220 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6221
6222 // Add builtin operator candidates.
6223 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6224
6225 // Perform overload resolution.
6226 OverloadCandidateSet::iterator Best;
6227 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6228 case OR_Success: {
6229 // We found a built-in operator or an overloaded operator.
6230 FunctionDecl *FnDecl = Best->Function;
6231
6232 if (FnDecl) {
6233 // We matched an overloaded operator. Build a call to that
6234 // operator.
6235
John McCalla0296f72010-03-19 07:35:19 +00006236 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +00006237
Sebastian Redladba46e2009-10-29 20:17:01 +00006238 // Convert the arguments.
6239 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006240 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006241 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006242 return ExprError();
6243
Anders Carlssona68e51e2010-01-29 18:37:50 +00006244 // Convert the arguments.
6245 OwningExprResult InputInit
6246 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6247 FnDecl->getParamDecl(0)),
6248 SourceLocation(),
6249 Owned(Args[1]));
6250 if (InputInit.isInvalid())
6251 return ExprError();
6252
6253 Args[1] = InputInit.takeAs<Expr>();
6254
Sebastian Redladba46e2009-10-29 20:17:01 +00006255 // Determine the result type
6256 QualType ResultTy
6257 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6258 ResultTy = ResultTy.getNonReferenceType();
6259
6260 // Build the actual expression node.
6261 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6262 LLoc);
6263 UsualUnaryConversions(FnExpr);
6264
6265 Base.release();
6266 Idx.release();
6267 ExprOwningPtr<CXXOperatorCallExpr>
6268 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6269 FnExpr, Args, 2,
6270 ResultTy, RLoc));
6271
6272 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6273 FnDecl))
6274 return ExprError();
6275
6276 return MaybeBindToTemporary(TheCall.release());
6277 } else {
6278 // We matched a built-in operator. Convert the arguments, then
6279 // break out so that we will build the appropriate built-in
6280 // operator node.
6281 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006282 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006283 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006284 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006285 return ExprError();
6286
6287 break;
6288 }
6289 }
6290
6291 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006292 if (CandidateSet.empty())
6293 Diag(LLoc, diag::err_ovl_no_oper)
6294 << Args[0]->getType() << /*subscript*/ 0
6295 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6296 else
6297 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6298 << Args[0]->getType()
6299 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006300 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006301 "[]", LLoc);
6302 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006303 }
6304
6305 case OR_Ambiguous:
6306 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6307 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006308 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006309 "[]", LLoc);
6310 return ExprError();
6311
6312 case OR_Deleted:
6313 Diag(LLoc, diag::err_ovl_deleted_oper)
6314 << Best->Function->isDeleted() << "[]"
6315 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006316 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006317 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006318 return ExprError();
6319 }
6320
6321 // We matched a built-in operator; build it.
6322 Base.release();
6323 Idx.release();
6324 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6325 Owned(Args[1]), RLoc);
6326}
6327
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006328/// BuildCallToMemberFunction - Build a call to a member
6329/// function. MemExpr is the expression that refers to the member
6330/// function (and includes the object parameter), Args/NumArgs are the
6331/// arguments to the function call (not including the object
6332/// parameter). The caller needs to validate that the member
6333/// expression refers to a member function or an overloaded member
6334/// function.
John McCall2d74de92009-12-01 22:10:20 +00006335Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006336Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6337 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006338 unsigned NumArgs, SourceLocation *CommaLocs,
6339 SourceLocation RParenLoc) {
6340 // Dig out the member expression. This holds both the object
6341 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006342 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6343
John McCall10eae182009-11-30 22:42:35 +00006344 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006345 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006346 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006347 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006348 if (isa<MemberExpr>(NakedMemExpr)) {
6349 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006350 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006351 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006352 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006353 } else {
6354 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006355 Qualifier = UnresExpr->getQualifier();
6356
John McCall6e9f8f62009-12-03 04:06:58 +00006357 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006358
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006359 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006360 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006361
John McCall2d74de92009-12-01 22:10:20 +00006362 // FIXME: avoid copy.
6363 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6364 if (UnresExpr->hasExplicitTemplateArgs()) {
6365 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6366 TemplateArgs = &TemplateArgsBuffer;
6367 }
6368
John McCall10eae182009-11-30 22:42:35 +00006369 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6370 E = UnresExpr->decls_end(); I != E; ++I) {
6371
John McCall6e9f8f62009-12-03 04:06:58 +00006372 NamedDecl *Func = *I;
6373 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6374 if (isa<UsingShadowDecl>(Func))
6375 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6376
John McCall10eae182009-11-30 22:42:35 +00006377 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006378 // If explicit template arguments were provided, we can't call a
6379 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006380 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006381 continue;
6382
John McCalla0296f72010-03-19 07:35:19 +00006383 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006384 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006385 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006386 } else {
John McCall10eae182009-11-30 22:42:35 +00006387 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006388 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006389 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006390 CandidateSet,
6391 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006392 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006393 }
Mike Stump11289f42009-09-09 15:08:12 +00006394
John McCall10eae182009-11-30 22:42:35 +00006395 DeclarationName DeclName = UnresExpr->getMemberName();
6396
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006397 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006398 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006399 case OR_Success:
6400 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006401 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006402 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006403 break;
6404
6405 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006406 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006407 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006408 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006409 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006410 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006411 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006412
6413 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006414 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006415 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006416 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006417 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006418 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006419
6420 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006421 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006422 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006423 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006424 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006425 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006426 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006427 }
6428
John McCall16df1e52010-03-30 21:47:33 +00006429 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006430
John McCall2d74de92009-12-01 22:10:20 +00006431 // If overload resolution picked a static member, build a
6432 // non-member call based on that function.
6433 if (Method->isStatic()) {
6434 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6435 Args, NumArgs, RParenLoc);
6436 }
6437
John McCall10eae182009-11-30 22:42:35 +00006438 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006439 }
6440
6441 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006442 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006443 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006444 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006445 Method->getResultType().getNonReferenceType(),
6446 RParenLoc));
6447
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006448 // Check for a valid return type.
6449 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6450 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006451 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006452
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006453 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006454 // We only need to do this if there was actually an overload; otherwise
6455 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006456 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006457 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006458 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6459 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006460 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006461 MemExpr->setBase(ObjectArg);
6462
6463 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006464 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006465 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006466 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006467 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006468
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006469 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006470 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006471
John McCall2d74de92009-12-01 22:10:20 +00006472 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006473}
6474
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006475/// BuildCallToObjectOfClassType - Build a call to an object of class
6476/// type (C++ [over.call.object]), which can end up invoking an
6477/// overloaded function call operator (@c operator()) or performing a
6478/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006479Sema::ExprResult
6480Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006481 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006482 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006483 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006484 SourceLocation RParenLoc) {
6485 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006486 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006487
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006488 // C++ [over.call.object]p1:
6489 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006490 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006491 // candidate functions includes at least the function call
6492 // operators of T. The function call operators of T are obtained by
6493 // ordinary lookup of the name operator() in the context of
6494 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006495 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006496 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006497
6498 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006499 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006500 << Object->getSourceRange()))
6501 return true;
6502
John McCall27b18f82009-11-17 02:14:36 +00006503 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6504 LookupQualifiedName(R, Record->getDecl());
6505 R.suppressDiagnostics();
6506
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006507 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006508 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006509 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006510 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006511 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006512 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006513
Douglas Gregorab7897a2008-11-19 22:57:39 +00006514 // C++ [over.call.object]p2:
6515 // In addition, for each conversion function declared in T of the
6516 // form
6517 //
6518 // operator conversion-type-id () cv-qualifier;
6519 //
6520 // where cv-qualifier is the same cv-qualification as, or a
6521 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006522 // denotes the type "pointer to function of (P1,...,Pn) returning
6523 // R", or the type "reference to pointer to function of
6524 // (P1,...,Pn) returning R", or the type "reference to function
6525 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006526 // is also considered as a candidate function. Similarly,
6527 // surrogate call functions are added to the set of candidate
6528 // functions for each conversion function declared in an
6529 // accessible base class provided the function is not hidden
6530 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006531 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006532 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006533 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006534 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006535 NamedDecl *D = *I;
6536 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6537 if (isa<UsingShadowDecl>(D))
6538 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6539
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006540 // Skip over templated conversion functions; they aren't
6541 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006542 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006543 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006544
John McCall6e9f8f62009-12-03 04:06:58 +00006545 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006546
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006547 // Strip the reference type (if any) and then the pointer type (if
6548 // any) to get down to what might be a function type.
6549 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6550 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6551 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006552
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006553 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006554 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006555 Object->getType(), Args, NumArgs,
6556 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006557 }
Mike Stump11289f42009-09-09 15:08:12 +00006558
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006559 // Perform overload resolution.
6560 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006561 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006562 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006563 // Overload resolution succeeded; we'll build the appropriate call
6564 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006565 break;
6566
6567 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006568 if (CandidateSet.empty())
6569 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6570 << Object->getType() << /*call*/ 1
6571 << Object->getSourceRange();
6572 else
6573 Diag(Object->getSourceRange().getBegin(),
6574 diag::err_ovl_no_viable_object_call)
6575 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006576 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006577 break;
6578
6579 case OR_Ambiguous:
6580 Diag(Object->getSourceRange().getBegin(),
6581 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006582 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006583 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006584 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006585
6586 case OR_Deleted:
6587 Diag(Object->getSourceRange().getBegin(),
6588 diag::err_ovl_deleted_object_call)
6589 << Best->Function->isDeleted()
6590 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006591 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006592 break;
Mike Stump11289f42009-09-09 15:08:12 +00006593 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006594
Douglas Gregorab7897a2008-11-19 22:57:39 +00006595 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006596 // We had an error; delete all of the subexpressions and return
6597 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006598 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006599 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006600 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006601 return true;
6602 }
6603
Douglas Gregorab7897a2008-11-19 22:57:39 +00006604 if (Best->Function == 0) {
6605 // Since there is no function declaration, this is one of the
6606 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006607 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006608 = cast<CXXConversionDecl>(
6609 Best->Conversions[0].UserDefined.ConversionFunction);
6610
John McCalla0296f72010-03-19 07:35:19 +00006611 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006612
Douglas Gregorab7897a2008-11-19 22:57:39 +00006613 // We selected one of the surrogate functions that converts the
6614 // object parameter to a function pointer. Perform the conversion
6615 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006616
6617 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006618 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006619 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6620 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006621
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006622 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006623 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006624 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006625 }
6626
John McCalla0296f72010-03-19 07:35:19 +00006627 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006628
Douglas Gregorab7897a2008-11-19 22:57:39 +00006629 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6630 // that calls this method, using Object for the implicit object
6631 // parameter and passing along the remaining arguments.
6632 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006633 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006634
6635 unsigned NumArgsInProto = Proto->getNumArgs();
6636 unsigned NumArgsToCheck = NumArgs;
6637
6638 // Build the full argument list for the method call (the
6639 // implicit object parameter is placed at the beginning of the
6640 // list).
6641 Expr **MethodArgs;
6642 if (NumArgs < NumArgsInProto) {
6643 NumArgsToCheck = NumArgsInProto;
6644 MethodArgs = new Expr*[NumArgsInProto + 1];
6645 } else {
6646 MethodArgs = new Expr*[NumArgs + 1];
6647 }
6648 MethodArgs[0] = Object;
6649 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6650 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006651
6652 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006653 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006654 UsualUnaryConversions(NewFn);
6655
6656 // Once we've built TheCall, all of the expressions are properly
6657 // owned.
6658 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006659 ExprOwningPtr<CXXOperatorCallExpr>
6660 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006661 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006662 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006663 delete [] MethodArgs;
6664
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006665 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6666 Method))
6667 return true;
6668
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006669 // We may have default arguments. If so, we need to allocate more
6670 // slots in the call for them.
6671 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006672 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006673 else if (NumArgs > NumArgsInProto)
6674 NumArgsToCheck = NumArgsInProto;
6675
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006676 bool IsError = false;
6677
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006678 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006679 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006680 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006681 TheCall->setArg(0, Object);
6682
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006683
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006684 // Check the argument types.
6685 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006686 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006687 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006688 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006689
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006690 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006691
6692 OwningExprResult InputInit
6693 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6694 Method->getParamDecl(i)),
6695 SourceLocation(), Owned(Arg));
6696
6697 IsError |= InputInit.isInvalid();
6698 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006699 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006700 OwningExprResult DefArg
6701 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6702 if (DefArg.isInvalid()) {
6703 IsError = true;
6704 break;
6705 }
6706
6707 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006708 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006709
6710 TheCall->setArg(i + 1, Arg);
6711 }
6712
6713 // If this is a variadic call, handle args passed through "...".
6714 if (Proto->isVariadic()) {
6715 // Promote the arguments (C99 6.5.2.2p7).
6716 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6717 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006718 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006719 TheCall->setArg(i + 1, Arg);
6720 }
6721 }
6722
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006723 if (IsError) return true;
6724
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006725 if (CheckFunctionCall(Method, TheCall.get()))
6726 return true;
6727
Douglas Gregore5e775b2010-04-13 15:50:39 +00006728 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006729}
6730
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006731/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006732/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006733/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006734Sema::OwningExprResult
6735Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6736 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006737 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006738
John McCallbc077cf2010-02-08 23:07:23 +00006739 SourceLocation Loc = Base->getExprLoc();
6740
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006741 // C++ [over.ref]p1:
6742 //
6743 // [...] An expression x->m is interpreted as (x.operator->())->m
6744 // for a class object x of type T if T::operator->() exists and if
6745 // the operator is selected as the best match function by the
6746 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006747 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006748 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006749 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006750
John McCallbc077cf2010-02-08 23:07:23 +00006751 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006752 PDiag(diag::err_typecheck_incomplete_tag)
6753 << Base->getSourceRange()))
6754 return ExprError();
6755
John McCall27b18f82009-11-17 02:14:36 +00006756 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6757 LookupQualifiedName(R, BaseRecord->getDecl());
6758 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006759
6760 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006761 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006762 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006763 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006764 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006765
6766 // Perform overload resolution.
6767 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006768 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006769 case OR_Success:
6770 // Overload resolution succeeded; we'll build the call below.
6771 break;
6772
6773 case OR_No_Viable_Function:
6774 if (CandidateSet.empty())
6775 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006776 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006777 else
6778 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006779 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006780 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006781 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006782
6783 case OR_Ambiguous:
6784 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006785 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006786 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006787 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006788
6789 case OR_Deleted:
6790 Diag(OpLoc, diag::err_ovl_deleted_oper)
6791 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006792 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006793 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006794 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006795 }
6796
John McCalla0296f72010-03-19 07:35:19 +00006797 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6798
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006799 // Convert the object parameter.
6800 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006801 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6802 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006803 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006804
6805 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006806 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006807
6808 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006809 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6810 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006811 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006812
6813 QualType ResultTy = Method->getResultType().getNonReferenceType();
6814 ExprOwningPtr<CXXOperatorCallExpr>
6815 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6816 &Base, 1, ResultTy, OpLoc));
6817
6818 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6819 Method))
6820 return ExprError();
6821 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006822}
6823
Douglas Gregorcd695e52008-11-10 20:40:00 +00006824/// FixOverloadedFunctionReference - E is an expression that refers to
6825/// a C++ overloaded function (possibly with some parentheses and
6826/// perhaps a '&' around it). We have resolved the overloaded function
6827/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006828/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006829Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006830 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006831 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006832 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6833 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006834 if (SubExpr == PE->getSubExpr())
6835 return PE->Retain();
6836
6837 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6838 }
6839
6840 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006841 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6842 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006843 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006844 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006845 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006846 if (SubExpr == ICE->getSubExpr())
6847 return ICE->Retain();
6848
6849 return new (Context) ImplicitCastExpr(ICE->getType(),
6850 ICE->getCastKind(),
6851 SubExpr,
6852 ICE->isLvalueCast());
6853 }
6854
6855 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006856 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006857 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6859 if (Method->isStatic()) {
6860 // Do nothing: static member functions aren't any different
6861 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006862 } else {
John McCalle66edc12009-11-24 19:00:30 +00006863 // Fix the sub expression, which really has to be an
6864 // UnresolvedLookupExpr holding an overloaded member function
6865 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006866 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6867 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006868 if (SubExpr == UnOp->getSubExpr())
6869 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006870
John McCalld14a8642009-11-21 08:51:07 +00006871 assert(isa<DeclRefExpr>(SubExpr)
6872 && "fixed to something other than a decl ref");
6873 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6874 && "fixed to a member ref with no nested name qualifier");
6875
6876 // We have taken the address of a pointer to member
6877 // function. Perform the computation here so that we get the
6878 // appropriate pointer to member type.
6879 QualType ClassType
6880 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6881 QualType MemPtrType
6882 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6883
6884 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6885 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006886 }
6887 }
John McCall16df1e52010-03-30 21:47:33 +00006888 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6889 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006890 if (SubExpr == UnOp->getSubExpr())
6891 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006892
Douglas Gregor51c538b2009-11-20 19:42:02 +00006893 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6894 Context.getPointerType(SubExpr->getType()),
6895 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006896 }
John McCalld14a8642009-11-21 08:51:07 +00006897
6898 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006899 // FIXME: avoid copy.
6900 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006901 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006902 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6903 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006904 }
6905
John McCalld14a8642009-11-21 08:51:07 +00006906 return DeclRefExpr::Create(Context,
6907 ULE->getQualifier(),
6908 ULE->getQualifierRange(),
6909 Fn,
6910 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006911 Fn->getType(),
6912 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006913 }
6914
John McCall10eae182009-11-30 22:42:35 +00006915 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006916 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006917 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6918 if (MemExpr->hasExplicitTemplateArgs()) {
6919 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6920 TemplateArgs = &TemplateArgsBuffer;
6921 }
John McCall6b51f282009-11-23 01:53:49 +00006922
John McCall2d74de92009-12-01 22:10:20 +00006923 Expr *Base;
6924
6925 // If we're filling in
6926 if (MemExpr->isImplicitAccess()) {
6927 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6928 return DeclRefExpr::Create(Context,
6929 MemExpr->getQualifier(),
6930 MemExpr->getQualifierRange(),
6931 Fn,
6932 MemExpr->getMemberLoc(),
6933 Fn->getType(),
6934 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006935 } else {
6936 SourceLocation Loc = MemExpr->getMemberLoc();
6937 if (MemExpr->getQualifier())
6938 Loc = MemExpr->getQualifierRange().getBegin();
6939 Base = new (Context) CXXThisExpr(Loc,
6940 MemExpr->getBaseType(),
6941 /*isImplicit=*/true);
6942 }
John McCall2d74de92009-12-01 22:10:20 +00006943 } else
6944 Base = MemExpr->getBase()->Retain();
6945
6946 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006947 MemExpr->isArrow(),
6948 MemExpr->getQualifier(),
6949 MemExpr->getQualifierRange(),
6950 Fn,
John McCall16df1e52010-03-30 21:47:33 +00006951 Found,
John McCall6b51f282009-11-23 01:53:49 +00006952 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006953 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006954 Fn->getType());
6955 }
6956
Douglas Gregor51c538b2009-11-20 19:42:02 +00006957 assert(false && "Invalid reference to overloaded function");
6958 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006959}
6960
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006961Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00006962 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006963 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00006964 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006965}
6966
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006967} // end namespace clang