blob: c9c16aafc4122d01ffed13a364ea3761672e02dd [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 Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include "llvm/Support/Compiler.h"
27#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000028#include <cstdio>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000029
30namespace clang {
31
32/// GetConversionCategory - Retrieve the implicit conversion
33/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000034ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035GetConversionCategory(ImplicitConversionKind Kind) {
36 static const ImplicitConversionCategory
37 Category[(int)ICK_Num_Conversion_Kinds] = {
38 ICC_Identity,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Lvalue_Transformation,
42 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,
70 ICR_Promotion,
71 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000072 ICR_Promotion,
73 ICR_Conversion,
74 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000080 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000081 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000082 ICR_Conversion
83 };
84 return Rank[(int)Kind];
85}
86
87/// GetImplicitConversionName - Return the name of this kind of
88/// implicit conversion.
89const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
90 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
91 "No conversion",
92 "Lvalue-to-rvalue",
93 "Array-to-pointer",
94 "Function-to-pointer",
95 "Qualification",
96 "Integral promotion",
97 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +000098 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000099 "Integral conversion",
100 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000101 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Pointer conversion",
105 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000106 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000107 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 };
110 return Name[Kind];
111}
112
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000113/// StandardConversionSequence - Set the standard conversion
114/// sequence to the identity conversion.
115void StandardConversionSequence::setAsIdentityConversion() {
116 First = ICK_Identity;
117 Second = ICK_Identity;
118 Third = ICK_Identity;
119 Deprecated = false;
120 ReferenceBinding = false;
121 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000122 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000123 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000124}
125
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000126/// getRank - Retrieve the rank of this standard conversion sequence
127/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
128/// implicit conversions.
129ImplicitConversionRank StandardConversionSequence::getRank() const {
130 ImplicitConversionRank Rank = ICR_Exact_Match;
131 if (GetConversionRank(First) > Rank)
132 Rank = GetConversionRank(First);
133 if (GetConversionRank(Second) > Rank)
134 Rank = GetConversionRank(Second);
135 if (GetConversionRank(Third) > Rank)
136 Rank = GetConversionRank(Third);
137 return Rank;
138}
139
140/// isPointerConversionToBool - Determines whether this conversion is
141/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000142/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000144bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
146 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
147
148 // Note that FromType has not necessarily been transformed by the
149 // array-to-pointer or function-to-pointer implicit conversions, so
150 // check for their presence as well as checking whether FromType is
151 // a pointer.
152 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000153 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
155 return true;
156
157 return false;
158}
159
Douglas Gregor5c407d92008-10-23 00:40:37 +0000160/// isPointerConversionToVoidPointer - Determines whether this
161/// conversion is a conversion of a pointer to a void pointer. This is
162/// used as part of the ranking of standard conversion sequences (C++
163/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000164bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000165StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000166isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
168 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
169
170 // Note that FromType has not necessarily been transformed by the
171 // array-to-pointer implicit conversion, so check for its presence
172 // and redo the conversion to get a pointer.
173 if (First == ICK_Array_To_Pointer)
174 FromType = Context.getArrayDecayedType(FromType);
175
176 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183/// DebugPrint - Print this standard conversion sequence to standard
184/// error. Useful for debugging overloading issues.
185void StandardConversionSequence::DebugPrint() const {
186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
188 fprintf(stderr, "%s", GetImplicitConversionName(First));
189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
199 fprintf(stderr, " (by copy constructor)");
200 } else if (DirectBinding) {
201 fprintf(stderr, " (direct reference binding)");
202 } else if (ReferenceBinding) {
203 fprintf(stderr, " (reference binding)");
204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
210 fprintf(stderr, " -> ");
211 }
212 fprintf(stderr, "%s", GetImplicitConversionName(Third));
213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
217 fprintf(stderr, "No conversions required");
218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224 if (Before.First || Before.Second || Before.Third) {
225 Before.DebugPrint();
226 fprintf(stderr, " -> ");
227 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 if (After.First || After.Second || After.Third) {
230 fprintf(stderr, " -> ");
231 After.DebugPrint();
232 }
233}
234
235/// DebugPrint - Print this implicit conversion sequence to standard
236/// error. Useful for debugging overloading issues.
237void ImplicitConversionSequence::DebugPrint() const {
238 switch (ConversionKind) {
239 case StandardConversion:
240 fprintf(stderr, "Standard conversion: ");
241 Standard.DebugPrint();
242 break;
243 case UserDefinedConversion:
244 fprintf(stderr, "User-defined conversion: ");
245 UserDefined.DebugPrint();
246 break;
247 case EllipsisConversion:
248 fprintf(stderr, "Ellipsis conversion");
249 break;
250 case BadConversion:
251 fprintf(stderr, "Bad conversion");
252 break;
253 }
254
255 fprintf(stderr, "\n");
256}
257
258// IsOverload - Determine whether the given New declaration is an
259// overload of the Old declaration. This routine returns false if New
260// and Old cannot be overloaded, e.g., if they are functions with the
261// same signature (C++ 1.3.10) or if the Old declaration isn't a
262// function (or overload set). When it does return false and Old is an
263// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump11289f42009-09-09 15:08:12 +0000264// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265//
266// Example: Given the following input:
267//
268// void f(int, float); // #1
269// void f(int, int); // #2
270// int f(int, int); // #3
271//
272// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000273// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274//
275// When we process #2, Old is a FunctionDecl for #1. By comparing the
276// parameter types, we see that #1 and #2 are overloaded (since they
277// have different signatures), so this routine returns false;
278// MatchedDecl is unchanged.
279//
280// When we process #3, Old is an OverloadedFunctionDecl containing #1
281// and #2. We compare the signatures of #3 to #1 (they're overloaded,
282// so we do nothing) and then #3 to #2. Since the signatures of #3 and
283// #2 are identical (return types of functions are not part of the
284// signature), IsOverload returns false and MatchedDecl will be set to
285// point to the FunctionDecl for #2.
286bool
Mike Stump11289f42009-09-09 15:08:12 +0000287Sema::IsOverload(FunctionDecl *New, Decl* OldD,
288 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000303 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
304 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
305 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor23061de2009-06-24 16:50:40 +0000306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308
Douglas Gregor23061de2009-06-24 16:50:40 +0000309 // C++ [temp.fct]p2:
310 // A function template can be overloaded with other function templates
311 // and with normal (non-template) functions.
312 if ((OldTemplate == 0) != (NewTemplate == 0))
313 return true;
314
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000315 // Is the function New an overload of the function Old?
316 QualType OldQType = Context.getCanonicalType(Old->getType());
317 QualType NewQType = Context.getCanonicalType(New->getType());
318
319 // Compare the signatures (C++ 1.3.10) of the two functions to
320 // determine whether they are overloads. If we find any mismatch
321 // in the signature, they are overloads.
322
323 // If either of these functions is a K&R-style function (no
324 // prototype), then we consider them to have matching signatures.
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000327 return false;
328
Douglas Gregor23061de2009-06-24 16:50:40 +0000329 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
330 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000331
332 // The signature of a function includes the types of its
333 // parameters (C++ 1.3.10), which includes the presence or absence
334 // of the ellipsis; see C++ DR 357).
335 if (OldQType != NewQType &&
336 (OldType->getNumArgs() != NewType->getNumArgs() ||
337 OldType->isVariadic() != NewType->isVariadic() ||
338 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
339 NewType->arg_type_begin())))
340 return true;
341
Douglas Gregor23061de2009-06-24 16:50:40 +0000342 // C++ [temp.over.link]p4:
Mike Stump11289f42009-09-09 15:08:12 +0000343 // The signature of a function template consists of its function
Douglas Gregor23061de2009-06-24 16:50:40 +0000344 // signature, its return type and its template parameter list. The names
345 // of the template parameters are significant only for establishing the
Mike Stump11289f42009-09-09 15:08:12 +0000346 // relationship between the template parameters and the rest of the
Douglas Gregor23061de2009-06-24 16:50:40 +0000347 // signature.
348 //
349 // We check the return type and template parameter lists for function
350 // templates first; the remaining checks follow.
351 if (NewTemplate &&
Mike Stump11289f42009-09-09 15:08:12 +0000352 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
353 OldTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000354 false, TPL_TemplateMatch) ||
Douglas Gregor23061de2009-06-24 16:50:40 +0000355 OldType->getResultType() != NewType->getResultType()))
356 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000357
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000358 // If the function is a class member, its signature includes the
359 // cv-qualifiers (if any) on the function itself.
360 //
361 // As part of this, also check whether one of the member functions
362 // is static, in which case they are not overloads (C++
363 // 13.1p2). While not part of the definition of the signature,
364 // this check is important to determine whether these functions
365 // can be overloaded.
366 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
367 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump11289f42009-09-09 15:08:12 +0000368 if (OldMethod && NewMethod &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000369 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb81897c2008-11-21 15:36:28 +0000370 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000371 return true;
372
373 // The signatures match; this is not an overload.
374 return false;
375 } else {
376 // (C++ 13p1):
377 // Only function declarations can be overloaded; object and type
378 // declarations cannot be overloaded.
379 return false;
380 }
381}
382
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000383/// TryImplicitConversion - Attempt to perform an implicit conversion
384/// from the given expression (Expr) to the given type (ToType). This
385/// function returns an implicit conversion sequence that can be used
386/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000387///
388/// void f(float f);
389/// void g(int i) { f(i); }
390///
391/// this routine would produce an implicit conversion sequence to
392/// describe the initialization of f from i, which will be a standard
393/// conversion sequence containing an lvalue-to-rvalue conversion (C++
394/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395//
396/// Note that this routine only determines how the conversion can be
397/// performed; it does not actually perform the conversion. As such,
398/// it will not produce any diagnostics if no conversion is available,
399/// but will instead return an implicit conversion sequence of kind
400/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000401///
402/// If @p SuppressUserConversions, then user-defined conversions are
403/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000404/// If @p AllowExplicit, then explicit user-defined conversions are
405/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000406/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
407/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000408/// If @p UserCast, the implicit conversion is being done for a user-specified
409/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000410ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000411Sema::TryImplicitConversion(Expr* From, QualType ToType,
412 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000413 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000414 bool InOverloadResolution,
415 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000416 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000417 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000418 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000419 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000420 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000421 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000422 (UserDefResult = IsUserDefinedConversion(From, ToType,
423 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000424 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000425 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000426 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000427 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000428 // C++ [over.ics.user]p4:
429 // A conversion of an expression of class type to the same class
430 // type is given Exact Match rank, and a conversion of an
431 // expression of class type to a base class of that type is
432 // given Conversion rank, in spite of the fact that a copy
433 // constructor (i.e., a user-defined conversion function) is
434 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000435 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000436 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000437 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000438 = Context.getCanonicalType(From->getType().getUnqualifiedType());
439 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
440 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441 // Turn this into a "standard" conversion sequence, so that it
442 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000443 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
444 ICS.Standard.setAsIdentityConversion();
445 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
446 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000447 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000448 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000449 ICS.Standard.Second = ICK_Derived_To_Base;
450 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000451 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000452
453 // C++ [over.best.ics]p4:
454 // However, when considering the argument of a user-defined
455 // conversion function that is a candidate by 13.3.1.3 when
456 // invoked for the copying of the temporary in the second step
457 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
458 // 13.3.1.6 in all cases, only standard conversion sequences and
459 // ellipsis conversion sequences are allowed.
460 if (SuppressUserConversions &&
461 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
462 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000463 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000464 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000465 if (UserDefResult == OR_Ambiguous) {
466 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
467 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000468 if (Cand->Viable)
469 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000470 }
471 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000472
473 return ICS;
474}
475
476/// IsStandardConversion - Determines whether there is a standard
477/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
478/// expression From to the type ToType. Standard conversion sequences
479/// only consider non-class types; for conversions that involve class
480/// types, use TryImplicitConversion. If a conversion exists, SCS will
481/// contain the standard conversion sequence required to perform this
482/// conversion and this routine will return true. Otherwise, this
483/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000484bool
485Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000486 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000487 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 QualType FromType = From->getType();
489
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000490 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000491 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000493 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000494 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000495 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000497 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000498 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000499 if (FromType->isRecordType() || ToType->isRecordType()) {
500 if (getLangOptions().CPlusPlus)
501 return false;
502
Mike Stump11289f42009-09-09 15:08:12 +0000503 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000504 }
505
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 // The first conversion can be an lvalue-to-rvalue conversion,
507 // array-to-pointer conversion, or function-to-pointer conversion
508 // (C++ 4p1).
509
Mike Stump11289f42009-09-09 15:08:12 +0000510 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 // An lvalue (3.10) of a non-function, non-array type T can be
512 // converted to an rvalue.
513 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000514 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000515 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000516 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000517 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518
519 // If T is a non-class type, the type of the rvalue is the
520 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000521 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
522 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000523 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000524 } else if (FromType->isArrayType()) {
525 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000526 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000527
528 // An lvalue or rvalue of type "array of N T" or "array of unknown
529 // bound of T" can be converted to an rvalue of type "pointer to
530 // T" (C++ 4.2p1).
531 FromType = Context.getArrayDecayedType(FromType);
532
533 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
534 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000535 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000536
537 // For the purpose of ranking in overload resolution
538 // (13.3.3.1.1), this conversion is considered an
539 // array-to-pointer conversion followed by a qualification
540 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000541 SCS.Second = ICK_Identity;
542 SCS.Third = ICK_Qualification;
543 SCS.ToTypePtr = ToType.getAsOpaquePtr();
544 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000546 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
547 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000548 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549
550 // An lvalue of function type T can be converted to an rvalue of
551 // type "pointer to T." The result is a pointer to the
552 // function. (C++ 4.3p1).
553 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000554 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000555 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000556 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000557 SCS.First = ICK_Function_To_Pointer;
558
559 // We were able to resolve the address of the overloaded function,
560 // so we can convert to the type of that function.
561 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000562 if (ToType->isLValueReferenceType())
563 FromType = Context.getLValueReferenceType(FromType);
564 else if (ToType->isRValueReferenceType())
565 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000566 else if (ToType->isMemberPointerType()) {
567 // Resolve address only succeeds if both sides are member pointers,
568 // but it doesn't have to be the same class. See DR 247.
569 // Note that this means that the type of &Derived::fn can be
570 // Ret (Base::*)(Args) if the fn overload actually found is from the
571 // base class, even if it was brought into the derived class via a
572 // using declaration. The standard isn't clear on this issue at all.
573 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
574 FromType = Context.getMemberPointerType(FromType,
575 Context.getTypeDeclType(M->getParent()).getTypePtr());
576 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000577 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000578 } else {
579 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000580 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000581 }
582
583 // The second conversion can be an integral promotion, floating
584 // point promotion, integral conversion, floating point conversion,
585 // floating-integral conversion, pointer conversion,
586 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000587 // For overloading in C, this can also be a "compatible-type"
588 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000589 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000590 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000591 // The unqualified versions of the types are the same: there's no
592 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000593 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000594 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000595 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000596 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000597 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000598 } else if (IsFloatingPointPromotion(FromType, ToType)) {
599 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000600 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000601 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000602 } else if (IsComplexPromotion(FromType, ToType)) {
603 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000604 SCS.Second = ICK_Complex_Promotion;
605 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000607 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000608 // Integral conversions (C++ 4.7).
609 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000610 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000612 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
613 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000614 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000615 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000616 } else if (FromType->isComplexType() && ToType->isComplexType()) {
617 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000618 SCS.Second = ICK_Complex_Conversion;
619 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000620 } else if ((FromType->isFloatingType() &&
621 ToType->isIntegralType() && (!ToType->isBooleanType() &&
622 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000623 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000624 ToType->isFloatingType())) {
625 // Floating-integral conversions (C++ 4.9).
626 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000627 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000628 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000629 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
630 (ToType->isComplexType() && FromType->isArithmeticType())) {
631 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000632 SCS.Second = ICK_Complex_Real;
633 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000634 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
635 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000636 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000637 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000638 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000639 } else if (IsMemberPointerConversion(From, FromType, ToType,
640 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000641 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000642 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000643 } else if (ToType->isBooleanType() &&
644 (FromType->isArithmeticType() ||
645 FromType->isEnumeralType() ||
646 FromType->isPointerType() ||
647 FromType->isBlockPointerType() ||
648 FromType->isMemberPointerType() ||
649 FromType->isNullPtrType())) {
650 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000651 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000653 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000654 Context.typesAreCompatible(ToType, FromType)) {
655 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000656 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000657 } else {
658 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000659 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000660 }
661
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000662 QualType CanonFrom;
663 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000664 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000665 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000666 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000667 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000668 CanonFrom = Context.getCanonicalType(FromType);
669 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000670 } else {
671 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000672 SCS.Third = ICK_Identity;
673
Mike Stump11289f42009-09-09 15:08:12 +0000674 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000675 // [...] Any difference in top-level cv-qualification is
676 // subsumed by the initialization itself and does not constitute
677 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000678 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000679 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000680 if (CanonFrom.getLocalUnqualifiedType()
681 == CanonTo.getLocalUnqualifiedType() &&
682 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000683 FromType = ToType;
684 CanonFrom = CanonTo;
685 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000686 }
687
688 // If we have not converted the argument type to the parameter type,
689 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000690 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 SCS.ToTypePtr = FromType.getAsOpaquePtr();
694 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000695}
696
697/// IsIntegralPromotion - Determines whether the conversion from the
698/// expression From (whose potentially-adjusted type is FromType) to
699/// ToType is an integral promotion (C++ 4.5). If so, returns true and
700/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000701bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000702 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000703 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000704 if (!To) {
705 return false;
706 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707
708 // An rvalue of type char, signed char, unsigned char, short int, or
709 // unsigned short int can be converted to an rvalue of type int if
710 // int can represent all the values of the source type; otherwise,
711 // the source rvalue can be converted to an rvalue of type unsigned
712 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000713 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 if (// We can promote any signed, promotable integer type to an int
715 (FromType->isSignedIntegerType() ||
716 // We can promote any unsigned integer type whose size is
717 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000718 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000719 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000721 }
722
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::UInt;
724 }
725
726 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
727 // can be converted to an rvalue of the first of the following types
728 // that can represent all the values of its underlying type: int,
729 // unsigned int, long, or unsigned long (C++ 4.5p2).
730 if ((FromType->isEnumeralType() || FromType->isWideCharType())
731 && ToType->isIntegerType()) {
732 // Determine whether the type we're converting from is signed or
733 // unsigned.
734 bool FromIsSigned;
735 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
738 FromIsSigned = UnderlyingType->isSignedIntegerType();
739 } else {
740 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
741 FromIsSigned = true;
742 }
743
744 // The types we'll try to promote to, in the appropriate
745 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000746 QualType PromoteTypes[6] = {
747 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000748 Context.LongTy, Context.UnsignedLongTy ,
749 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000751 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
753 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000754 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
756 // We found the type that we can promote to. If this is the
757 // type we wanted, we have a promotion. Otherwise, no
758 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000759 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000760 }
761 }
762 }
763
764 // An rvalue for an integral bit-field (9.6) can be converted to an
765 // rvalue of type int if int can represent all the values of the
766 // bit-field; otherwise, it can be converted to unsigned int if
767 // unsigned int can represent all the values of the bit-field. If
768 // the bit-field is larger yet, no integral promotion applies to
769 // it. If the bit-field has an enumerated type, it is treated as any
770 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000771 // FIXME: We should delay checking of bit-fields until we actually perform the
772 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000773 using llvm::APSInt;
774 if (From)
775 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000776 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000777 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
778 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
779 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
780 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000781
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000782 // Are we promoting to an int from a bitfield that fits in an int?
783 if (BitWidth < ToSize ||
784 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
785 return To->getKind() == BuiltinType::Int;
786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000788 // Are we promoting to an unsigned int from an unsigned bitfield
789 // that fits into an unsigned int?
790 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
791 return To->getKind() == BuiltinType::UInt;
792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000794 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000795 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000796 }
Mike Stump11289f42009-09-09 15:08:12 +0000797
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000798 // An rvalue of type bool can be converted to an rvalue of type int,
799 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000800 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000801 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000802 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803
804 return false;
805}
806
807/// IsFloatingPointPromotion - Determines whether the conversion from
808/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
809/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000810bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811 /// An rvalue of type float can be converted to an rvalue of type
812 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000813 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
814 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000815 if (FromBuiltin->getKind() == BuiltinType::Float &&
816 ToBuiltin->getKind() == BuiltinType::Double)
817 return true;
818
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000819 // C99 6.3.1.5p1:
820 // When a float is promoted to double or long double, or a
821 // double is promoted to long double [...].
822 if (!getLangOptions().CPlusPlus &&
823 (FromBuiltin->getKind() == BuiltinType::Float ||
824 FromBuiltin->getKind() == BuiltinType::Double) &&
825 (ToBuiltin->getKind() == BuiltinType::LongDouble))
826 return true;
827 }
828
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000829 return false;
830}
831
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000832/// \brief Determine if a conversion is a complex promotion.
833///
834/// A complex promotion is defined as a complex -> complex conversion
835/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000836/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000837bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000838 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000839 if (!FromComplex)
840 return false;
841
John McCall9dd450b2009-09-21 23:43:11 +0000842 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000843 if (!ToComplex)
844 return false;
845
846 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000847 ToComplex->getElementType()) ||
848 IsIntegralPromotion(0, FromComplex->getElementType(),
849 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000850}
851
Douglas Gregor237f96c2008-11-26 23:31:11 +0000852/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
853/// the pointer type FromPtr to a pointer to type ToPointee, with the
854/// same type qualifiers as FromPtr has on its pointee type. ToType,
855/// if non-empty, will be a pointer to ToType that may or may not have
856/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000857static QualType
858BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000859 QualType ToPointee, QualType ToType,
860 ASTContext &Context) {
861 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
862 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000863 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000864
865 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000866 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000867 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000868 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000869 return ToType;
870
871 // Build a pointer to ToPointee. It has the right qualifiers
872 // already.
873 return Context.getPointerType(ToPointee);
874 }
875
876 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000877 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000878 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
879 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000880}
881
Mike Stump11289f42009-09-09 15:08:12 +0000882static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000883 bool InOverloadResolution,
884 ASTContext &Context) {
885 // Handle value-dependent integral null pointer constants correctly.
886 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
887 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
888 Expr->getType()->isIntegralType())
889 return !InOverloadResolution;
890
Douglas Gregor56751b52009-09-25 04:25:58 +0000891 return Expr->isNullPointerConstant(Context,
892 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
893 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000894}
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896/// IsPointerConversion - Determines whether the conversion of the
897/// expression From, which has the (possibly adjusted) type FromType,
898/// can be converted to the type ToType via a pointer conversion (C++
899/// 4.10). If so, returns true and places the converted type (that
900/// might differ from ToType in its cv-qualifiers at some level) into
901/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000902///
Douglas Gregora29dc052008-11-27 01:19:21 +0000903/// This routine also supports conversions to and from block pointers
904/// and conversions with Objective-C's 'id', 'id<protocols...>', and
905/// pointers to interfaces. FIXME: Once we've determined the
906/// appropriate overloading rules for Objective-C, we may want to
907/// split the Objective-C checks into a different routine; however,
908/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000909/// conversions, so for now they live here. IncompatibleObjC will be
910/// set if the conversion is an allowed Objective-C conversion that
911/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000913 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000914 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000915 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000917 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
918 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000919
Mike Stump11289f42009-09-09 15:08:12 +0000920 // Conversion from a null pointer constant to any Objective-C pointer type.
921 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000922 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000923 ConvertedType = ToType;
924 return true;
925 }
926
Douglas Gregor231d1c62008-11-27 00:15:41 +0000927 // Blocks: Block pointers can be converted to void*.
928 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000929 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000930 ConvertedType = ToType;
931 return true;
932 }
933 // Blocks: A null pointer constant can be converted to a block
934 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000937 ConvertedType = ToType;
938 return true;
939 }
940
Sebastian Redl576fd422009-05-10 18:38:11 +0000941 // If the left-hand-side is nullptr_t, the right side can be a null
942 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000943 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000944 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000945 ConvertedType = ToType;
946 return true;
947 }
948
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000949 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950 if (!ToTypePtr)
951 return false;
952
953 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000954 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955 ConvertedType = ToType;
956 return true;
957 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000958
Douglas Gregor237f96c2008-11-26 23:31:11 +0000959 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000961 if (!FromTypePtr)
962 return false;
963
964 QualType FromPointeeType = FromTypePtr->getPointeeType();
965 QualType ToPointeeType = ToTypePtr->getPointeeType();
966
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967 // An rvalue of type "pointer to cv T," where T is an object type,
968 // can be converted to an rvalue of type "pointer to cv void" (C++
969 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000970 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000972 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000973 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 return true;
975 }
976
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000977 // When we're overloading in C, we allow a special kind of pointer
978 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000979 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000980 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000981 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000983 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 return true;
985 }
986
Douglas Gregor5c407d92008-10-23 00:40:37 +0000987 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000988 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000989 // An rvalue of type "pointer to cv D," where D is a class type,
990 // can be converted to an rvalue of type "pointer to cv B," where
991 // B is a base class (clause 10) of D. If B is an inaccessible
992 // (clause 11) or ambiguous (10.2) base class of D, a program that
993 // necessitates this conversion is ill-formed. The result of the
994 // conversion is a pointer to the base class sub-object of the
995 // derived class object. The null pointer value is converted to
996 // the null pointer value of the destination type.
997 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000998 // Note that we do not check for ambiguity or inaccessibility
999 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001000 if (getLangOptions().CPlusPlus &&
1001 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001002 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001003 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001005 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001006 ToType, Context);
1007 return true;
1008 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001009
Douglas Gregora119f102008-12-19 19:13:09 +00001010 return false;
1011}
1012
1013/// isObjCPointerConversion - Determines whether this is an
1014/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1015/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001016bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001017 QualType& ConvertedType,
1018 bool &IncompatibleObjC) {
1019 if (!getLangOptions().ObjC1)
1020 return false;
1021
Steve Naroff7cae42b2009-07-10 23:34:53 +00001022 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001023 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001024 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001025 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001026
Steve Naroff7cae42b2009-07-10 23:34:53 +00001027 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001028 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001029 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001030 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001031 ConvertedType = ToType;
1032 return true;
1033 }
1034 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001035 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001036 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001037 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001038 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001039 ConvertedType = ToType;
1040 return true;
1041 }
1042 // Objective C++: We're able to convert from a pointer to an
1043 // interface to a pointer to a different interface.
1044 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1045 ConvertedType = ToType;
1046 return true;
1047 }
1048
1049 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1050 // Okay: this is some kind of implicit downcast of Objective-C
1051 // interfaces, which is permitted. However, we're going to
1052 // complain about it.
1053 IncompatibleObjC = true;
1054 ConvertedType = FromType;
1055 return true;
1056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001058 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001059 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001061 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001062 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001063 ToPointeeType = ToBlockPtr->getPointeeType();
1064 else
Douglas Gregora119f102008-12-19 19:13:09 +00001065 return false;
1066
Douglas Gregor033f56d2008-12-23 00:53:59 +00001067 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001068 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001069 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001070 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001071 FromPointeeType = FromBlockPtr->getPointeeType();
1072 else
Douglas Gregora119f102008-12-19 19:13:09 +00001073 return false;
1074
Douglas Gregora119f102008-12-19 19:13:09 +00001075 // If we have pointers to pointers, recursively check whether this
1076 // is an Objective-C conversion.
1077 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1078 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1079 IncompatibleObjC)) {
1080 // We always complain about this conversion.
1081 IncompatibleObjC = true;
1082 ConvertedType = ToType;
1083 return true;
1084 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001085 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001086 // differences in the argument and result types are in Objective-C
1087 // pointer conversions. If so, we permit the conversion (but
1088 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001089 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001090 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001091 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001092 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001093 if (FromFunctionType && ToFunctionType) {
1094 // If the function types are exactly the same, this isn't an
1095 // Objective-C pointer conversion.
1096 if (Context.getCanonicalType(FromPointeeType)
1097 == Context.getCanonicalType(ToPointeeType))
1098 return false;
1099
1100 // Perform the quick checks that will tell us whether these
1101 // function types are obviously different.
1102 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1103 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1104 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1105 return false;
1106
1107 bool HasObjCConversion = false;
1108 if (Context.getCanonicalType(FromFunctionType->getResultType())
1109 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1110 // Okay, the types match exactly. Nothing to do.
1111 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1112 ToFunctionType->getResultType(),
1113 ConvertedType, IncompatibleObjC)) {
1114 // Okay, we have an Objective-C pointer conversion.
1115 HasObjCConversion = true;
1116 } else {
1117 // Function types are too different. Abort.
1118 return false;
1119 }
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregora119f102008-12-19 19:13:09 +00001121 // Check argument types.
1122 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1123 ArgIdx != NumArgs; ++ArgIdx) {
1124 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1125 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1126 if (Context.getCanonicalType(FromArgType)
1127 == Context.getCanonicalType(ToArgType)) {
1128 // Okay, the types match exactly. Nothing to do.
1129 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1130 ConvertedType, IncompatibleObjC)) {
1131 // Okay, we have an Objective-C pointer conversion.
1132 HasObjCConversion = true;
1133 } else {
1134 // Argument types are too different. Abort.
1135 return false;
1136 }
1137 }
1138
1139 if (HasObjCConversion) {
1140 // We had an Objective-C conversion. Allow this pointer
1141 // conversion, but complain about it.
1142 ConvertedType = ToType;
1143 IncompatibleObjC = true;
1144 return true;
1145 }
1146 }
1147
Sebastian Redl72b597d2009-01-25 19:43:20 +00001148 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001149}
1150
Douglas Gregor39c16d42008-10-24 04:54:22 +00001151/// CheckPointerConversion - Check the pointer conversion from the
1152/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001153/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001154/// conversions for which IsPointerConversion has already returned
1155/// true. It returns true and produces a diagnostic if there was an
1156/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001157bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001158 CastExpr::CastKind &Kind,
1159 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001160 QualType FromType = From->getType();
1161
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001162 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1163 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001164 QualType FromPointeeType = FromPtrType->getPointeeType(),
1165 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001166
Douglas Gregor39c16d42008-10-24 04:54:22 +00001167 if (FromPointeeType->isRecordType() &&
1168 ToPointeeType->isRecordType()) {
1169 // We must have a derived-to-base conversion. Check an
1170 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001171 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1172 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001173 From->getSourceRange(),
1174 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001175 return true;
1176
1177 // The conversion was successful.
1178 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001179 }
1180 }
Mike Stump11289f42009-09-09 15:08:12 +00001181 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001182 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001183 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001184 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001185 // Objective-C++ conversions are always okay.
1186 // FIXME: We should have a different class of conversions for the
1187 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001188 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001189 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001190
Steve Naroff7cae42b2009-07-10 23:34:53 +00001191 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001192 return false;
1193}
1194
Sebastian Redl72b597d2009-01-25 19:43:20 +00001195/// IsMemberPointerConversion - Determines whether the conversion of the
1196/// expression From, which has the (possibly adjusted) type FromType, can be
1197/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1198/// If so, returns true and places the converted type (that might differ from
1199/// ToType in its cv-qualifiers at some level) into ConvertedType.
1200bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001201 QualType ToType,
1202 bool InOverloadResolution,
1203 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001204 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001205 if (!ToTypePtr)
1206 return false;
1207
1208 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001209 if (From->isNullPointerConstant(Context,
1210 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1211 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001212 ConvertedType = ToType;
1213 return true;
1214 }
1215
1216 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001217 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001218 if (!FromTypePtr)
1219 return false;
1220
1221 // A pointer to member of B can be converted to a pointer to member of D,
1222 // where D is derived from B (C++ 4.11p2).
1223 QualType FromClass(FromTypePtr->getClass(), 0);
1224 QualType ToClass(ToTypePtr->getClass(), 0);
1225 // FIXME: What happens when these are dependent? Is this function even called?
1226
1227 if (IsDerivedFrom(ToClass, FromClass)) {
1228 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1229 ToClass.getTypePtr());
1230 return true;
1231 }
1232
1233 return false;
1234}
1235
1236/// CheckMemberPointerConversion - Check the member pointer conversion from the
1237/// expression From to the type ToType. This routine checks for ambiguous or
1238/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1239/// for which IsMemberPointerConversion has already returned true. It returns
1240/// true and produces a diagnostic if there was an error, or returns false
1241/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001242bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001243 CastExpr::CastKind &Kind,
1244 bool IgnoreBaseAccess) {
1245 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001246 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001247 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001248 if (!FromPtrType) {
1249 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001250 assert(From->isNullPointerConstant(Context,
1251 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001252 "Expr must be null pointer constant!");
1253 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001254 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001255 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001256
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001257 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001258 assert(ToPtrType && "No member pointer cast has a target type "
1259 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001260
Sebastian Redled8f2002009-01-28 18:33:18 +00001261 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1262 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001263
Sebastian Redled8f2002009-01-28 18:33:18 +00001264 // FIXME: What about dependent types?
1265 assert(FromClass->isRecordType() && "Pointer into non-class.");
1266 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001267
Douglas Gregor36d1b142009-10-06 17:59:45 +00001268 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1269 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001270 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1271 assert(DerivationOkay &&
1272 "Should not have been called if derivation isn't OK.");
1273 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001274
Sebastian Redled8f2002009-01-28 18:33:18 +00001275 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1276 getUnqualifiedType())) {
1277 // Derivation is ambiguous. Redo the check to find the exact paths.
1278 Paths.clear();
1279 Paths.setRecordingPaths(true);
1280 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1281 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1282 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001283
Sebastian Redled8f2002009-01-28 18:33:18 +00001284 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1285 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1286 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1287 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001288 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001289
Douglas Gregor89ee6822009-02-28 01:32:25 +00001290 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001291 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1292 << FromClass << ToClass << QualType(VBase, 0)
1293 << From->getSourceRange();
1294 return true;
1295 }
1296
Anders Carlssond7923c62009-08-22 23:33:40 +00001297 // Must be a base to derived member conversion.
1298 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001299 return false;
1300}
1301
Douglas Gregor9a657932008-10-21 23:43:52 +00001302/// IsQualificationConversion - Determines whether the conversion from
1303/// an rvalue of type FromType to ToType is a qualification conversion
1304/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001305bool
1306Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001307 FromType = Context.getCanonicalType(FromType);
1308 ToType = Context.getCanonicalType(ToType);
1309
1310 // If FromType and ToType are the same type, this is not a
1311 // qualification conversion.
1312 if (FromType == ToType)
1313 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001314
Douglas Gregor9a657932008-10-21 23:43:52 +00001315 // (C++ 4.4p4):
1316 // A conversion can add cv-qualifiers at levels other than the first
1317 // in multi-level pointers, subject to the following rules: [...]
1318 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001319 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001320 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001321 // Within each iteration of the loop, we check the qualifiers to
1322 // determine if this still looks like a qualification
1323 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001324 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001325 // until there are no more pointers or pointers-to-members left to
1326 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001327 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001328
1329 // -- for every j > 0, if const is in cv 1,j then const is in cv
1330 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001331 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001332 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001333
Douglas Gregor9a657932008-10-21 23:43:52 +00001334 // -- if the cv 1,j and cv 2,j are different, then const is in
1335 // every cv for 0 < k < j.
1336 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001337 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001338 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001339
Douglas Gregor9a657932008-10-21 23:43:52 +00001340 // Keep track of whether all prior cv-qualifiers in the "to" type
1341 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001342 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001343 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001344 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001345
1346 // We are left with FromType and ToType being the pointee types
1347 // after unwrapping the original FromType and ToType the same number
1348 // of types. If we unwrapped any pointers, and if FromType and
1349 // ToType have the same unqualified type (since we checked
1350 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001351 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001352}
1353
Douglas Gregor05155d82009-08-21 23:19:43 +00001354/// \brief Given a function template or function, extract the function template
1355/// declaration (if any) and the underlying function declaration.
1356template<typename T>
1357static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1358 FunctionTemplateDecl *&FunctionTemplate) {
1359 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1360 if (FunctionTemplate)
1361 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1362 else
1363 Function = cast<T>(Orig);
1364}
1365
Douglas Gregor576e98c2009-01-30 23:27:23 +00001366/// Determines whether there is a user-defined conversion sequence
1367/// (C++ [over.ics.user]) that converts expression From to the type
1368/// ToType. If such a conversion exists, User will contain the
1369/// user-defined conversion sequence that performs such a conversion
1370/// and this routine will return true. Otherwise, this routine returns
1371/// false and User is unspecified.
1372///
1373/// \param AllowConversionFunctions true if the conversion should
1374/// consider conversion functions at all. If false, only constructors
1375/// will be considered.
1376///
1377/// \param AllowExplicit true if the conversion should consider C++0x
1378/// "explicit" conversion functions as well as non-explicit conversion
1379/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001380///
1381/// \param ForceRValue true if the expression should be treated as an rvalue
1382/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001383/// \param UserCast true if looking for user defined conversion for a static
1384/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001385Sema::OverloadingResult Sema::IsUserDefinedConversion(
1386 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001387 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001388 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001389 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001390 bool AllowExplicit, bool ForceRValue,
1391 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001392 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001393 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1394 // We're not going to find any constructors.
1395 } else if (CXXRecordDecl *ToRecordDecl
1396 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001397 // C++ [over.match.ctor]p1:
1398 // When objects of class type are direct-initialized (8.5), or
1399 // copy-initialized from an expression of the same or a
1400 // derived class type (8.5), overload resolution selects the
1401 // constructor. [...] For copy-initialization, the candidate
1402 // functions are all the converting constructors (12.3.1) of
1403 // that class. The argument list is the expression-list within
1404 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001405 bool SuppressUserConversions = !UserCast;
1406 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1407 IsDerivedFrom(From->getType(), ToType)) {
1408 SuppressUserConversions = false;
1409 AllowConversionFunctions = false;
1410 }
1411
Mike Stump11289f42009-09-09 15:08:12 +00001412 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001413 = Context.DeclarationNames.getCXXConstructorName(
1414 Context.getCanonicalType(ToType).getUnqualifiedType());
1415 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001416 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001417 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001418 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001419 // Find the constructor (which may be a template).
1420 CXXConstructorDecl *Constructor = 0;
1421 FunctionTemplateDecl *ConstructorTmpl
1422 = dyn_cast<FunctionTemplateDecl>(*Con);
1423 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001424 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001425 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1426 else
1427 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001428
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001429 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001430 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001431 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001432 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001433 1, CandidateSet,
1434 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001435 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001436 // Allow one user-defined conversion when user specifies a
1437 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001438 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001439 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001440 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001441 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001442 }
1443 }
1444
Douglas Gregor576e98c2009-01-30 23:27:23 +00001445 if (!AllowConversionFunctions) {
1446 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001447 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1448 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001449 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001450 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001451 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001452 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001453 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001454 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1455 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001456 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001457 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001458 for (OverloadedFunctionDecl::function_iterator Func
1459 = Conversions->function_begin();
1460 Func != Conversions->function_end(); ++Func) {
1461 CXXConversionDecl *Conv;
1462 FunctionTemplateDecl *ConvTemplate;
1463 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1464 if (ConvTemplate)
1465 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1466 else
1467 Conv = dyn_cast<CXXConversionDecl>(*Func);
1468
1469 if (AllowExplicit || !Conv->isExplicit()) {
1470 if (ConvTemplate)
1471 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1472 CandidateSet);
1473 else
1474 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1475 }
1476 }
1477 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001478 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001479
1480 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001481 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001482 case OR_Success:
1483 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001484 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001485 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1486 // C++ [over.ics.user]p1:
1487 // If the user-defined conversion is specified by a
1488 // constructor (12.3.1), the initial standard conversion
1489 // sequence converts the source type to the type required by
1490 // the argument of the constructor.
1491 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001492 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001493 if (Best->Conversions[0].ConversionKind ==
1494 ImplicitConversionSequence::EllipsisConversion)
1495 User.EllipsisConversion = true;
1496 else {
1497 User.Before = Best->Conversions[0].Standard;
1498 User.EllipsisConversion = false;
1499 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 User.ConversionFunction = Constructor;
1501 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001502 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001503 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001504 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001505 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001506 } else if (CXXConversionDecl *Conversion
1507 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1508 // C++ [over.ics.user]p1:
1509 //
1510 // [...] If the user-defined conversion is specified by a
1511 // conversion function (12.3.2), the initial standard
1512 // conversion sequence converts the source type to the
1513 // implicit object parameter of the conversion function.
1514 User.Before = Best->Conversions[0].Standard;
1515 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001516 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001517
1518 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001519 // The second standard conversion sequence converts the
1520 // result of the user-defined conversion to the target type
1521 // for the sequence. Since an implicit conversion sequence
1522 // is an initialization, the special rules for
1523 // initialization by user-defined conversion apply when
1524 // selecting the best user-defined conversion for a
1525 // user-defined conversion sequence (see 13.3.3 and
1526 // 13.3.3.1).
1527 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001528 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001529 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001530 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001531 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001532 }
Mike Stump11289f42009-09-09 15:08:12 +00001533
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001534 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001535 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001536 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001537 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001538 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539
1540 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001541 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 }
1543
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001544 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001546
1547bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001548Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001549 ImplicitConversionSequence ICS;
1550 OverloadCandidateSet CandidateSet;
1551 OverloadingResult OvResult =
1552 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1553 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001554 if (OvResult == OR_Ambiguous)
1555 Diag(From->getSourceRange().getBegin(),
1556 diag::err_typecheck_ambiguous_condition)
1557 << From->getType() << ToType << From->getSourceRange();
1558 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1559 Diag(From->getSourceRange().getBegin(),
1560 diag::err_typecheck_nonviable_condition)
1561 << From->getType() << ToType << From->getSourceRange();
1562 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001563 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001564 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001565 return true;
1566}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001567
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568/// CompareImplicitConversionSequences - Compare two implicit
1569/// conversion sequences to determine whether one is better than the
1570/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001571ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1573 const ImplicitConversionSequence& ICS2)
1574{
1575 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1576 // conversion sequences (as defined in 13.3.3.1)
1577 // -- a standard conversion sequence (13.3.3.1.1) is a better
1578 // conversion sequence than a user-defined conversion sequence or
1579 // an ellipsis conversion sequence, and
1580 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1581 // conversion sequence than an ellipsis conversion sequence
1582 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001583 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584 if (ICS1.ConversionKind < ICS2.ConversionKind)
1585 return ImplicitConversionSequence::Better;
1586 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1587 return ImplicitConversionSequence::Worse;
1588
1589 // Two implicit conversion sequences of the same form are
1590 // indistinguishable conversion sequences unless one of the
1591 // following rules apply: (C++ 13.3.3.2p3):
1592 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1593 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001594 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595 ImplicitConversionSequence::UserDefinedConversion) {
1596 // User-defined conversion sequence U1 is a better conversion
1597 // sequence than another user-defined conversion sequence U2 if
1598 // they contain the same user-defined conversion function or
1599 // constructor and if the second standard conversion sequence of
1600 // U1 is better than the second standard conversion sequence of
1601 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001602 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001603 ICS2.UserDefined.ConversionFunction)
1604 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1605 ICS2.UserDefined.After);
1606 }
1607
1608 return ImplicitConversionSequence::Indistinguishable;
1609}
1610
1611/// CompareStandardConversionSequences - Compare two standard
1612/// conversion sequences to determine whether one is better than the
1613/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001614ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1616 const StandardConversionSequence& SCS2)
1617{
1618 // Standard conversion sequence S1 is a better conversion sequence
1619 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1620
1621 // -- S1 is a proper subsequence of S2 (comparing the conversion
1622 // sequences in the canonical form defined by 13.3.3.1.1,
1623 // excluding any Lvalue Transformation; the identity conversion
1624 // sequence is considered to be a subsequence of any
1625 // non-identity conversion sequence) or, if not that,
1626 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1627 // Neither is a proper subsequence of the other. Do nothing.
1628 ;
1629 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1630 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001631 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632 SCS1.Third == ICK_Identity))
1633 // SCS1 is a proper subsequence of SCS2.
1634 return ImplicitConversionSequence::Better;
1635 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1636 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001637 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 SCS2.Third == ICK_Identity))
1639 // SCS2 is a proper subsequence of SCS1.
1640 return ImplicitConversionSequence::Worse;
1641
1642 // -- the rank of S1 is better than the rank of S2 (by the rules
1643 // defined below), or, if not that,
1644 ImplicitConversionRank Rank1 = SCS1.getRank();
1645 ImplicitConversionRank Rank2 = SCS2.getRank();
1646 if (Rank1 < Rank2)
1647 return ImplicitConversionSequence::Better;
1648 else if (Rank2 < Rank1)
1649 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001650
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001651 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1652 // are indistinguishable unless one of the following rules
1653 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001654
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001655 // A conversion that is not a conversion of a pointer, or
1656 // pointer to member, to bool is better than another conversion
1657 // that is such a conversion.
1658 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1659 return SCS2.isPointerConversionToBool()
1660 ? ImplicitConversionSequence::Better
1661 : ImplicitConversionSequence::Worse;
1662
Douglas Gregor5c407d92008-10-23 00:40:37 +00001663 // C++ [over.ics.rank]p4b2:
1664 //
1665 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001666 // conversion of B* to A* is better than conversion of B* to
1667 // void*, and conversion of A* to void* is better than conversion
1668 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001669 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001670 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001671 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001672 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001673 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1674 // Exactly one of the conversion sequences is a conversion to
1675 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001676 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1677 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001678 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1679 // Neither conversion sequence converts to a void pointer; compare
1680 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001681 if (ImplicitConversionSequence::CompareKind DerivedCK
1682 = CompareDerivedToBaseConversions(SCS1, SCS2))
1683 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001684 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1685 // Both conversion sequences are conversions to void
1686 // pointers. Compare the source types to determine if there's an
1687 // inheritance relationship in their sources.
1688 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1689 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1690
1691 // Adjust the types we're converting from via the array-to-pointer
1692 // conversion, if we need to.
1693 if (SCS1.First == ICK_Array_To_Pointer)
1694 FromType1 = Context.getArrayDecayedType(FromType1);
1695 if (SCS2.First == ICK_Array_To_Pointer)
1696 FromType2 = Context.getArrayDecayedType(FromType2);
1697
Mike Stump11289f42009-09-09 15:08:12 +00001698 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001699 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001700 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001701 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001702
1703 if (IsDerivedFrom(FromPointee2, FromPointee1))
1704 return ImplicitConversionSequence::Better;
1705 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1706 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001707
1708 // Objective-C++: If one interface is more specific than the
1709 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001710 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1711 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001712 if (FromIface1 && FromIface1) {
1713 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1714 return ImplicitConversionSequence::Better;
1715 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1716 return ImplicitConversionSequence::Worse;
1717 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001718 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001719
1720 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1721 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001722 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001723 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001724 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001725
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001726 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001727 // C++0x [over.ics.rank]p3b4:
1728 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1729 // implicit object parameter of a non-static member function declared
1730 // without a ref-qualifier, and S1 binds an rvalue reference to an
1731 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001732 // FIXME: We don't know if we're dealing with the implicit object parameter,
1733 // or if the member function in this case has a ref qualifier.
1734 // (Of course, we don't have ref qualifiers yet.)
1735 if (SCS1.RRefBinding != SCS2.RRefBinding)
1736 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1737 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001738
1739 // C++ [over.ics.rank]p3b4:
1740 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1741 // which the references refer are the same type except for
1742 // top-level cv-qualifiers, and the type to which the reference
1743 // initialized by S2 refers is more cv-qualified than the type
1744 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001745 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1746 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001747 T1 = Context.getCanonicalType(T1);
1748 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001749 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001750 if (T2.isMoreQualifiedThan(T1))
1751 return ImplicitConversionSequence::Better;
1752 else if (T1.isMoreQualifiedThan(T2))
1753 return ImplicitConversionSequence::Worse;
1754 }
1755 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001756
1757 return ImplicitConversionSequence::Indistinguishable;
1758}
1759
1760/// CompareQualificationConversions - Compares two standard conversion
1761/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001762/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1763ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001764Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001765 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001766 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001767 // -- S1 and S2 differ only in their qualification conversion and
1768 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1769 // cv-qualification signature of type T1 is a proper subset of
1770 // the cv-qualification signature of type T2, and S1 is not the
1771 // deprecated string literal array-to-pointer conversion (4.2).
1772 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1773 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1774 return ImplicitConversionSequence::Indistinguishable;
1775
1776 // FIXME: the example in the standard doesn't use a qualification
1777 // conversion (!)
1778 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1779 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1780 T1 = Context.getCanonicalType(T1);
1781 T2 = Context.getCanonicalType(T2);
1782
1783 // If the types are the same, we won't learn anything by unwrapped
1784 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001785 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001786 return ImplicitConversionSequence::Indistinguishable;
1787
Mike Stump11289f42009-09-09 15:08:12 +00001788 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001789 = ImplicitConversionSequence::Indistinguishable;
1790 while (UnwrapSimilarPointerTypes(T1, T2)) {
1791 // Within each iteration of the loop, we check the qualifiers to
1792 // determine if this still looks like a qualification
1793 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001794 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001795 // until there are no more pointers or pointers-to-members left
1796 // to unwrap. This essentially mimics what
1797 // IsQualificationConversion does, but here we're checking for a
1798 // strict subset of qualifiers.
1799 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1800 // The qualifiers are the same, so this doesn't tell us anything
1801 // about how the sequences rank.
1802 ;
1803 else if (T2.isMoreQualifiedThan(T1)) {
1804 // T1 has fewer qualifiers, so it could be the better sequence.
1805 if (Result == ImplicitConversionSequence::Worse)
1806 // Neither has qualifiers that are a subset of the other's
1807 // qualifiers.
1808 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001809
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001810 Result = ImplicitConversionSequence::Better;
1811 } else if (T1.isMoreQualifiedThan(T2)) {
1812 // T2 has fewer qualifiers, so it could be the better sequence.
1813 if (Result == ImplicitConversionSequence::Better)
1814 // Neither has qualifiers that are a subset of the other's
1815 // qualifiers.
1816 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001817
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001818 Result = ImplicitConversionSequence::Worse;
1819 } else {
1820 // Qualifiers are disjoint.
1821 return ImplicitConversionSequence::Indistinguishable;
1822 }
1823
1824 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001825 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001826 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 }
1828
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001829 // Check that the winning standard conversion sequence isn't using
1830 // the deprecated string literal array to pointer conversion.
1831 switch (Result) {
1832 case ImplicitConversionSequence::Better:
1833 if (SCS1.Deprecated)
1834 Result = ImplicitConversionSequence::Indistinguishable;
1835 break;
1836
1837 case ImplicitConversionSequence::Indistinguishable:
1838 break;
1839
1840 case ImplicitConversionSequence::Worse:
1841 if (SCS2.Deprecated)
1842 Result = ImplicitConversionSequence::Indistinguishable;
1843 break;
1844 }
1845
1846 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001847}
1848
Douglas Gregor5c407d92008-10-23 00:40:37 +00001849/// CompareDerivedToBaseConversions - Compares two standard conversion
1850/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001851/// various kinds of derived-to-base conversions (C++
1852/// [over.ics.rank]p4b3). As part of these checks, we also look at
1853/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001854ImplicitConversionSequence::CompareKind
1855Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1856 const StandardConversionSequence& SCS2) {
1857 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1858 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1859 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1860 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1861
1862 // Adjust the types we're converting from via the array-to-pointer
1863 // conversion, if we need to.
1864 if (SCS1.First == ICK_Array_To_Pointer)
1865 FromType1 = Context.getArrayDecayedType(FromType1);
1866 if (SCS2.First == ICK_Array_To_Pointer)
1867 FromType2 = Context.getArrayDecayedType(FromType2);
1868
1869 // Canonicalize all of the types.
1870 FromType1 = Context.getCanonicalType(FromType1);
1871 ToType1 = Context.getCanonicalType(ToType1);
1872 FromType2 = Context.getCanonicalType(FromType2);
1873 ToType2 = Context.getCanonicalType(ToType2);
1874
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001875 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001876 //
1877 // If class B is derived directly or indirectly from class A and
1878 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001879 //
1880 // For Objective-C, we let A, B, and C also be Objective-C
1881 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001882
1883 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001884 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001885 SCS2.Second == ICK_Pointer_Conversion &&
1886 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1887 FromType1->isPointerType() && FromType2->isPointerType() &&
1888 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001889 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001890 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001891 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001892 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001893 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001894 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001895 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001896 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001897
John McCall9dd450b2009-09-21 23:43:11 +00001898 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1899 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1900 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1901 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001902
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001903 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001904 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1905 if (IsDerivedFrom(ToPointee1, ToPointee2))
1906 return ImplicitConversionSequence::Better;
1907 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1908 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001909
1910 if (ToIface1 && ToIface2) {
1911 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1912 return ImplicitConversionSequence::Better;
1913 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1914 return ImplicitConversionSequence::Worse;
1915 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001916 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001917
1918 // -- conversion of B* to A* is better than conversion of C* to A*,
1919 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1920 if (IsDerivedFrom(FromPointee2, FromPointee1))
1921 return ImplicitConversionSequence::Better;
1922 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1923 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001924
Douglas Gregor237f96c2008-11-26 23:31:11 +00001925 if (FromIface1 && FromIface2) {
1926 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1927 return ImplicitConversionSequence::Better;
1928 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1929 return ImplicitConversionSequence::Worse;
1930 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001931 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001932 }
1933
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001934 // Compare based on reference bindings.
1935 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1936 SCS1.Second == ICK_Derived_To_Base) {
1937 // -- binding of an expression of type C to a reference of type
1938 // B& is better than binding an expression of type C to a
1939 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001940 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1941 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001942 if (IsDerivedFrom(ToType1, ToType2))
1943 return ImplicitConversionSequence::Better;
1944 else if (IsDerivedFrom(ToType2, ToType1))
1945 return ImplicitConversionSequence::Worse;
1946 }
1947
Douglas Gregor2fe98832008-11-03 19:09:14 +00001948 // -- binding of an expression of type B to a reference of type
1949 // A& is better than binding an expression of type C to a
1950 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001951 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1952 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001953 if (IsDerivedFrom(FromType2, FromType1))
1954 return ImplicitConversionSequence::Better;
1955 else if (IsDerivedFrom(FromType1, FromType2))
1956 return ImplicitConversionSequence::Worse;
1957 }
1958 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001959
1960 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001961 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1962 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1963 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1964 const MemberPointerType * FromMemPointer1 =
1965 FromType1->getAs<MemberPointerType>();
1966 const MemberPointerType * ToMemPointer1 =
1967 ToType1->getAs<MemberPointerType>();
1968 const MemberPointerType * FromMemPointer2 =
1969 FromType2->getAs<MemberPointerType>();
1970 const MemberPointerType * ToMemPointer2 =
1971 ToType2->getAs<MemberPointerType>();
1972 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1973 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1974 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1975 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1976 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1977 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1978 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1979 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001980 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001981 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1982 if (IsDerivedFrom(ToPointee1, ToPointee2))
1983 return ImplicitConversionSequence::Worse;
1984 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1985 return ImplicitConversionSequence::Better;
1986 }
1987 // conversion of B::* to C::* is better than conversion of A::* to C::*
1988 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1989 if (IsDerivedFrom(FromPointee1, FromPointee2))
1990 return ImplicitConversionSequence::Better;
1991 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1992 return ImplicitConversionSequence::Worse;
1993 }
1994 }
1995
Douglas Gregor2fe98832008-11-03 19:09:14 +00001996 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1997 SCS1.Second == ICK_Derived_To_Base) {
1998 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001999 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2000 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002001 if (IsDerivedFrom(ToType1, ToType2))
2002 return ImplicitConversionSequence::Better;
2003 else if (IsDerivedFrom(ToType2, ToType1))
2004 return ImplicitConversionSequence::Worse;
2005 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002006
Douglas Gregor2fe98832008-11-03 19:09:14 +00002007 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002008 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2009 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002010 if (IsDerivedFrom(FromType2, FromType1))
2011 return ImplicitConversionSequence::Better;
2012 else if (IsDerivedFrom(FromType1, FromType2))
2013 return ImplicitConversionSequence::Worse;
2014 }
2015 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002016
Douglas Gregor5c407d92008-10-23 00:40:37 +00002017 return ImplicitConversionSequence::Indistinguishable;
2018}
2019
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002020/// TryCopyInitialization - Try to copy-initialize a value of type
2021/// ToType from the expression From. Return the implicit conversion
2022/// sequence required to pass this argument, which may be a bad
2023/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002024/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002025/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2026/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002027ImplicitConversionSequence
2028Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002029 bool SuppressUserConversions, bool ForceRValue,
2030 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002031 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002032 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002033 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002034 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002035 SuppressUserConversions,
2036 /*AllowExplicit=*/false,
2037 ForceRValue,
2038 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002039 return ICS;
2040 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002041 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002042 SuppressUserConversions,
2043 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002044 ForceRValue,
2045 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002046 }
2047}
2048
Sebastian Redl42e92c42009-04-12 17:16:29 +00002049/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2050/// the expression @p From. Returns true (and emits a diagnostic) if there was
2051/// an error, returns false if the initialization succeeded. Elidable should
2052/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2053/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002054bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002055 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002056 if (!getLangOptions().CPlusPlus) {
2057 // In C, argument passing is the same as performing an assignment.
2058 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002060 AssignConvertType ConvTy =
2061 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002062 if (ConvTy != Compatible &&
2063 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2064 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002065
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002066 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2067 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002068 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002069
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002070 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002071 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002072 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002073 /*SuppressUserConversions=*/false,
2074 /*AllowExplicit=*/false,
2075 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002076
Sebastian Redl42e92c42009-04-12 17:16:29 +00002077 if (!PerformImplicitConversion(From, ToType, Flavor,
2078 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002079 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002080 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002081 return Diag(From->getSourceRange().getBegin(),
2082 diag::err_typecheck_convert_incompatible)
2083 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002084 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002085}
2086
Douglas Gregor436424c2008-11-18 23:14:02 +00002087/// TryObjectArgumentInitialization - Try to initialize the object
2088/// parameter of the given member function (@c Method) from the
2089/// expression @p From.
2090ImplicitConversionSequence
2091Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2092 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall8ccfcb52009-09-24 19:53:00 +00002093 QualType ImplicitParamType
2094 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor436424c2008-11-18 23:14:02 +00002095
2096 // Set up the conversion sequence as a "bad" conversion, to allow us
2097 // to exit early.
2098 ImplicitConversionSequence ICS;
2099 ICS.Standard.setAsIdentityConversion();
2100 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2101
2102 // We need to have an object of class type.
2103 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002104 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002105 FromType = PT->getPointeeType();
2106
2107 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002108
2109 // The implicit object parmeter is has the type "reference to cv X",
2110 // where X is the class of which the function is a member
2111 // (C++ [over.match.funcs]p4). However, when finding an implicit
2112 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002113 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002114 // (C++ [over.match.funcs]p5). We perform a simplified version of
2115 // reference binding here, that allows class rvalues to bind to
2116 // non-constant references.
2117
2118 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2119 // with the implicit object parameter (C++ [over.match.funcs]p5).
2120 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002121 if (ImplicitParamType.getCVRQualifiers()
2122 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002123 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002124 return ICS;
2125
2126 // Check that we have either the same type or a derived type. It
2127 // affects the conversion rank.
2128 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002129 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002130 ICS.Standard.Second = ICK_Identity;
2131 else if (IsDerivedFrom(FromType, ClassType))
2132 ICS.Standard.Second = ICK_Derived_To_Base;
2133 else
2134 return ICS;
2135
2136 // Success. Mark this as a reference binding.
2137 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2138 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2139 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2140 ICS.Standard.ReferenceBinding = true;
2141 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002142 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002143 return ICS;
2144}
2145
2146/// PerformObjectArgumentInitialization - Perform initialization of
2147/// the implicit object parameter for the given Method with the given
2148/// expression.
2149bool
2150Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002151 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002152 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002153 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002154
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002155 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002156 FromRecordType = PT->getPointeeType();
2157 DestType = Method->getThisType(Context);
2158 } else {
2159 FromRecordType = From->getType();
2160 DestType = ImplicitParamRecordType;
2161 }
2162
Mike Stump11289f42009-09-09 15:08:12 +00002163 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002164 = TryObjectArgumentInitialization(From, Method);
2165 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2166 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002167 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002168 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002169
Douglas Gregor436424c2008-11-18 23:14:02 +00002170 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002171 CheckDerivedToBaseConversion(FromRecordType,
2172 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002173 From->getSourceRange().getBegin(),
2174 From->getSourceRange()))
2175 return true;
2176
Mike Stump11289f42009-09-09 15:08:12 +00002177 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002178 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002179 return false;
2180}
2181
Douglas Gregor5fb53972009-01-14 15:45:31 +00002182/// TryContextuallyConvertToBool - Attempt to contextually convert the
2183/// expression From to bool (C++0x [conv]p3).
2184ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002185 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002186 // FIXME: Are these flags correct?
2187 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002188 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002189 /*ForceRValue=*/false,
2190 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002191}
2192
2193/// PerformContextuallyConvertToBool - Perform a contextual conversion
2194/// of the expression From to bool (C++0x [conv]p3).
2195bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2196 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2197 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2198 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002199
Fariborz Jahanian76197412009-11-18 18:26:29 +00002200 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002201 return Diag(From->getSourceRange().getBegin(),
2202 diag::err_typecheck_bool_condition)
2203 << From->getType() << From->getSourceRange();
2204 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002205}
2206
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002207/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002208/// candidate functions, using the given function call arguments. If
2209/// @p SuppressUserConversions, then don't allow user-defined
2210/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002211/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2212/// hacky way to implement the overloading rules for elidable copy
2213/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002214///
2215/// \para PartialOverloading true if we are performing "partial" overloading
2216/// based on an incomplete set of function arguments. This feature is used by
2217/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002218void
2219Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002220 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002221 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002222 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002223 bool ForceRValue,
2224 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002225 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002226 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002227 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002228 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002229 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002230 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002231 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002232
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002234 if (!isa<CXXConstructorDecl>(Method)) {
2235 // If we get here, it's because we're calling a member function
2236 // that is named without a member access expression (e.g.,
2237 // "this->f") that was either written explicitly or created
2238 // implicitly. This can happen with a qualified call to a member
2239 // function, e.g., X::f(). We use a NULL object as the implied
2240 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002241 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002242 SuppressUserConversions, ForceRValue);
2243 return;
2244 }
2245 // We treat a constructor like a non-member function, since its object
2246 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002247 }
2248
Douglas Gregorff7028a2009-11-13 23:59:09 +00002249 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002250 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002251
2252 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2253 // C++ [class.copy]p3:
2254 // A member function template is never instantiated to perform the copy
2255 // of a class object to an object of its class type.
2256 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2257 if (NumArgs == 1 &&
2258 Constructor->isCopyConstructorLikeSpecialization() &&
2259 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2260 return;
2261 }
2262
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002263 // Add this candidate
2264 CandidateSet.push_back(OverloadCandidate());
2265 OverloadCandidate& Candidate = CandidateSet.back();
2266 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002267 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002268 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002269 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002270
2271 unsigned NumArgsInProto = Proto->getNumArgs();
2272
2273 // (C++ 13.3.2p2): A candidate function having fewer than m
2274 // parameters is viable only if it has an ellipsis in its parameter
2275 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002276 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2277 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002278 Candidate.Viable = false;
2279 return;
2280 }
2281
2282 // (C++ 13.3.2p2): A candidate function having more than m parameters
2283 // is viable only if the (m+1)st parameter has a default argument
2284 // (8.3.6). For the purposes of overload resolution, the
2285 // parameter list is truncated on the right, so that there are
2286 // exactly m parameters.
2287 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002288 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002289 // Not enough arguments.
2290 Candidate.Viable = false;
2291 return;
2292 }
2293
2294 // Determine the implicit conversion sequences for each of the
2295 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002296 Candidate.Conversions.resize(NumArgs);
2297 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2298 if (ArgIdx < NumArgsInProto) {
2299 // (C++ 13.3.2p3): for F to be a viable function, there shall
2300 // exist for each argument an implicit conversion sequence
2301 // (13.3.3.1) that converts that argument to the corresponding
2302 // parameter of F.
2303 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002304 Candidate.Conversions[ArgIdx]
2305 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002306 SuppressUserConversions, ForceRValue,
2307 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002308 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002309 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002310 // 13.3.3.1-p10 If several different sequences of conversions exist that
2311 // each convert the argument to the parameter type, the implicit conversion
2312 // sequence associated with the parameter is defined to be the unique conversion
2313 // sequence designated the ambiguous conversion sequence. For the purpose of
2314 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2315 // conversion sequence is treated as a user-defined sequence that is
2316 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002317 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002318 Candidate.Conversions[ArgIdx].ConversionKind =
2319 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002320 // Set the conversion function to one of them. As due to ambiguity,
2321 // they carry the same weight and is needed for overload resolution
2322 // later.
2323 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2324 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2325 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002326 else {
2327 Candidate.Viable = false;
2328 break;
2329 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002330 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002331 } else {
2332 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2333 // argument for which there is no corresponding parameter is
2334 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002335 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002336 = ImplicitConversionSequence::EllipsisConversion;
2337 }
2338 }
2339}
2340
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002341/// \brief Add all of the function declarations in the given function set to
2342/// the overload canddiate set.
2343void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2344 Expr **Args, unsigned NumArgs,
2345 OverloadCandidateSet& CandidateSet,
2346 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002347 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002348 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002349 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002350 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2351 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2352 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2353 Args[0], Args + 1, NumArgs - 1,
2354 CandidateSet, SuppressUserConversions);
2355 else
2356 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2357 SuppressUserConversions);
2358 } else {
2359 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2360 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2361 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2362 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor89026b52009-06-30 23:57:56 +00002363 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002364 Args[0], Args + 1, NumArgs - 1,
2365 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002366 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002367 else
2368 AddTemplateOverloadCandidate(FunTmpl,
2369 /*FIXME: explicit args */false, 0, 0,
2370 Args, NumArgs, CandidateSet,
2371 SuppressUserConversions);
2372 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002373 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002374}
2375
John McCallf0f1cf02009-11-17 07:50:12 +00002376/// AddMethodCandidate - Adds a named decl (which is some kind of
2377/// method) as a method candidate to the given overload set.
2378void Sema::AddMethodCandidate(NamedDecl *Decl, Expr *Object,
2379 Expr **Args, unsigned NumArgs,
2380 OverloadCandidateSet& CandidateSet,
2381 bool SuppressUserConversions, bool ForceRValue) {
2382
2383 // FIXME: use this
2384 //DeclContext *ActingContext = Decl->getDeclContext();
2385
2386 if (isa<UsingShadowDecl>(Decl))
2387 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2388
2389 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2390 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2391 "Expected a member function template");
2392 AddMethodTemplateCandidate(TD, false, 0, 0,
2393 Object, Args, NumArgs,
2394 CandidateSet,
2395 SuppressUserConversions,
2396 ForceRValue);
2397 } else {
2398 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Object, Args, NumArgs,
2399 CandidateSet, SuppressUserConversions, ForceRValue);
2400 }
2401}
2402
Douglas Gregor436424c2008-11-18 23:14:02 +00002403/// AddMethodCandidate - Adds the given C++ member function to the set
2404/// of candidate functions, using the given function call arguments
2405/// and the object argument (@c Object). For example, in a call
2406/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2407/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2408/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002409/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2410/// a slightly hacky way to implement the overloading rules for elidable copy
2411/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002412void
Douglas Gregor436424c2008-11-18 23:14:02 +00002413Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2414 Expr **Args, unsigned NumArgs,
2415 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002416 bool SuppressUserConversions, bool ForceRValue) {
2417 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002418 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002419 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002420 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002421 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002422 assert(!isa<CXXConstructorDecl>(Method) &&
2423 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002424
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002425 if (!CandidateSet.isNewCandidate(Method))
2426 return;
2427
Douglas Gregor436424c2008-11-18 23:14:02 +00002428 // Add this candidate
2429 CandidateSet.push_back(OverloadCandidate());
2430 OverloadCandidate& Candidate = CandidateSet.back();
2431 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002432 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002433 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002434
2435 unsigned NumArgsInProto = Proto->getNumArgs();
2436
2437 // (C++ 13.3.2p2): A candidate function having fewer than m
2438 // parameters is viable only if it has an ellipsis in its parameter
2439 // list (8.3.5).
2440 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2441 Candidate.Viable = false;
2442 return;
2443 }
2444
2445 // (C++ 13.3.2p2): A candidate function having more than m parameters
2446 // is viable only if the (m+1)st parameter has a default argument
2447 // (8.3.6). For the purposes of overload resolution, the
2448 // parameter list is truncated on the right, so that there are
2449 // exactly m parameters.
2450 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2451 if (NumArgs < MinRequiredArgs) {
2452 // Not enough arguments.
2453 Candidate.Viable = false;
2454 return;
2455 }
2456
2457 Candidate.Viable = true;
2458 Candidate.Conversions.resize(NumArgs + 1);
2459
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002460 if (Method->isStatic() || !Object)
2461 // The implicit object argument is ignored.
2462 Candidate.IgnoreObjectArgument = true;
2463 else {
2464 // Determine the implicit conversion sequence for the object
2465 // parameter.
2466 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002467 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002468 == ImplicitConversionSequence::BadConversion) {
2469 Candidate.Viable = false;
2470 return;
2471 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002472 }
2473
2474 // Determine the implicit conversion sequences for each of the
2475 // arguments.
2476 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2477 if (ArgIdx < NumArgsInProto) {
2478 // (C++ 13.3.2p3): for F to be a viable function, there shall
2479 // exist for each argument an implicit conversion sequence
2480 // (13.3.3.1) that converts that argument to the corresponding
2481 // parameter of F.
2482 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002483 Candidate.Conversions[ArgIdx + 1]
2484 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002485 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002486 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002487 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002488 == ImplicitConversionSequence::BadConversion) {
2489 Candidate.Viable = false;
2490 break;
2491 }
2492 } else {
2493 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2494 // argument for which there is no corresponding parameter is
2495 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002496 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002497 = ImplicitConversionSequence::EllipsisConversion;
2498 }
2499 }
2500}
2501
Douglas Gregor97628d62009-08-21 00:16:32 +00002502/// \brief Add a C++ member function template as a candidate to the candidate
2503/// set, using template argument deduction to produce an appropriate member
2504/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002505void
Douglas Gregor97628d62009-08-21 00:16:32 +00002506Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2507 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002508 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002509 unsigned NumExplicitTemplateArgs,
2510 Expr *Object, Expr **Args, unsigned NumArgs,
2511 OverloadCandidateSet& CandidateSet,
2512 bool SuppressUserConversions,
2513 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002514 if (!CandidateSet.isNewCandidate(MethodTmpl))
2515 return;
2516
Douglas Gregor97628d62009-08-21 00:16:32 +00002517 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002518 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002519 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002520 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002521 // candidate functions in the usual way.113) A given name can refer to one
2522 // or more function templates and also to a set of overloaded non-template
2523 // functions. In such a case, the candidate functions generated from each
2524 // function template are combined with the set of non-template candidate
2525 // functions.
2526 TemplateDeductionInfo Info(Context);
2527 FunctionDecl *Specialization = 0;
2528 if (TemplateDeductionResult Result
2529 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2530 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2531 Args, NumArgs, Specialization, Info)) {
2532 // FIXME: Record what happened with template argument deduction, so
2533 // that we can give the user a beautiful diagnostic.
2534 (void)Result;
2535 return;
2536 }
Mike Stump11289f42009-09-09 15:08:12 +00002537
Douglas Gregor97628d62009-08-21 00:16:32 +00002538 // Add the function template specialization produced by template argument
2539 // deduction as a candidate.
2540 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002541 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002542 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002543 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002544 CandidateSet, SuppressUserConversions, ForceRValue);
2545}
2546
Douglas Gregor05155d82009-08-21 23:19:43 +00002547/// \brief Add a C++ function template specialization as a candidate
2548/// in the candidate set, using template argument deduction to produce
2549/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002550void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002551Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002552 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002553 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002554 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002555 Expr **Args, unsigned NumArgs,
2556 OverloadCandidateSet& CandidateSet,
2557 bool SuppressUserConversions,
2558 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002559 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2560 return;
2561
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002562 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002563 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002564 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002565 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002566 // candidate functions in the usual way.113) A given name can refer to one
2567 // or more function templates and also to a set of overloaded non-template
2568 // functions. In such a case, the candidate functions generated from each
2569 // function template are combined with the set of non-template candidate
2570 // functions.
2571 TemplateDeductionInfo Info(Context);
2572 FunctionDecl *Specialization = 0;
2573 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002574 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2575 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2576 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002577 // FIXME: Record what happened with template argument deduction, so
2578 // that we can give the user a beautiful diagnostic.
2579 (void)Result;
2580 return;
2581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002583 // Add the function template specialization produced by template argument
2584 // deduction as a candidate.
2585 assert(Specialization && "Missing function template specialization?");
2586 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2587 SuppressUserConversions, ForceRValue);
2588}
Mike Stump11289f42009-09-09 15:08:12 +00002589
Douglas Gregora1f013e2008-11-07 22:36:19 +00002590/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002591/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002592/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002593/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002594/// (which may or may not be the same type as the type that the
2595/// conversion function produces).
2596void
2597Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2598 Expr *From, QualType ToType,
2599 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002600 assert(!Conversion->getDescribedFunctionTemplate() &&
2601 "Conversion function templates use AddTemplateConversionCandidate");
2602
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002603 if (!CandidateSet.isNewCandidate(Conversion))
2604 return;
2605
Douglas Gregora1f013e2008-11-07 22:36:19 +00002606 // Add this candidate
2607 CandidateSet.push_back(OverloadCandidate());
2608 OverloadCandidate& Candidate = CandidateSet.back();
2609 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002610 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002611 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002612 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002613 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002614 = Conversion->getConversionType().getAsOpaquePtr();
2615 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2616
Douglas Gregor436424c2008-11-18 23:14:02 +00002617 // Determine the implicit conversion sequence for the implicit
2618 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002619 Candidate.Viable = true;
2620 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002621 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002622 // Conversion functions to a different type in the base class is visible in
2623 // the derived class. So, a derived to base conversion should not participate
2624 // in overload resolution.
2625 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2626 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002627 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002628 == ImplicitConversionSequence::BadConversion) {
2629 Candidate.Viable = false;
2630 return;
2631 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002632
2633 // We won't go through a user-define type conversion function to convert a
2634 // derived to base as such conversions are given Conversion Rank. They only
2635 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2636 QualType FromCanon
2637 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2638 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2639 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2640 Candidate.Viable = false;
2641 return;
2642 }
2643
Douglas Gregora1f013e2008-11-07 22:36:19 +00002644
2645 // To determine what the conversion from the result of calling the
2646 // conversion function to the type we're eventually trying to
2647 // convert to (ToType), we need to synthesize a call to the
2648 // conversion function and attempt copy initialization from it. This
2649 // makes sure that we get the right semantics with respect to
2650 // lvalues/rvalues and the type. Fortunately, we can allocate this
2651 // call on the stack and we don't need its arguments to be
2652 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002653 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002654 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002655 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002656 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002657 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002658
2659 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002660 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2661 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002662 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002663 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002664 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002665 ImplicitConversionSequence ICS =
2666 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002667 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002668 /*ForceRValue=*/false,
2669 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002670
Douglas Gregora1f013e2008-11-07 22:36:19 +00002671 switch (ICS.ConversionKind) {
2672 case ImplicitConversionSequence::StandardConversion:
2673 Candidate.FinalConversion = ICS.Standard;
2674 break;
2675
2676 case ImplicitConversionSequence::BadConversion:
2677 Candidate.Viable = false;
2678 break;
2679
2680 default:
Mike Stump11289f42009-09-09 15:08:12 +00002681 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002682 "Can only end up with a standard conversion sequence or failure");
2683 }
2684}
2685
Douglas Gregor05155d82009-08-21 23:19:43 +00002686/// \brief Adds a conversion function template specialization
2687/// candidate to the overload set, using template argument deduction
2688/// to deduce the template arguments of the conversion function
2689/// template from the type that we are converting to (C++
2690/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002691void
Douglas Gregor05155d82009-08-21 23:19:43 +00002692Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2693 Expr *From, QualType ToType,
2694 OverloadCandidateSet &CandidateSet) {
2695 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2696 "Only conversion function templates permitted here");
2697
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002698 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2699 return;
2700
Douglas Gregor05155d82009-08-21 23:19:43 +00002701 TemplateDeductionInfo Info(Context);
2702 CXXConversionDecl *Specialization = 0;
2703 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002704 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002705 Specialization, Info)) {
2706 // FIXME: Record what happened with template argument deduction, so
2707 // that we can give the user a beautiful diagnostic.
2708 (void)Result;
2709 return;
2710 }
Mike Stump11289f42009-09-09 15:08:12 +00002711
Douglas Gregor05155d82009-08-21 23:19:43 +00002712 // Add the conversion function template specialization produced by
2713 // template argument deduction as a candidate.
2714 assert(Specialization && "Missing function template specialization?");
2715 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2716}
2717
Douglas Gregorab7897a2008-11-19 22:57:39 +00002718/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2719/// converts the given @c Object to a function pointer via the
2720/// conversion function @c Conversion, and then attempts to call it
2721/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2722/// the type of function that we'll eventually be calling.
2723void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002724 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002725 Expr *Object, Expr **Args, unsigned NumArgs,
2726 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002727 if (!CandidateSet.isNewCandidate(Conversion))
2728 return;
2729
Douglas Gregorab7897a2008-11-19 22:57:39 +00002730 CandidateSet.push_back(OverloadCandidate());
2731 OverloadCandidate& Candidate = CandidateSet.back();
2732 Candidate.Function = 0;
2733 Candidate.Surrogate = Conversion;
2734 Candidate.Viable = true;
2735 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002736 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002737 Candidate.Conversions.resize(NumArgs + 1);
2738
2739 // Determine the implicit conversion sequence for the implicit
2740 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002741 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002742 = TryObjectArgumentInitialization(Object, Conversion);
2743 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2744 Candidate.Viable = false;
2745 return;
2746 }
2747
2748 // The first conversion is actually a user-defined conversion whose
2749 // first conversion is ObjectInit's standard conversion (which is
2750 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002751 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002752 = ImplicitConversionSequence::UserDefinedConversion;
2753 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002754 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002755 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002756 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002757 = Candidate.Conversions[0].UserDefined.Before;
2758 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2759
Mike Stump11289f42009-09-09 15:08:12 +00002760 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002761 unsigned NumArgsInProto = Proto->getNumArgs();
2762
2763 // (C++ 13.3.2p2): A candidate function having fewer than m
2764 // parameters is viable only if it has an ellipsis in its parameter
2765 // list (8.3.5).
2766 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2767 Candidate.Viable = false;
2768 return;
2769 }
2770
2771 // Function types don't have any default arguments, so just check if
2772 // we have enough arguments.
2773 if (NumArgs < NumArgsInProto) {
2774 // Not enough arguments.
2775 Candidate.Viable = false;
2776 return;
2777 }
2778
2779 // Determine the implicit conversion sequences for each of the
2780 // arguments.
2781 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2782 if (ArgIdx < NumArgsInProto) {
2783 // (C++ 13.3.2p3): for F to be a viable function, there shall
2784 // exist for each argument an implicit conversion sequence
2785 // (13.3.3.1) that converts that argument to the corresponding
2786 // parameter of F.
2787 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002788 Candidate.Conversions[ArgIdx + 1]
2789 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002790 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002791 /*ForceRValue=*/false,
2792 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002793 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002794 == ImplicitConversionSequence::BadConversion) {
2795 Candidate.Viable = false;
2796 break;
2797 }
2798 } else {
2799 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2800 // argument for which there is no corresponding parameter is
2801 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002802 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002803 = ImplicitConversionSequence::EllipsisConversion;
2804 }
2805 }
2806}
2807
Mike Stump87c57ac2009-05-16 07:39:55 +00002808// FIXME: This will eventually be removed, once we've migrated all of the
2809// operator overloading logic over to the scheme used by binary operators, which
2810// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002811void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002812 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002813 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002814 OverloadCandidateSet& CandidateSet,
2815 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002816 FunctionSet Functions;
2817
2818 QualType T1 = Args[0]->getType();
2819 QualType T2;
2820 if (NumArgs > 1)
2821 T2 = Args[1]->getType();
2822
2823 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002824 if (S)
2825 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002826 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002827 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2828 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002829 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002830}
2831
2832/// \brief Add overload candidates for overloaded operators that are
2833/// member functions.
2834///
2835/// Add the overloaded operator candidates that are member functions
2836/// for the operator Op that was used in an operator expression such
2837/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2838/// CandidateSet will store the added overload candidates. (C++
2839/// [over.match.oper]).
2840void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2841 SourceLocation OpLoc,
2842 Expr **Args, unsigned NumArgs,
2843 OverloadCandidateSet& CandidateSet,
2844 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002845 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2846
2847 // C++ [over.match.oper]p3:
2848 // For a unary operator @ with an operand of a type whose
2849 // cv-unqualified version is T1, and for a binary operator @ with
2850 // a left operand of a type whose cv-unqualified version is T1 and
2851 // a right operand of a type whose cv-unqualified version is T2,
2852 // three sets of candidate functions, designated member
2853 // candidates, non-member candidates and built-in candidates, are
2854 // constructed as follows:
2855 QualType T1 = Args[0]->getType();
2856 QualType T2;
2857 if (NumArgs > 1)
2858 T2 = Args[1]->getType();
2859
2860 // -- If T1 is a class type, the set of member candidates is the
2861 // result of the qualified lookup of T1::operator@
2862 // (13.3.1.1.1); otherwise, the set of member candidates is
2863 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002864 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002865 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002866 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002867 return;
Mike Stump11289f42009-09-09 15:08:12 +00002868
John McCall27b18f82009-11-17 02:14:36 +00002869 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2870 LookupQualifiedName(Operators, T1Rec->getDecl());
2871 Operators.suppressDiagnostics();
2872
Mike Stump11289f42009-09-09 15:08:12 +00002873 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002874 OperEnd = Operators.end();
2875 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002876 ++Oper)
2877 AddMethodCandidate(*Oper, Args[0], Args + 1, NumArgs - 1, CandidateSet,
2878 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002879 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002880}
2881
Douglas Gregora11693b2008-11-12 17:17:38 +00002882/// AddBuiltinCandidate - Add a candidate for a built-in
2883/// operator. ResultTy and ParamTys are the result and parameter types
2884/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002885/// arguments being passed to the candidate. IsAssignmentOperator
2886/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002887/// operator. NumContextualBoolArguments is the number of arguments
2888/// (at the beginning of the argument list) that will be contextually
2889/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002890void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002891 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002892 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002893 bool IsAssignmentOperator,
2894 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002895 // Add this candidate
2896 CandidateSet.push_back(OverloadCandidate());
2897 OverloadCandidate& Candidate = CandidateSet.back();
2898 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002899 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002900 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002901 Candidate.BuiltinTypes.ResultTy = ResultTy;
2902 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2903 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2904
2905 // Determine the implicit conversion sequences for each of the
2906 // arguments.
2907 Candidate.Viable = true;
2908 Candidate.Conversions.resize(NumArgs);
2909 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002910 // C++ [over.match.oper]p4:
2911 // For the built-in assignment operators, conversions of the
2912 // left operand are restricted as follows:
2913 // -- no temporaries are introduced to hold the left operand, and
2914 // -- no user-defined conversions are applied to the left
2915 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002916 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002917 //
2918 // We block these conversions by turning off user-defined
2919 // conversions, since that is the only way that initialization of
2920 // a reference to a non-class type can occur from something that
2921 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002922 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002923 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002924 "Contextual conversion to bool requires bool type");
2925 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2926 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002927 Candidate.Conversions[ArgIdx]
2928 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002929 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002930 /*ForceRValue=*/false,
2931 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002932 }
Mike Stump11289f42009-09-09 15:08:12 +00002933 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002934 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002935 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002936 break;
2937 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002938 }
2939}
2940
2941/// BuiltinCandidateTypeSet - A set of types that will be used for the
2942/// candidate operator functions for built-in operators (C++
2943/// [over.built]). The types are separated into pointer types and
2944/// enumeration types.
2945class BuiltinCandidateTypeSet {
2946 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002947 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002948
2949 /// PointerTypes - The set of pointer types that will be used in the
2950 /// built-in candidates.
2951 TypeSet PointerTypes;
2952
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002953 /// MemberPointerTypes - The set of member pointer types that will be
2954 /// used in the built-in candidates.
2955 TypeSet MemberPointerTypes;
2956
Douglas Gregora11693b2008-11-12 17:17:38 +00002957 /// EnumerationTypes - The set of enumeration types that will be
2958 /// used in the built-in candidates.
2959 TypeSet EnumerationTypes;
2960
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002961 /// Sema - The semantic analysis instance where we are building the
2962 /// candidate type set.
2963 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregora11693b2008-11-12 17:17:38 +00002965 /// Context - The AST context in which we will build the type sets.
2966 ASTContext &Context;
2967
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002968 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2969 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002970 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002971
2972public:
2973 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002974 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002975
Mike Stump11289f42009-09-09 15:08:12 +00002976 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002977 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002978
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002979 void AddTypesConvertedFrom(QualType Ty,
2980 SourceLocation Loc,
2981 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002982 bool AllowExplicitConversions,
2983 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002984
2985 /// pointer_begin - First pointer type found;
2986 iterator pointer_begin() { return PointerTypes.begin(); }
2987
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002988 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002989 iterator pointer_end() { return PointerTypes.end(); }
2990
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002991 /// member_pointer_begin - First member pointer type found;
2992 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2993
2994 /// member_pointer_end - Past the last member pointer type found;
2995 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2996
Douglas Gregora11693b2008-11-12 17:17:38 +00002997 /// enumeration_begin - First enumeration type found;
2998 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2999
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003000 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003001 iterator enumeration_end() { return EnumerationTypes.end(); }
3002};
3003
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003004/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003005/// the set of pointer types along with any more-qualified variants of
3006/// that type. For example, if @p Ty is "int const *", this routine
3007/// will add "int const *", "int const volatile *", "int const
3008/// restrict *", and "int const volatile restrict *" to the set of
3009/// pointer types. Returns true if the add of @p Ty itself succeeded,
3010/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003011///
3012/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003013bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003014BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3015 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003016
Douglas Gregora11693b2008-11-12 17:17:38 +00003017 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003018 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003019 return false;
3020
John McCall8ccfcb52009-09-24 19:53:00 +00003021 const PointerType *PointerTy = Ty->getAs<PointerType>();
3022 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003023
John McCall8ccfcb52009-09-24 19:53:00 +00003024 QualType PointeeTy = PointerTy->getPointeeType();
3025 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003026 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003027 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003028 bool hasVolatile = VisibleQuals.hasVolatile();
3029 bool hasRestrict = VisibleQuals.hasRestrict();
3030
John McCall8ccfcb52009-09-24 19:53:00 +00003031 // Iterate through all strict supersets of BaseCVR.
3032 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3033 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003034 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3035 // in the types.
3036 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3037 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003038 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3039 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003040 }
3041
3042 return true;
3043}
3044
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003045/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3046/// to the set of pointer types along with any more-qualified variants of
3047/// that type. For example, if @p Ty is "int const *", this routine
3048/// will add "int const *", "int const volatile *", "int const
3049/// restrict *", and "int const volatile restrict *" to the set of
3050/// pointer types. Returns true if the add of @p Ty itself succeeded,
3051/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003052///
3053/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003054bool
3055BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3056 QualType Ty) {
3057 // Insert this type.
3058 if (!MemberPointerTypes.insert(Ty))
3059 return false;
3060
John McCall8ccfcb52009-09-24 19:53:00 +00003061 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3062 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003063
John McCall8ccfcb52009-09-24 19:53:00 +00003064 QualType PointeeTy = PointerTy->getPointeeType();
3065 const Type *ClassTy = PointerTy->getClass();
3066
3067 // Iterate through all strict supersets of the pointee type's CVR
3068 // qualifiers.
3069 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3070 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3071 if ((CVR | BaseCVR) != CVR) continue;
3072
3073 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3074 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003075 }
3076
3077 return true;
3078}
3079
Douglas Gregora11693b2008-11-12 17:17:38 +00003080/// AddTypesConvertedFrom - Add each of the types to which the type @p
3081/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003082/// primarily interested in pointer types and enumeration types. We also
3083/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003084/// AllowUserConversions is true if we should look at the conversion
3085/// functions of a class type, and AllowExplicitConversions if we
3086/// should also include the explicit conversion functions of a class
3087/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003088void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003089BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003090 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003091 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003092 bool AllowExplicitConversions,
3093 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003094 // Only deal with canonical types.
3095 Ty = Context.getCanonicalType(Ty);
3096
3097 // Look through reference types; they aren't part of the type of an
3098 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003099 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003100 Ty = RefTy->getPointeeType();
3101
3102 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003103 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003104
Sebastian Redl65ae2002009-11-05 16:36:20 +00003105 // If we're dealing with an array type, decay to the pointer.
3106 if (Ty->isArrayType())
3107 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3108
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003109 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003110 QualType PointeeTy = PointerTy->getPointeeType();
3111
3112 // Insert our type, and its more-qualified variants, into the set
3113 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003114 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003115 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003116 } else if (Ty->isMemberPointerType()) {
3117 // Member pointers are far easier, since the pointee can't be converted.
3118 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3119 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003120 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003121 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003122 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003123 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003124 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003125 // No conversion functions in incomplete types.
3126 return;
3127 }
Mike Stump11289f42009-09-09 15:08:12 +00003128
Douglas Gregora11693b2008-11-12 17:17:38 +00003129 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003130 OverloadedFunctionDecl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003131 = ClassDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003132 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00003133 = Conversions->function_begin();
3134 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003135 CXXConversionDecl *Conv;
3136 FunctionTemplateDecl *ConvTemplate;
3137 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3138
Mike Stump11289f42009-09-09 15:08:12 +00003139 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003140 // about which builtin types we can convert to.
3141 if (ConvTemplate)
3142 continue;
3143
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003144 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003145 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003146 VisibleQuals);
3147 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003148 }
3149 }
3150 }
3151}
3152
Douglas Gregor84605ae2009-08-24 13:43:27 +00003153/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3154/// the volatile- and non-volatile-qualified assignment operators for the
3155/// given type to the candidate set.
3156static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3157 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003158 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003159 unsigned NumArgs,
3160 OverloadCandidateSet &CandidateSet) {
3161 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003162
Douglas Gregor84605ae2009-08-24 13:43:27 +00003163 // T& operator=(T&, T)
3164 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3165 ParamTypes[1] = T;
3166 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3167 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003168
Douglas Gregor84605ae2009-08-24 13:43:27 +00003169 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3170 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003171 ParamTypes[0]
3172 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003173 ParamTypes[1] = T;
3174 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003175 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003176 }
3177}
Mike Stump11289f42009-09-09 15:08:12 +00003178
Sebastian Redl1054fae2009-10-25 17:03:50 +00003179/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3180/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003181static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3182 Qualifiers VRQuals;
3183 const RecordType *TyRec;
3184 if (const MemberPointerType *RHSMPType =
3185 ArgExpr->getType()->getAs<MemberPointerType>())
3186 TyRec = cast<RecordType>(RHSMPType->getClass());
3187 else
3188 TyRec = ArgExpr->getType()->getAs<RecordType>();
3189 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003190 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003191 VRQuals.addVolatile();
3192 VRQuals.addRestrict();
3193 return VRQuals;
3194 }
3195
3196 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3197 OverloadedFunctionDecl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003198 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003199
3200 for (OverloadedFunctionDecl::function_iterator Func
3201 = Conversions->function_begin();
3202 Func != Conversions->function_end(); ++Func) {
3203 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3204 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3205 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3206 CanTy = ResTypeRef->getPointeeType();
3207 // Need to go down the pointer/mempointer chain and add qualifiers
3208 // as see them.
3209 bool done = false;
3210 while (!done) {
3211 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3212 CanTy = ResTypePtr->getPointeeType();
3213 else if (const MemberPointerType *ResTypeMPtr =
3214 CanTy->getAs<MemberPointerType>())
3215 CanTy = ResTypeMPtr->getPointeeType();
3216 else
3217 done = true;
3218 if (CanTy.isVolatileQualified())
3219 VRQuals.addVolatile();
3220 if (CanTy.isRestrictQualified())
3221 VRQuals.addRestrict();
3222 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3223 return VRQuals;
3224 }
3225 }
3226 }
3227 return VRQuals;
3228}
3229
Douglas Gregord08452f2008-11-19 15:42:04 +00003230/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3231/// operator overloads to the candidate set (C++ [over.built]), based
3232/// on the operator @p Op and the arguments given. For example, if the
3233/// operator is a binary '+', this routine might add "int
3234/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003235void
Mike Stump11289f42009-09-09 15:08:12 +00003236Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003237 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003238 Expr **Args, unsigned NumArgs,
3239 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003240 // The set of "promoted arithmetic types", which are the arithmetic
3241 // types are that preserved by promotion (C++ [over.built]p2). Note
3242 // that the first few of these types are the promoted integral
3243 // types; these types need to be first.
3244 // FIXME: What about complex?
3245 const unsigned FirstIntegralType = 0;
3246 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003247 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003248 LastPromotedIntegralType = 13;
3249 const unsigned FirstPromotedArithmeticType = 7,
3250 LastPromotedArithmeticType = 16;
3251 const unsigned NumArithmeticTypes = 16;
3252 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003253 Context.BoolTy, Context.CharTy, Context.WCharTy,
3254// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003255 Context.SignedCharTy, Context.ShortTy,
3256 Context.UnsignedCharTy, Context.UnsignedShortTy,
3257 Context.IntTy, Context.LongTy, Context.LongLongTy,
3258 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3259 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3260 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003261 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3262 "Invalid first promoted integral type");
3263 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3264 == Context.UnsignedLongLongTy &&
3265 "Invalid last promoted integral type");
3266 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3267 "Invalid first promoted arithmetic type");
3268 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3269 == Context.LongDoubleTy &&
3270 "Invalid last promoted arithmetic type");
3271
Douglas Gregora11693b2008-11-12 17:17:38 +00003272 // Find all of the types that the arguments can convert to, but only
3273 // if the operator we're looking at has built-in operator candidates
3274 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003275 Qualifiers VisibleTypeConversionsQuals;
3276 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003277 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3278 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3279
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003280 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003281 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3282 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003283 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003284 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003285 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003286 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003287 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003288 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003289 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003290 true,
3291 (Op == OO_Exclaim ||
3292 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003293 Op == OO_PipePipe),
3294 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003295 }
3296
3297 bool isComparison = false;
3298 switch (Op) {
3299 case OO_None:
3300 case NUM_OVERLOADED_OPERATORS:
3301 assert(false && "Expected an overloaded operator");
3302 break;
3303
Douglas Gregord08452f2008-11-19 15:42:04 +00003304 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003305 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003306 goto UnaryStar;
3307 else
3308 goto BinaryStar;
3309 break;
3310
3311 case OO_Plus: // '+' is either unary or binary
3312 if (NumArgs == 1)
3313 goto UnaryPlus;
3314 else
3315 goto BinaryPlus;
3316 break;
3317
3318 case OO_Minus: // '-' is either unary or binary
3319 if (NumArgs == 1)
3320 goto UnaryMinus;
3321 else
3322 goto BinaryMinus;
3323 break;
3324
3325 case OO_Amp: // '&' is either unary or binary
3326 if (NumArgs == 1)
3327 goto UnaryAmp;
3328 else
3329 goto BinaryAmp;
3330
3331 case OO_PlusPlus:
3332 case OO_MinusMinus:
3333 // C++ [over.built]p3:
3334 //
3335 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3336 // is either volatile or empty, there exist candidate operator
3337 // functions of the form
3338 //
3339 // VQ T& operator++(VQ T&);
3340 // T operator++(VQ T&, int);
3341 //
3342 // C++ [over.built]p4:
3343 //
3344 // For every pair (T, VQ), where T is an arithmetic type other
3345 // than bool, and VQ is either volatile or empty, there exist
3346 // candidate operator functions of the form
3347 //
3348 // VQ T& operator--(VQ T&);
3349 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003350 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003351 Arith < NumArithmeticTypes; ++Arith) {
3352 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003353 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003354 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003355
3356 // Non-volatile version.
3357 if (NumArgs == 1)
3358 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3359 else
3360 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003361 // heuristic to reduce number of builtin candidates in the set.
3362 // Add volatile version only if there are conversions to a volatile type.
3363 if (VisibleTypeConversionsQuals.hasVolatile()) {
3364 // Volatile version
3365 ParamTypes[0]
3366 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3367 if (NumArgs == 1)
3368 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3369 else
3370 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3371 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003372 }
3373
3374 // C++ [over.built]p5:
3375 //
3376 // For every pair (T, VQ), where T is a cv-qualified or
3377 // cv-unqualified object type, and VQ is either volatile or
3378 // empty, there exist candidate operator functions of the form
3379 //
3380 // T*VQ& operator++(T*VQ&);
3381 // T*VQ& operator--(T*VQ&);
3382 // T* operator++(T*VQ&, int);
3383 // T* operator--(T*VQ&, int);
3384 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3385 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3386 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003387 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003388 continue;
3389
Mike Stump11289f42009-09-09 15:08:12 +00003390 QualType ParamTypes[2] = {
3391 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003392 };
Mike Stump11289f42009-09-09 15:08:12 +00003393
Douglas Gregord08452f2008-11-19 15:42:04 +00003394 // Without volatile
3395 if (NumArgs == 1)
3396 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3397 else
3398 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3399
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003400 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3401 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003402 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003403 ParamTypes[0]
3404 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003405 if (NumArgs == 1)
3406 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3407 else
3408 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3409 }
3410 }
3411 break;
3412
3413 UnaryStar:
3414 // C++ [over.built]p6:
3415 // For every cv-qualified or cv-unqualified object type T, there
3416 // exist candidate operator functions of the form
3417 //
3418 // T& operator*(T*);
3419 //
3420 // C++ [over.built]p7:
3421 // For every function type T, there exist candidate operator
3422 // functions of the form
3423 // T& operator*(T*);
3424 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3425 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3426 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003427 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003428 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003429 &ParamTy, Args, 1, CandidateSet);
3430 }
3431 break;
3432
3433 UnaryPlus:
3434 // C++ [over.built]p8:
3435 // For every type T, there exist candidate operator functions of
3436 // the form
3437 //
3438 // T* operator+(T*);
3439 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3440 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3441 QualType ParamTy = *Ptr;
3442 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3443 }
Mike Stump11289f42009-09-09 15:08:12 +00003444
Douglas Gregord08452f2008-11-19 15:42:04 +00003445 // Fall through
3446
3447 UnaryMinus:
3448 // C++ [over.built]p9:
3449 // For every promoted arithmetic type T, there exist candidate
3450 // operator functions of the form
3451 //
3452 // T operator+(T);
3453 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003454 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003455 Arith < LastPromotedArithmeticType; ++Arith) {
3456 QualType ArithTy = ArithmeticTypes[Arith];
3457 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3458 }
3459 break;
3460
3461 case OO_Tilde:
3462 // C++ [over.built]p10:
3463 // For every promoted integral type T, there exist candidate
3464 // operator functions of the form
3465 //
3466 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003467 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003468 Int < LastPromotedIntegralType; ++Int) {
3469 QualType IntTy = ArithmeticTypes[Int];
3470 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3471 }
3472 break;
3473
Douglas Gregora11693b2008-11-12 17:17:38 +00003474 case OO_New:
3475 case OO_Delete:
3476 case OO_Array_New:
3477 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003478 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003479 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003480 break;
3481
3482 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003483 UnaryAmp:
3484 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003485 // C++ [over.match.oper]p3:
3486 // -- For the operator ',', the unary operator '&', or the
3487 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003488 break;
3489
Douglas Gregor84605ae2009-08-24 13:43:27 +00003490 case OO_EqualEqual:
3491 case OO_ExclaimEqual:
3492 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003493 // For every pointer to member type T, there exist candidate operator
3494 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003495 //
3496 // bool operator==(T,T);
3497 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003498 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003499 MemPtr = CandidateTypes.member_pointer_begin(),
3500 MemPtrEnd = CandidateTypes.member_pointer_end();
3501 MemPtr != MemPtrEnd;
3502 ++MemPtr) {
3503 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3504 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3505 }
Mike Stump11289f42009-09-09 15:08:12 +00003506
Douglas Gregor84605ae2009-08-24 13:43:27 +00003507 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003508
Douglas Gregora11693b2008-11-12 17:17:38 +00003509 case OO_Less:
3510 case OO_Greater:
3511 case OO_LessEqual:
3512 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003513 // C++ [over.built]p15:
3514 //
3515 // For every pointer or enumeration type T, there exist
3516 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003517 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003518 // bool operator<(T, T);
3519 // bool operator>(T, T);
3520 // bool operator<=(T, T);
3521 // bool operator>=(T, T);
3522 // bool operator==(T, T);
3523 // bool operator!=(T, T);
3524 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3525 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3526 QualType ParamTypes[2] = { *Ptr, *Ptr };
3527 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3528 }
Mike Stump11289f42009-09-09 15:08:12 +00003529 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003530 = CandidateTypes.enumeration_begin();
3531 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3532 QualType ParamTypes[2] = { *Enum, *Enum };
3533 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3534 }
3535
3536 // Fall through.
3537 isComparison = true;
3538
Douglas Gregord08452f2008-11-19 15:42:04 +00003539 BinaryPlus:
3540 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003541 if (!isComparison) {
3542 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3543
3544 // C++ [over.built]p13:
3545 //
3546 // For every cv-qualified or cv-unqualified object type T
3547 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003548 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003549 // T* operator+(T*, ptrdiff_t);
3550 // T& operator[](T*, ptrdiff_t); [BELOW]
3551 // T* operator-(T*, ptrdiff_t);
3552 // T* operator+(ptrdiff_t, T*);
3553 // T& operator[](ptrdiff_t, T*); [BELOW]
3554 //
3555 // C++ [over.built]p14:
3556 //
3557 // For every T, where T is a pointer to object type, there
3558 // exist candidate operator functions of the form
3559 //
3560 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003561 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003562 = CandidateTypes.pointer_begin();
3563 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3564 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3565
3566 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3567 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3568
3569 if (Op == OO_Plus) {
3570 // T* operator+(ptrdiff_t, T*);
3571 ParamTypes[0] = ParamTypes[1];
3572 ParamTypes[1] = *Ptr;
3573 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3574 } else {
3575 // ptrdiff_t operator-(T, T);
3576 ParamTypes[1] = *Ptr;
3577 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3578 Args, 2, CandidateSet);
3579 }
3580 }
3581 }
3582 // Fall through
3583
Douglas Gregora11693b2008-11-12 17:17:38 +00003584 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003585 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003586 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003587 // C++ [over.built]p12:
3588 //
3589 // For every pair of promoted arithmetic types L and R, there
3590 // exist candidate operator functions of the form
3591 //
3592 // LR operator*(L, R);
3593 // LR operator/(L, R);
3594 // LR operator+(L, R);
3595 // LR operator-(L, R);
3596 // bool operator<(L, R);
3597 // bool operator>(L, R);
3598 // bool operator<=(L, R);
3599 // bool operator>=(L, R);
3600 // bool operator==(L, R);
3601 // bool operator!=(L, R);
3602 //
3603 // where LR is the result of the usual arithmetic conversions
3604 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003605 //
3606 // C++ [over.built]p24:
3607 //
3608 // For every pair of promoted arithmetic types L and R, there exist
3609 // candidate operator functions of the form
3610 //
3611 // LR operator?(bool, L, R);
3612 //
3613 // where LR is the result of the usual arithmetic conversions
3614 // between types L and R.
3615 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003616 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003617 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003618 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003619 Right < LastPromotedArithmeticType; ++Right) {
3620 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003621 QualType Result
3622 = isComparison
3623 ? Context.BoolTy
3624 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003625 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3626 }
3627 }
3628 break;
3629
3630 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003631 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003632 case OO_Caret:
3633 case OO_Pipe:
3634 case OO_LessLess:
3635 case OO_GreaterGreater:
3636 // C++ [over.built]p17:
3637 //
3638 // For every pair of promoted integral types L and R, there
3639 // exist candidate operator functions of the form
3640 //
3641 // LR operator%(L, R);
3642 // LR operator&(L, R);
3643 // LR operator^(L, R);
3644 // LR operator|(L, R);
3645 // L operator<<(L, R);
3646 // L operator>>(L, R);
3647 //
3648 // where LR is the result of the usual arithmetic conversions
3649 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003650 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003651 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003652 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003653 Right < LastPromotedIntegralType; ++Right) {
3654 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3655 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3656 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003657 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003658 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3659 }
3660 }
3661 break;
3662
3663 case OO_Equal:
3664 // C++ [over.built]p20:
3665 //
3666 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003667 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003668 // empty, there exist candidate operator functions of the form
3669 //
3670 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003671 for (BuiltinCandidateTypeSet::iterator
3672 Enum = CandidateTypes.enumeration_begin(),
3673 EnumEnd = CandidateTypes.enumeration_end();
3674 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003675 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003676 CandidateSet);
3677 for (BuiltinCandidateTypeSet::iterator
3678 MemPtr = CandidateTypes.member_pointer_begin(),
3679 MemPtrEnd = CandidateTypes.member_pointer_end();
3680 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003681 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003682 CandidateSet);
3683 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003684
3685 case OO_PlusEqual:
3686 case OO_MinusEqual:
3687 // C++ [over.built]p19:
3688 //
3689 // For every pair (T, VQ), where T is any type and VQ is either
3690 // volatile or empty, there exist candidate operator functions
3691 // of the form
3692 //
3693 // T*VQ& operator=(T*VQ&, T*);
3694 //
3695 // C++ [over.built]p21:
3696 //
3697 // For every pair (T, VQ), where T is a cv-qualified or
3698 // cv-unqualified object type and VQ is either volatile or
3699 // empty, there exist candidate operator functions of the form
3700 //
3701 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3702 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3703 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3704 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3705 QualType ParamTypes[2];
3706 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3707
3708 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003709 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003710 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3711 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003712
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003713 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3714 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003715 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003716 ParamTypes[0]
3717 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003718 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3719 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003720 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003721 }
3722 // Fall through.
3723
3724 case OO_StarEqual:
3725 case OO_SlashEqual:
3726 // C++ [over.built]p18:
3727 //
3728 // For every triple (L, VQ, R), where L is an arithmetic type,
3729 // VQ is either volatile or empty, and R is a promoted
3730 // arithmetic type, there exist candidate operator functions of
3731 // the form
3732 //
3733 // VQ L& operator=(VQ L&, R);
3734 // VQ L& operator*=(VQ L&, R);
3735 // VQ L& operator/=(VQ L&, R);
3736 // VQ L& operator+=(VQ L&, R);
3737 // VQ L& operator-=(VQ L&, R);
3738 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003739 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003740 Right < LastPromotedArithmeticType; ++Right) {
3741 QualType ParamTypes[2];
3742 ParamTypes[1] = ArithmeticTypes[Right];
3743
3744 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003745 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003746 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3747 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003748
3749 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003750 if (VisibleTypeConversionsQuals.hasVolatile()) {
3751 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3752 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3753 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3754 /*IsAssigmentOperator=*/Op == OO_Equal);
3755 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003756 }
3757 }
3758 break;
3759
3760 case OO_PercentEqual:
3761 case OO_LessLessEqual:
3762 case OO_GreaterGreaterEqual:
3763 case OO_AmpEqual:
3764 case OO_CaretEqual:
3765 case OO_PipeEqual:
3766 // C++ [over.built]p22:
3767 //
3768 // For every triple (L, VQ, R), where L is an integral type, VQ
3769 // is either volatile or empty, and R is a promoted integral
3770 // type, there exist candidate operator functions of the form
3771 //
3772 // VQ L& operator%=(VQ L&, R);
3773 // VQ L& operator<<=(VQ L&, R);
3774 // VQ L& operator>>=(VQ L&, R);
3775 // VQ L& operator&=(VQ L&, R);
3776 // VQ L& operator^=(VQ L&, R);
3777 // VQ L& operator|=(VQ L&, R);
3778 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003779 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003780 Right < LastPromotedIntegralType; ++Right) {
3781 QualType ParamTypes[2];
3782 ParamTypes[1] = ArithmeticTypes[Right];
3783
3784 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003785 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003786 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003787 if (VisibleTypeConversionsQuals.hasVolatile()) {
3788 // Add this built-in operator as a candidate (VQ is 'volatile').
3789 ParamTypes[0] = ArithmeticTypes[Left];
3790 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3791 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3792 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3793 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003794 }
3795 }
3796 break;
3797
Douglas Gregord08452f2008-11-19 15:42:04 +00003798 case OO_Exclaim: {
3799 // C++ [over.operator]p23:
3800 //
3801 // There also exist candidate operator functions of the form
3802 //
Mike Stump11289f42009-09-09 15:08:12 +00003803 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003804 // bool operator&&(bool, bool); [BELOW]
3805 // bool operator||(bool, bool); [BELOW]
3806 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003807 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3808 /*IsAssignmentOperator=*/false,
3809 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003810 break;
3811 }
3812
Douglas Gregora11693b2008-11-12 17:17:38 +00003813 case OO_AmpAmp:
3814 case OO_PipePipe: {
3815 // C++ [over.operator]p23:
3816 //
3817 // There also exist candidate operator functions of the form
3818 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003819 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003820 // bool operator&&(bool, bool);
3821 // bool operator||(bool, bool);
3822 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003823 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3824 /*IsAssignmentOperator=*/false,
3825 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003826 break;
3827 }
3828
3829 case OO_Subscript:
3830 // C++ [over.built]p13:
3831 //
3832 // For every cv-qualified or cv-unqualified object type T there
3833 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003834 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003835 // T* operator+(T*, ptrdiff_t); [ABOVE]
3836 // T& operator[](T*, ptrdiff_t);
3837 // T* operator-(T*, ptrdiff_t); [ABOVE]
3838 // T* operator+(ptrdiff_t, T*); [ABOVE]
3839 // T& operator[](ptrdiff_t, T*);
3840 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3841 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3842 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003843 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003844 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003845
3846 // T& operator[](T*, ptrdiff_t)
3847 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3848
3849 // T& operator[](ptrdiff_t, T*);
3850 ParamTypes[0] = ParamTypes[1];
3851 ParamTypes[1] = *Ptr;
3852 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3853 }
3854 break;
3855
3856 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003857 // C++ [over.built]p11:
3858 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3859 // C1 is the same type as C2 or is a derived class of C2, T is an object
3860 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3861 // there exist candidate operator functions of the form
3862 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3863 // where CV12 is the union of CV1 and CV2.
3864 {
3865 for (BuiltinCandidateTypeSet::iterator Ptr =
3866 CandidateTypes.pointer_begin();
3867 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3868 QualType C1Ty = (*Ptr);
3869 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003870 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003871 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003872 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003873 if (!isa<RecordType>(C1))
3874 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003875 // heuristic to reduce number of builtin candidates in the set.
3876 // Add volatile/restrict version only if there are conversions to a
3877 // volatile/restrict type.
3878 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3879 continue;
3880 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3881 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003882 }
3883 for (BuiltinCandidateTypeSet::iterator
3884 MemPtr = CandidateTypes.member_pointer_begin(),
3885 MemPtrEnd = CandidateTypes.member_pointer_end();
3886 MemPtr != MemPtrEnd; ++MemPtr) {
3887 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3888 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003889 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003890 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3891 break;
3892 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3893 // build CV12 T&
3894 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003895 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3896 T.isVolatileQualified())
3897 continue;
3898 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3899 T.isRestrictQualified())
3900 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003901 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003902 QualType ResultTy = Context.getLValueReferenceType(T);
3903 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3904 }
3905 }
3906 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003907 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003908
3909 case OO_Conditional:
3910 // Note that we don't consider the first argument, since it has been
3911 // contextually converted to bool long ago. The candidates below are
3912 // therefore added as binary.
3913 //
3914 // C++ [over.built]p24:
3915 // For every type T, where T is a pointer or pointer-to-member type,
3916 // there exist candidate operator functions of the form
3917 //
3918 // T operator?(bool, T, T);
3919 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003920 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3921 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3922 QualType ParamTypes[2] = { *Ptr, *Ptr };
3923 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3924 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003925 for (BuiltinCandidateTypeSet::iterator Ptr =
3926 CandidateTypes.member_pointer_begin(),
3927 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3928 QualType ParamTypes[2] = { *Ptr, *Ptr };
3929 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3930 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003931 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003932 }
3933}
3934
Douglas Gregore254f902009-02-04 00:32:51 +00003935/// \brief Add function candidates found via argument-dependent lookup
3936/// to the set of overloading candidates.
3937///
3938/// This routine performs argument-dependent name lookup based on the
3939/// given function name (which may also be an operator name) and adds
3940/// all of the overload candidates found by ADL to the overload
3941/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003942void
Douglas Gregore254f902009-02-04 00:32:51 +00003943Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3944 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003945 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00003946 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003947 unsigned NumExplicitTemplateArgs,
3948 OverloadCandidateSet& CandidateSet,
3949 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003950 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003951
Douglas Gregorcabea402009-09-22 15:41:20 +00003952 // FIXME: Should we be trafficking in canonical function decls throughout?
3953
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003954 // Record all of the function candidates that we've already
3955 // added to the overload set, so that we don't add those same
3956 // candidates a second time.
3957 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3958 CandEnd = CandidateSet.end();
3959 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003960 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003961 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003962 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3963 Functions.insert(FunTmpl);
3964 }
Douglas Gregore254f902009-02-04 00:32:51 +00003965
Douglas Gregorcabea402009-09-22 15:41:20 +00003966 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00003967 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003968
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003969 // Erase all of the candidates we already knew about.
3970 // FIXME: This is suboptimal. Is there a better way?
3971 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3972 CandEnd = CandidateSet.end();
3973 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003974 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003975 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003976 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3977 Functions.erase(FunTmpl);
3978 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003979
3980 // For each of the ADL candidates we found, add it to the overload
3981 // set.
3982 for (FunctionSet::iterator Func = Functions.begin(),
3983 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003984 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003985 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3986 if (HasExplicitTemplateArgs)
3987 continue;
3988
3989 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3990 false, false, PartialOverloading);
3991 } else
Mike Stump11289f42009-09-09 15:08:12 +00003992 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003993 HasExplicitTemplateArgs,
3994 ExplicitTemplateArgs,
3995 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003996 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003997 }
Douglas Gregore254f902009-02-04 00:32:51 +00003998}
3999
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004000/// isBetterOverloadCandidate - Determines whether the first overload
4001/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004002bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004003Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004004 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004005 // Define viable functions to be better candidates than non-viable
4006 // functions.
4007 if (!Cand2.Viable)
4008 return Cand1.Viable;
4009 else if (!Cand1.Viable)
4010 return false;
4011
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004012 // C++ [over.match.best]p1:
4013 //
4014 // -- if F is a static member function, ICS1(F) is defined such
4015 // that ICS1(F) is neither better nor worse than ICS1(G) for
4016 // any function G, and, symmetrically, ICS1(G) is neither
4017 // better nor worse than ICS1(F).
4018 unsigned StartArg = 0;
4019 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4020 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004021
Douglas Gregord3cb3562009-07-07 23:38:56 +00004022 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004023 // A viable function F1 is defined to be a better function than another
4024 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004025 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004026 unsigned NumArgs = Cand1.Conversions.size();
4027 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4028 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004029 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004030 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4031 Cand2.Conversions[ArgIdx])) {
4032 case ImplicitConversionSequence::Better:
4033 // Cand1 has a better conversion sequence.
4034 HasBetterConversion = true;
4035 break;
4036
4037 case ImplicitConversionSequence::Worse:
4038 // Cand1 can't be better than Cand2.
4039 return false;
4040
4041 case ImplicitConversionSequence::Indistinguishable:
4042 // Do nothing.
4043 break;
4044 }
4045 }
4046
Mike Stump11289f42009-09-09 15:08:12 +00004047 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004048 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004049 if (HasBetterConversion)
4050 return true;
4051
Mike Stump11289f42009-09-09 15:08:12 +00004052 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004053 // specialization, or, if not that,
4054 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4055 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4056 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004057
4058 // -- F1 and F2 are function template specializations, and the function
4059 // template for F1 is more specialized than the template for F2
4060 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004061 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004062 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4063 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004064 if (FunctionTemplateDecl *BetterTemplate
4065 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4066 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004067 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4068 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004069 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004070
Douglas Gregora1f013e2008-11-07 22:36:19 +00004071 // -- the context is an initialization by user-defined conversion
4072 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4073 // from the return type of F1 to the destination type (i.e.,
4074 // the type of the entity being initialized) is a better
4075 // conversion sequence than the standard conversion sequence
4076 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004077 if (Cand1.Function && Cand2.Function &&
4078 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004079 isa<CXXConversionDecl>(Cand2.Function)) {
4080 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4081 Cand2.FinalConversion)) {
4082 case ImplicitConversionSequence::Better:
4083 // Cand1 has a better conversion sequence.
4084 return true;
4085
4086 case ImplicitConversionSequence::Worse:
4087 // Cand1 can't be better than Cand2.
4088 return false;
4089
4090 case ImplicitConversionSequence::Indistinguishable:
4091 // Do nothing
4092 break;
4093 }
4094 }
4095
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004096 return false;
4097}
4098
Mike Stump11289f42009-09-09 15:08:12 +00004099/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004100/// within an overload candidate set.
4101///
4102/// \param CandidateSet the set of candidate functions.
4103///
4104/// \param Loc the location of the function name (or operator symbol) for
4105/// which overload resolution occurs.
4106///
Mike Stump11289f42009-09-09 15:08:12 +00004107/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004108/// function, Best points to the candidate function found.
4109///
4110/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004111Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004112Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004113 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004114 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004115 // Find the best viable function.
4116 Best = CandidateSet.end();
4117 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4118 Cand != CandidateSet.end(); ++Cand) {
4119 if (Cand->Viable) {
4120 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4121 Best = Cand;
4122 }
4123 }
4124
4125 // If we didn't find any viable functions, abort.
4126 if (Best == CandidateSet.end())
4127 return OR_No_Viable_Function;
4128
4129 // Make sure that this function is better than every other viable
4130 // function. If not, we have an ambiguity.
4131 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4132 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004133 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004134 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004135 !isBetterOverloadCandidate(*Best, *Cand)) {
4136 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004137 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004138 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004139 }
Mike Stump11289f42009-09-09 15:08:12 +00004140
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004141 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004142 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004143 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004144 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004145 return OR_Deleted;
4146
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004147 // C++ [basic.def.odr]p2:
4148 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004149 // when referred to from a potentially-evaluated expression. [Note: this
4150 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004151 // (clause 13), user-defined conversions (12.3.2), allocation function for
4152 // placement new (5.3.4), as well as non-default initialization (8.5).
4153 if (Best->Function)
4154 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004155 return OR_Success;
4156}
4157
4158/// PrintOverloadCandidates - When overload resolution fails, prints
4159/// diagnostic messages containing the candidates in the candidate
4160/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004161void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004162Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004163 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004164 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004165 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004166 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4167 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004168 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004169 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004170 if (Cand->Viable || !OnlyViable) {
4171 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004172 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004173 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004174 // Deleted or "unavailable" function.
4175 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4176 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004177 } else if (FunctionTemplateDecl *FunTmpl
4178 = Cand->Function->getPrimaryTemplate()) {
4179 // Function template specialization
4180 // FIXME: Give a better reason!
4181 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4182 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4183 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004184 } else {
4185 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004186 bool errReported = false;
4187 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4188 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4189 const ImplicitConversionSequence &Conversion =
4190 Cand->Conversions[i];
4191 if ((Conversion.ConversionKind !=
4192 ImplicitConversionSequence::BadConversion) ||
4193 Conversion.ConversionFunctionSet.size() == 0)
4194 continue;
4195 Diag(Cand->Function->getLocation(),
4196 diag::err_ovl_candidate_not_viable) << (i+1);
4197 errReported = true;
4198 for (int j = Conversion.ConversionFunctionSet.size()-1;
4199 j >= 0; j--) {
4200 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4201 Diag(Func->getLocation(), diag::err_ovl_candidate);
4202 }
4203 }
4204 }
4205 if (!errReported)
4206 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004207 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004208 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004209 // Desugar the type of the surrogate down to a function type,
4210 // retaining as many typedefs as possible while still showing
4211 // the function type (and, therefore, its parameter types).
4212 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004213 bool isLValueReference = false;
4214 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004215 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004216 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004217 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004218 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004219 isLValueReference = true;
4220 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004221 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004222 FnType = FnTypeRef->getPointeeType();
4223 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004224 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004225 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004226 FnType = FnTypePtr->getPointeeType();
4227 isPointer = true;
4228 }
4229 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004230 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004231 // Reconstruct the pointer/reference as appropriate.
4232 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004233 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4234 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004235
Douglas Gregorab7897a2008-11-19 22:57:39 +00004236 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004237 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004238 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004239 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004240 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004241 std::string TypeStr("operator");
4242 TypeStr += Opc;
4243 TypeStr += "(";
4244 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4245 if (Cand->Conversions.size() == 1) {
4246 TypeStr += ")";
4247 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4248 }
4249 else {
4250 TypeStr += ", ";
4251 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4252 TypeStr += ")";
4253 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4254 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004255 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004256 else if (!Cand->Viable && !Reported) {
4257 // Non-viability might be due to ambiguous user-defined conversions,
4258 // needed for built-in operators. Report them as well, but only once
4259 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004260 unsigned NoOperands = Cand->Conversions.size();
4261 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004262 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4263 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4264 ICS.ConversionFunctionSet.empty())
4265 continue;
4266 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4267 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4268 QualType FromTy =
4269 QualType(
4270 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4271 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4272 << FromTy << Func->getConversionType();
4273 }
4274 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4275 FunctionDecl *Func =
4276 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4277 Diag(Func->getLocation(),diag::err_ovl_candidate);
4278 }
4279 }
4280 Reported = true;
4281 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004282 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004283 }
4284}
4285
Douglas Gregorcd695e52008-11-10 20:40:00 +00004286/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4287/// an overloaded function (C++ [over.over]), where @p From is an
4288/// expression with overloaded function type and @p ToType is the type
4289/// we're trying to resolve to. For example:
4290///
4291/// @code
4292/// int f(double);
4293/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004294///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004295/// int (*pfd)(double) = f; // selects f(double)
4296/// @endcode
4297///
4298/// This routine returns the resulting FunctionDecl if it could be
4299/// resolved, and NULL otherwise. When @p Complain is true, this
4300/// routine will emit diagnostics if there is an error.
4301FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004302Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004303 bool Complain) {
4304 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004305 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004306 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004307 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004308 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004309 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004310 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004311 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004312 FunctionType = MemTypePtr->getPointeeType();
4313 IsMember = true;
4314 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004315
4316 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004317 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004318 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004319 return 0;
4320
4321 // Find the actual overloaded function declaration.
4322 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004323
Douglas Gregorcd695e52008-11-10 20:40:00 +00004324 // C++ [over.over]p1:
4325 // [...] [Note: any redundant set of parentheses surrounding the
4326 // overloaded function name is ignored (5.1). ]
4327 Expr *OvlExpr = From->IgnoreParens();
4328
4329 // C++ [over.over]p1:
4330 // [...] The overloaded function name can be preceded by the &
4331 // operator.
4332 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4333 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4334 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4335 }
4336
Anders Carlssonb68b0282009-10-20 22:53:47 +00004337 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004338 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004339 unsigned NumExplicitTemplateArgs = 0;
4340
Douglas Gregorcd695e52008-11-10 20:40:00 +00004341 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004342 FunctionTemplateDecl *FunctionTemplate = 0;
4343 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004344 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004345 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004346 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4347 ExplicitTemplateArgs = DR->getTemplateArgs();
4348 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
Anders Carlsson6c966c42009-10-07 22:26:29 +00004349 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4350 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4351 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004352 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4353 ExplicitTemplateArgs = ME->getTemplateArgs();
4354 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
Anders Carlssonb68b0282009-10-20 22:53:47 +00004355 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4356 TemplateName Name = TIRE->getTemplateName();
4357 Ovl = Name.getAsOverloadedFunctionDecl();
4358 FunctionTemplate =
4359 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4360
4361 HasExplicitTemplateArgs = true;
4362 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4363 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
Douglas Gregor9b146582009-07-08 20:55:45 +00004364 }
Anders Carlssonb68b0282009-10-20 22:53:47 +00004365
Mike Stump11289f42009-09-09 15:08:12 +00004366 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004367 // we're done.
4368 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004369 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004370
Douglas Gregor9b146582009-07-08 20:55:45 +00004371 OverloadIterator Fun;
4372 if (Ovl)
4373 Fun = Ovl;
4374 else
4375 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004376
Douglas Gregorcd695e52008-11-10 20:40:00 +00004377 // Look through all of the overloaded functions, searching for one
4378 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004379 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004380 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004381 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004382 // C++ [over.over]p3:
4383 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004384 // targets of type "pointer-to-function" or "reference-to-function."
4385 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004386 // type "pointer-to-member-function."
4387 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004388
Mike Stump11289f42009-09-09 15:08:12 +00004389 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004390 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004391 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004392 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004393 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004394 // static when converting to member pointer.
4395 if (Method->isStatic() == IsMember)
4396 continue;
4397 } else if (IsMember)
4398 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004399
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004400 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004401 // If the name is a function template, template argument deduction is
4402 // done (14.8.2.2), and if the argument deduction succeeds, the
4403 // resulting template argument list is used to generate a single
4404 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004405 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004406 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004407 FunctionDecl *Specialization = 0;
4408 TemplateDeductionInfo Info(Context);
4409 if (TemplateDeductionResult Result
Anders Carlssonb68b0282009-10-20 22:53:47 +00004410 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4411 ExplicitTemplateArgs,
4412 NumExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00004413 FunctionType, Specialization, Info)) {
4414 // FIXME: make a note of the failed deduction for diagnostics.
4415 (void)Result;
4416 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004417 // FIXME: If the match isn't exact, shouldn't we just drop this as
4418 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004419 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004420 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004421 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004422 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004423 }
4424 }
Mike Stump11289f42009-09-09 15:08:12 +00004425
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004426 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4427 // Skip non-static functions when converting to pointer, and static
4428 // when converting to member pointer.
4429 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004430 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004431
4432 // If we have explicit template arguments, skip non-templates.
4433 if (HasExplicitTemplateArgs)
4434 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004435 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004436 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004437
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004438 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004439 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004440 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004441 FoundNonTemplateFunction = true;
4442 }
Mike Stump11289f42009-09-09 15:08:12 +00004443 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004444 }
4445
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004446 // If there were 0 or 1 matches, we're done.
4447 if (Matches.empty())
4448 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004449 else if (Matches.size() == 1) {
4450 FunctionDecl *Result = *Matches.begin();
4451 MarkDeclarationReferenced(From->getLocStart(), Result);
4452 return Result;
4453 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004454
4455 // C++ [over.over]p4:
4456 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004457 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004458 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004459 // [...] and any given function template specialization F1 is
4460 // eliminated if the set contains a second function template
4461 // specialization whose function template is more specialized
4462 // than the function template of F1 according to the partial
4463 // ordering rules of 14.5.5.2.
4464
4465 // The algorithm specified above is quadratic. We instead use a
4466 // two-pass algorithm (similar to the one used to identify the
4467 // best viable function in an overload set) that identifies the
4468 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004469 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004470 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004471 FunctionDecl *Result =
4472 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4473 TPOC_Other, From->getLocStart(),
4474 PDiag(),
4475 PDiag(diag::err_addr_ovl_ambiguous)
4476 << TemplateMatches[0]->getDeclName(),
4477 PDiag(diag::err_ovl_template_candidate));
4478 MarkDeclarationReferenced(From->getLocStart(), Result);
4479 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004480 }
Mike Stump11289f42009-09-09 15:08:12 +00004481
Douglas Gregorfae1d712009-09-26 03:56:17 +00004482 // [...] any function template specializations in the set are
4483 // eliminated if the set also contains a non-template function, [...]
4484 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4485 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4486 if ((*M)->getPrimaryTemplate() == 0)
4487 RemainingMatches.push_back(*M);
4488
Mike Stump11289f42009-09-09 15:08:12 +00004489 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004490 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004491 if (RemainingMatches.size() == 1) {
4492 FunctionDecl *Result = RemainingMatches.front();
4493 MarkDeclarationReferenced(From->getLocStart(), Result);
4494 return Result;
4495 }
Mike Stump11289f42009-09-09 15:08:12 +00004496
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004497 // FIXME: We should probably return the same thing that BestViableFunction
4498 // returns (even if we issue the diagnostics here).
4499 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4500 << RemainingMatches[0]->getDeclName();
4501 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4502 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004503 return 0;
4504}
4505
Douglas Gregorcabea402009-09-22 15:41:20 +00004506/// \brief Add a single candidate to the overload set.
4507static void AddOverloadedCallCandidate(Sema &S,
4508 AnyFunctionDecl Callee,
4509 bool &ArgumentDependentLookup,
4510 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004511 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004512 unsigned NumExplicitTemplateArgs,
4513 Expr **Args, unsigned NumArgs,
4514 OverloadCandidateSet &CandidateSet,
4515 bool PartialOverloading) {
4516 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4517 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4518 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4519 PartialOverloading);
4520
4521 if (Func->getDeclContext()->isRecord() ||
4522 Func->getDeclContext()->isFunctionOrMethod())
4523 ArgumentDependentLookup = false;
4524 return;
4525 }
4526
4527 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4528 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4529 ExplicitTemplateArgs,
4530 NumExplicitTemplateArgs,
4531 Args, NumArgs, CandidateSet);
4532
4533 if (FuncTemplate->getDeclContext()->isRecord())
4534 ArgumentDependentLookup = false;
4535}
4536
4537/// \brief Add the overload candidates named by callee and/or found by argument
4538/// dependent lookup to the given overload set.
4539void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4540 DeclarationName &UnqualifiedName,
4541 bool &ArgumentDependentLookup,
4542 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004543 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004544 unsigned NumExplicitTemplateArgs,
4545 Expr **Args, unsigned NumArgs,
4546 OverloadCandidateSet &CandidateSet,
4547 bool PartialOverloading) {
4548 // Add the functions denoted by Callee to the set of candidate
4549 // functions. While we're doing so, track whether argument-dependent
4550 // lookup still applies, per:
4551 //
4552 // C++0x [basic.lookup.argdep]p3:
4553 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4554 // and let Y be the lookup set produced by argument dependent
4555 // lookup (defined as follows). If X contains
4556 //
4557 // -- a declaration of a class member, or
4558 //
4559 // -- a block-scope function declaration that is not a
4560 // using-declaration (FIXME: check for using declaration), or
4561 //
4562 // -- a declaration that is neither a function or a function
4563 // template
4564 //
4565 // then Y is empty.
4566 if (!Callee) {
4567 // Nothing to do.
4568 } else if (OverloadedFunctionDecl *Ovl
4569 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4570 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4571 FuncEnd = Ovl->function_end();
4572 Func != FuncEnd; ++Func)
4573 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4574 HasExplicitTemplateArgs,
4575 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4576 Args, NumArgs, CandidateSet,
4577 PartialOverloading);
4578 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4579 AddOverloadedCallCandidate(*this,
4580 AnyFunctionDecl::getFromNamedDecl(Callee),
4581 ArgumentDependentLookup,
4582 HasExplicitTemplateArgs,
4583 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4584 Args, NumArgs, CandidateSet,
4585 PartialOverloading);
4586 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4587 // checking dynamically.
4588
4589 if (Callee)
4590 UnqualifiedName = Callee->getDeclName();
4591
4592 if (ArgumentDependentLookup)
4593 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4594 HasExplicitTemplateArgs,
4595 ExplicitTemplateArgs,
4596 NumExplicitTemplateArgs,
4597 CandidateSet,
4598 PartialOverloading);
4599}
4600
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004601/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004602/// (which eventually refers to the declaration Func) and the call
4603/// arguments Args/NumArgs, attempt to resolve the function call down
4604/// to a specific function. If overload resolution succeeds, returns
4605/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004606/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004607/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004608FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004609 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004610 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004611 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004612 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004613 SourceLocation LParenLoc,
4614 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004615 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004616 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004617 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004618 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004619
4620 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004621 // functions.
4622 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4623 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4624 NumExplicitTemplateArgs, Args, NumArgs,
4625 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004626 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004627 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004628 case OR_Success:
4629 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004630
4631 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004632 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004633 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004634 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004635 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4636 break;
4637
4638 case OR_Ambiguous:
4639 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004640 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004641 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4642 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004643
4644 case OR_Deleted:
4645 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4646 << Best->Function->isDeleted()
4647 << UnqualifiedName
4648 << Fn->getSourceRange();
4649 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4650 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004651 }
4652
4653 // Overload resolution failed. Destroy all of the subexpressions and
4654 // return NULL.
4655 Fn->Destroy(Context);
4656 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4657 Args[Arg]->Destroy(Context);
4658 return 0;
4659}
4660
Douglas Gregor084d8552009-03-13 23:49:33 +00004661/// \brief Create a unary operation that may resolve to an overloaded
4662/// operator.
4663///
4664/// \param OpLoc The location of the operator itself (e.g., '*').
4665///
4666/// \param OpcIn The UnaryOperator::Opcode that describes this
4667/// operator.
4668///
4669/// \param Functions The set of non-member functions that will be
4670/// considered by overload resolution. The caller needs to build this
4671/// set based on the context using, e.g.,
4672/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4673/// set should not contain any member functions; those will be added
4674/// by CreateOverloadedUnaryOp().
4675///
4676/// \param input The input argument.
4677Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4678 unsigned OpcIn,
4679 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004680 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004681 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4682 Expr *Input = (Expr *)input.get();
4683
4684 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4685 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4686 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4687
4688 Expr *Args[2] = { Input, 0 };
4689 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004690
Douglas Gregor084d8552009-03-13 23:49:33 +00004691 // For post-increment and post-decrement, add the implicit '0' as
4692 // the second argument, so that we know this is a post-increment or
4693 // post-decrement.
4694 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4695 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004696 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004697 SourceLocation());
4698 NumArgs = 2;
4699 }
4700
4701 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004702 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004703 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004704 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004705 FuncEnd = Functions.end();
4706 Func != FuncEnd; ++Func)
4707 Overloads->addOverload(*Func);
4708
4709 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4710 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004711
Douglas Gregor084d8552009-03-13 23:49:33 +00004712 input.release();
4713 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4714 &Args[0], NumArgs,
4715 Context.DependentTy,
4716 OpLoc));
4717 }
4718
4719 // Build an empty overload set.
4720 OverloadCandidateSet CandidateSet;
4721
4722 // Add the candidates from the given function set.
4723 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4724
4725 // Add operator candidates that are member functions.
4726 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4727
4728 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004729 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004730
4731 // Perform overload resolution.
4732 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004733 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004734 case OR_Success: {
4735 // We found a built-in operator or an overloaded operator.
4736 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004737
Douglas Gregor084d8552009-03-13 23:49:33 +00004738 if (FnDecl) {
4739 // We matched an overloaded operator. Build a call to that
4740 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004741
Douglas Gregor084d8552009-03-13 23:49:33 +00004742 // Convert the arguments.
4743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4744 if (PerformObjectArgumentInitialization(Input, Method))
4745 return ExprError();
4746 } else {
4747 // Convert the arguments.
4748 if (PerformCopyInitialization(Input,
4749 FnDecl->getParamDecl(0)->getType(),
4750 "passing"))
4751 return ExprError();
4752 }
4753
4754 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004755 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004756
Douglas Gregor084d8552009-03-13 23:49:33 +00004757 // Build the actual expression node.
4758 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4759 SourceLocation());
4760 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004761
Douglas Gregor084d8552009-03-13 23:49:33 +00004762 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004763 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004764 ExprOwningPtr<CallExpr> TheCall(this,
4765 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004766 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004767
4768 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4769 FnDecl))
4770 return ExprError();
4771
4772 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004773 } else {
4774 // We matched a built-in operator. Convert the arguments, then
4775 // break out so that we will build the appropriate built-in
4776 // operator node.
4777 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4778 Best->Conversions[0], "passing"))
4779 return ExprError();
4780
4781 break;
4782 }
4783 }
4784
4785 case OR_No_Viable_Function:
4786 // No viable function; fall through to handling this as a
4787 // built-in operator, which will produce an error message for us.
4788 break;
4789
4790 case OR_Ambiguous:
4791 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4792 << UnaryOperator::getOpcodeStr(Opc)
4793 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004794 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4795 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004796 return ExprError();
4797
4798 case OR_Deleted:
4799 Diag(OpLoc, diag::err_ovl_deleted_oper)
4800 << Best->Function->isDeleted()
4801 << UnaryOperator::getOpcodeStr(Opc)
4802 << Input->getSourceRange();
4803 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4804 return ExprError();
4805 }
4806
4807 // Either we found no viable overloaded operator or we matched a
4808 // built-in operator. In either case, fall through to trying to
4809 // build a built-in operation.
4810 input.release();
4811 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4812}
4813
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004814/// \brief Create a binary operation that may resolve to an overloaded
4815/// operator.
4816///
4817/// \param OpLoc The location of the operator itself (e.g., '+').
4818///
4819/// \param OpcIn The BinaryOperator::Opcode that describes this
4820/// operator.
4821///
4822/// \param Functions The set of non-member functions that will be
4823/// considered by overload resolution. The caller needs to build this
4824/// set based on the context using, e.g.,
4825/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4826/// set should not contain any member functions; those will be added
4827/// by CreateOverloadedBinOp().
4828///
4829/// \param LHS Left-hand argument.
4830/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004831Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004832Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004833 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004834 FunctionSet &Functions,
4835 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004836 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004837 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004838
4839 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4840 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4841 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4842
4843 // If either side is type-dependent, create an appropriate dependent
4844 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004845 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004846 if (Functions.empty()) {
4847 // If there are no functions to store, just build a dependent
4848 // BinaryOperator or CompoundAssignment.
4849 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4850 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4851 Context.DependentTy, OpLoc));
4852
4853 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4854 Context.DependentTy,
4855 Context.DependentTy,
4856 Context.DependentTy,
4857 OpLoc));
4858 }
4859
Mike Stump11289f42009-09-09 15:08:12 +00004860 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004861 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004862 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004863 FuncEnd = Functions.end();
4864 Func != FuncEnd; ++Func)
4865 Overloads->addOverload(*Func);
4866
4867 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4868 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004869
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004870 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004871 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004872 Context.DependentTy,
4873 OpLoc));
4874 }
4875
4876 // If this is the .* operator, which is not overloadable, just
4877 // create a built-in binary operator.
4878 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004879 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004880
4881 // If this is one of the assignment operators, we only perform
4882 // overload resolution if the left-hand side is a class or
4883 // enumeration type (C++ [expr.ass]p3).
4884 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004885 !Args[0]->getType()->isOverloadableType())
4886 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004887
Douglas Gregor084d8552009-03-13 23:49:33 +00004888 // Build an empty overload set.
4889 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004890
4891 // Add the candidates from the given function set.
4892 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4893
4894 // Add operator candidates that are member functions.
4895 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4896
4897 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004898 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004899
4900 // Perform overload resolution.
4901 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004902 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004903 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004904 // We found a built-in operator or an overloaded operator.
4905 FunctionDecl *FnDecl = Best->Function;
4906
4907 if (FnDecl) {
4908 // We matched an overloaded operator. Build a call to that
4909 // operator.
4910
4911 // Convert the arguments.
4912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004913 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4914 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004915 "passing"))
4916 return ExprError();
4917 } else {
4918 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004919 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004920 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004921 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004922 "passing"))
4923 return ExprError();
4924 }
4925
4926 // Determine the result type
4927 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004928 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004929 ResultTy = ResultTy.getNonReferenceType();
4930
4931 // Build the actual expression node.
4932 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004933 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004934 UsualUnaryConversions(FnExpr);
4935
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004936 ExprOwningPtr<CXXOperatorCallExpr>
4937 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4938 Args, 2, ResultTy,
4939 OpLoc));
4940
4941 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4942 FnDecl))
4943 return ExprError();
4944
4945 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004946 } else {
4947 // We matched a built-in operator. Convert the arguments, then
4948 // break out so that we will build the appropriate built-in
4949 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004950 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004951 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004952 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004953 Best->Conversions[1], "passing"))
4954 return ExprError();
4955
4956 break;
4957 }
4958 }
4959
Douglas Gregor66950a32009-09-30 21:46:01 +00004960 case OR_No_Viable_Function: {
4961 // C++ [over.match.oper]p9:
4962 // If the operator is the operator , [...] and there are no
4963 // viable functions, then the operator is assumed to be the
4964 // built-in operator and interpreted according to clause 5.
4965 if (Opc == BinaryOperator::Comma)
4966 break;
4967
Sebastian Redl027de2a2009-05-21 11:50:50 +00004968 // For class as left operand for assignment or compound assigment operator
4969 // do not fall through to handling in built-in, but report that no overloaded
4970 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004971 OwningExprResult Result = ExprError();
4972 if (Args[0]->getType()->isRecordType() &&
4973 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004974 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4975 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004976 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004977 } else {
4978 // No viable function; try to create a built-in operation, which will
4979 // produce an error. Then, show the non-viable candidates.
4980 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004981 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004982 assert(Result.isInvalid() &&
4983 "C++ binary operator overloading is missing candidates!");
4984 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004985 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4986 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004987 return move(Result);
4988 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004989
4990 case OR_Ambiguous:
4991 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4992 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004993 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004994 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4995 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004996 return ExprError();
4997
4998 case OR_Deleted:
4999 Diag(OpLoc, diag::err_ovl_deleted_oper)
5000 << Best->Function->isDeleted()
5001 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005002 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005003 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5004 return ExprError();
5005 }
5006
Douglas Gregor66950a32009-09-30 21:46:01 +00005007 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005008 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005009}
5010
Sebastian Redladba46e2009-10-29 20:17:01 +00005011Action::OwningExprResult
5012Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5013 SourceLocation RLoc,
5014 ExprArg Base, ExprArg Idx) {
5015 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5016 static_cast<Expr*>(Idx.get()) };
5017 DeclarationName OpName =
5018 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5019
5020 // If either side is type-dependent, create an appropriate dependent
5021 // expression.
5022 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5023
5024 OverloadedFunctionDecl *Overloads
5025 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
5026
5027 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
5028 LLoc, false, false);
5029
5030 Base.release();
5031 Idx.release();
5032 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5033 Args, 2,
5034 Context.DependentTy,
5035 RLoc));
5036 }
5037
5038 // Build an empty overload set.
5039 OverloadCandidateSet CandidateSet;
5040
5041 // Subscript can only be overloaded as a member function.
5042
5043 // Add operator candidates that are member functions.
5044 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5045
5046 // Add builtin operator candidates.
5047 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5048
5049 // Perform overload resolution.
5050 OverloadCandidateSet::iterator Best;
5051 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5052 case OR_Success: {
5053 // We found a built-in operator or an overloaded operator.
5054 FunctionDecl *FnDecl = Best->Function;
5055
5056 if (FnDecl) {
5057 // We matched an overloaded operator. Build a call to that
5058 // operator.
5059
5060 // Convert the arguments.
5061 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5062 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5063 PerformCopyInitialization(Args[1],
5064 FnDecl->getParamDecl(0)->getType(),
5065 "passing"))
5066 return ExprError();
5067
5068 // Determine the result type
5069 QualType ResultTy
5070 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5071 ResultTy = ResultTy.getNonReferenceType();
5072
5073 // Build the actual expression node.
5074 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5075 LLoc);
5076 UsualUnaryConversions(FnExpr);
5077
5078 Base.release();
5079 Idx.release();
5080 ExprOwningPtr<CXXOperatorCallExpr>
5081 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5082 FnExpr, Args, 2,
5083 ResultTy, RLoc));
5084
5085 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5086 FnDecl))
5087 return ExprError();
5088
5089 return MaybeBindToTemporary(TheCall.release());
5090 } else {
5091 // We matched a built-in operator. Convert the arguments, then
5092 // break out so that we will build the appropriate built-in
5093 // operator node.
5094 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5095 Best->Conversions[0], "passing") ||
5096 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5097 Best->Conversions[1], "passing"))
5098 return ExprError();
5099
5100 break;
5101 }
5102 }
5103
5104 case OR_No_Viable_Function: {
5105 // No viable function; try to create a built-in operation, which will
5106 // produce an error. Then, show the non-viable candidates.
5107 OwningExprResult Result =
5108 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5109 assert(Result.isInvalid() &&
5110 "C++ subscript operator overloading is missing candidates!");
5111 if (Result.isInvalid())
5112 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5113 "[]", LLoc);
5114 return move(Result);
5115 }
5116
5117 case OR_Ambiguous:
5118 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5119 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5120 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5121 "[]", LLoc);
5122 return ExprError();
5123
5124 case OR_Deleted:
5125 Diag(LLoc, diag::err_ovl_deleted_oper)
5126 << Best->Function->isDeleted() << "[]"
5127 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5128 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5129 return ExprError();
5130 }
5131
5132 // We matched a built-in operator; build it.
5133 Base.release();
5134 Idx.release();
5135 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5136 Owned(Args[1]), RLoc);
5137}
5138
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005139/// BuildCallToMemberFunction - Build a call to a member
5140/// function. MemExpr is the expression that refers to the member
5141/// function (and includes the object parameter), Args/NumArgs are the
5142/// arguments to the function call (not including the object
5143/// parameter). The caller needs to validate that the member
5144/// expression refers to a member function or an overloaded member
5145/// function.
5146Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005147Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5148 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005149 unsigned NumArgs, SourceLocation *CommaLocs,
5150 SourceLocation RParenLoc) {
5151 // Dig out the member expression. This holds both the object
5152 // argument and the member function we're referring to.
5153 MemberExpr *MemExpr = 0;
5154 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5155 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5156 else
5157 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5158 assert(MemExpr && "Building member call without member expression");
5159
5160 // Extract the object argument.
5161 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005162
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005163 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00005164 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5165 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005166 // Add overload candidates
5167 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00005168 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005169
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005170 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5171 Func != FuncEnd; ++Func) {
Douglas Gregord3319842009-10-24 04:59:53 +00005172 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5173 // If explicit template arguments were provided, we can't call a
5174 // non-template member function.
5175 if (MemExpr->hasExplicitTemplateArgumentList())
5176 continue;
5177
Mike Stump11289f42009-09-09 15:08:12 +00005178 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005179 /*SuppressUserConversions=*/false);
Douglas Gregord3319842009-10-24 04:59:53 +00005180 } else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005181 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5182 MemExpr->hasExplicitTemplateArgumentList(),
5183 MemExpr->getTemplateArgs(),
5184 MemExpr->getNumTemplateArgs(),
5185 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005186 CandidateSet,
5187 /*SuppressUsedConversions=*/false);
5188 }
Mike Stump11289f42009-09-09 15:08:12 +00005189
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005190 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005191 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005192 case OR_Success:
5193 Method = cast<CXXMethodDecl>(Best->Function);
5194 break;
5195
5196 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005197 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005198 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005199 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005200 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5201 // FIXME: Leaking incoming expressions!
5202 return true;
5203
5204 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00005205 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005206 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005207 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005208 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5209 // FIXME: Leaking incoming expressions!
5210 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005211
5212 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00005213 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00005214 diag::err_ovl_deleted_member_call)
5215 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005216 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005217 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5218 // FIXME: Leaking incoming expressions!
5219 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005220 }
5221
5222 FixOverloadedFunctionReference(MemExpr, Method);
5223 } else {
5224 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5225 }
5226
5227 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005228 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005229 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005230 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005231 Method->getResultType().getNonReferenceType(),
5232 RParenLoc));
5233
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005234 // Check for a valid return type.
5235 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5236 TheCall.get(), Method))
5237 return true;
5238
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005239 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00005240 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005241 PerformObjectArgumentInitialization(ObjectArg, Method))
5242 return true;
5243 MemExpr->setBase(ObjectArg);
5244
5245 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005246 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005247 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005248 RParenLoc))
5249 return true;
5250
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005251 if (CheckFunctionCall(Method, TheCall.get()))
5252 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00005253
5254 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005255}
5256
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005257/// BuildCallToObjectOfClassType - Build a call to an object of class
5258/// type (C++ [over.call.object]), which can end up invoking an
5259/// overloaded function call operator (@c operator()) or performing a
5260/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005261Sema::ExprResult
5262Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005263 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005264 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005265 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005266 SourceLocation RParenLoc) {
5267 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005268 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005269
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005270 // C++ [over.call.object]p1:
5271 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005272 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005273 // candidate functions includes at least the function call
5274 // operators of T. The function call operators of T are obtained by
5275 // ordinary lookup of the name operator() in the context of
5276 // (E).operator().
5277 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005278 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005279
5280 if (RequireCompleteType(LParenLoc, Object->getType(),
5281 PartialDiagnostic(diag::err_incomplete_object_call)
5282 << Object->getSourceRange()))
5283 return true;
5284
John McCall27b18f82009-11-17 02:14:36 +00005285 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5286 LookupQualifiedName(R, Record->getDecl());
5287 R.suppressDiagnostics();
5288
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005289 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005290 Oper != OperEnd; ++Oper) {
John McCallf0f1cf02009-11-17 07:50:12 +00005291 AddMethodCandidate(*Oper, Object, Args, NumArgs, CandidateSet,
5292 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005293 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005294
Douglas Gregorab7897a2008-11-19 22:57:39 +00005295 // C++ [over.call.object]p2:
5296 // In addition, for each conversion function declared in T of the
5297 // form
5298 //
5299 // operator conversion-type-id () cv-qualifier;
5300 //
5301 // where cv-qualifier is the same cv-qualification as, or a
5302 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005303 // denotes the type "pointer to function of (P1,...,Pn) returning
5304 // R", or the type "reference to pointer to function of
5305 // (P1,...,Pn) returning R", or the type "reference to function
5306 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005307 // is also considered as a candidate function. Similarly,
5308 // surrogate call functions are added to the set of candidate
5309 // functions for each conversion function declared in an
5310 // accessible base class provided the function is not hidden
5311 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005312 // FIXME: Look in base classes for more conversion operators!
5313 OverloadedFunctionDecl *Conversions
5314 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5315 for (OverloadedFunctionDecl::function_iterator
5316 Func = Conversions->function_begin(),
5317 FuncEnd = Conversions->function_end();
5318 Func != FuncEnd; ++Func) {
5319 CXXConversionDecl *Conv;
5320 FunctionTemplateDecl *ConvTemplate;
5321 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Mike Stump11289f42009-09-09 15:08:12 +00005322
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005323 // Skip over templated conversion functions; they aren't
5324 // surrogates.
5325 if (ConvTemplate)
5326 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005327
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005328 // Strip the reference type (if any) and then the pointer type (if
5329 // any) to get down to what might be a function type.
5330 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5331 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5332 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005333
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005334 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5335 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005336 }
Mike Stump11289f42009-09-09 15:08:12 +00005337
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005338 // Perform overload resolution.
5339 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005340 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005341 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005342 // Overload resolution succeeded; we'll build the appropriate call
5343 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005344 break;
5345
5346 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005347 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005348 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005349 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005350 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005351 break;
5352
5353 case OR_Ambiguous:
5354 Diag(Object->getSourceRange().getBegin(),
5355 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005356 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005357 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5358 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005359
5360 case OR_Deleted:
5361 Diag(Object->getSourceRange().getBegin(),
5362 diag::err_ovl_deleted_object_call)
5363 << Best->Function->isDeleted()
5364 << Object->getType() << Object->getSourceRange();
5365 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5366 break;
Mike Stump11289f42009-09-09 15:08:12 +00005367 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005368
Douglas Gregorab7897a2008-11-19 22:57:39 +00005369 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005370 // We had an error; delete all of the subexpressions and return
5371 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005372 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005373 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005374 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005375 return true;
5376 }
5377
Douglas Gregorab7897a2008-11-19 22:57:39 +00005378 if (Best->Function == 0) {
5379 // Since there is no function declaration, this is one of the
5380 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005381 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005382 = cast<CXXConversionDecl>(
5383 Best->Conversions[0].UserDefined.ConversionFunction);
5384
5385 // We selected one of the surrogate functions that converts the
5386 // object parameter to a function pointer. Perform the conversion
5387 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005388
5389 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005390 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005391 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005392 BuildCXXMemberCallExpr(Object, Conv);
5393
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005394 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005395 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5396 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005397 }
5398
5399 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5400 // that calls this method, using Object for the implicit object
5401 // parameter and passing along the remaining arguments.
5402 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005403 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005404
5405 unsigned NumArgsInProto = Proto->getNumArgs();
5406 unsigned NumArgsToCheck = NumArgs;
5407
5408 // Build the full argument list for the method call (the
5409 // implicit object parameter is placed at the beginning of the
5410 // list).
5411 Expr **MethodArgs;
5412 if (NumArgs < NumArgsInProto) {
5413 NumArgsToCheck = NumArgsInProto;
5414 MethodArgs = new Expr*[NumArgsInProto + 1];
5415 } else {
5416 MethodArgs = new Expr*[NumArgs + 1];
5417 }
5418 MethodArgs[0] = Object;
5419 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5420 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005421
5422 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005423 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005424 UsualUnaryConversions(NewFn);
5425
5426 // Once we've built TheCall, all of the expressions are properly
5427 // owned.
5428 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005429 ExprOwningPtr<CXXOperatorCallExpr>
5430 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005431 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005432 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005433 delete [] MethodArgs;
5434
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005435 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5436 Method))
5437 return true;
5438
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005439 // We may have default arguments. If so, we need to allocate more
5440 // slots in the call for them.
5441 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005442 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005443 else if (NumArgs > NumArgsInProto)
5444 NumArgsToCheck = NumArgsInProto;
5445
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005446 bool IsError = false;
5447
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005448 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005449 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005450 TheCall->setArg(0, Object);
5451
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005452
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005453 // Check the argument types.
5454 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005455 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005456 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005457 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005458
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005459 // Pass the argument.
5460 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005461 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005462 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005463 OwningExprResult DefArg
5464 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5465 if (DefArg.isInvalid()) {
5466 IsError = true;
5467 break;
5468 }
5469
5470 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005471 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005472
5473 TheCall->setArg(i + 1, Arg);
5474 }
5475
5476 // If this is a variadic call, handle args passed through "...".
5477 if (Proto->isVariadic()) {
5478 // Promote the arguments (C99 6.5.2.2p7).
5479 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5480 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005481 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005482 TheCall->setArg(i + 1, Arg);
5483 }
5484 }
5485
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005486 if (IsError) return true;
5487
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005488 if (CheckFunctionCall(Method, TheCall.get()))
5489 return true;
5490
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005491 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005492}
5493
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005494/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005495/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005496/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005497Sema::OwningExprResult
5498Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5499 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005500 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005501
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005502 // C++ [over.ref]p1:
5503 //
5504 // [...] An expression x->m is interpreted as (x.operator->())->m
5505 // for a class object x of type T if T::operator->() exists and if
5506 // the operator is selected as the best match function by the
5507 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005508 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5509 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005510 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005511
Eli Friedman132e70b2009-11-18 01:28:03 +00005512 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5513 PDiag(diag::err_typecheck_incomplete_tag)
5514 << Base->getSourceRange()))
5515 return ExprError();
5516
John McCall27b18f82009-11-17 02:14:36 +00005517 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5518 LookupQualifiedName(R, BaseRecord->getDecl());
5519 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005520
5521 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5522 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005523 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005524 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005525
5526 // Perform overload resolution.
5527 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005528 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005529 case OR_Success:
5530 // Overload resolution succeeded; we'll build the call below.
5531 break;
5532
5533 case OR_No_Viable_Function:
5534 if (CandidateSet.empty())
5535 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005536 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005537 else
5538 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005539 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005540 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005541 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005542
5543 case OR_Ambiguous:
5544 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005545 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005546 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005547 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005548
5549 case OR_Deleted:
5550 Diag(OpLoc, diag::err_ovl_deleted_oper)
5551 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005552 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005553 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005554 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005555 }
5556
5557 // Convert the object parameter.
5558 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005559 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005560 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005561
5562 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005563 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005564
5565 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005566 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5567 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005568 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005569
5570 QualType ResultTy = Method->getResultType().getNonReferenceType();
5571 ExprOwningPtr<CXXOperatorCallExpr>
5572 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5573 &Base, 1, ResultTy, OpLoc));
5574
5575 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5576 Method))
5577 return ExprError();
5578 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005579}
5580
Douglas Gregorcd695e52008-11-10 20:40:00 +00005581/// FixOverloadedFunctionReference - E is an expression that refers to
5582/// a C++ overloaded function (possibly with some parentheses and
5583/// perhaps a '&' around it). We have resolved the overloaded function
5584/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005585/// refer (possibly indirectly) to Fn. Returns the new expr.
5586Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005587 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005588 Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005589 PE->setSubExpr(NewExpr);
5590 PE->setType(NewExpr->getType());
5591 } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5592 Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5593 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5594 NewExpr->getType()) &&
5595 "Implicit cast type cannot be determined from overload");
5596 ICE->setSubExpr(NewExpr);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005597 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005598 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005599 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005600 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5601 if (Method->isStatic()) {
5602 // Do nothing: static member functions aren't any different
5603 // from non-member functions.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005604 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5605 if (DRE->getQualifier()) {
5606 // We have taken the address of a pointer to member
5607 // function. Perform the computation here so that we get the
5608 // appropriate pointer to member type.
5609 DRE->setDecl(Fn);
5610 DRE->setType(Fn->getType());
5611 QualType ClassType
5612 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5613 E->setType(Context.getMemberPointerType(Fn->getType(),
5614 ClassType.getTypePtr()));
5615 return E;
5616 }
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005617 }
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005618 // FIXME: TemplateIdRefExpr referring to a member function template
5619 // specialization!
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005620 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005621 Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5622 UnOp->setSubExpr(NewExpr);
5623 UnOp->setType(Context.getPointerType(NewExpr->getType()));
5624
5625 return UnOp;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005626 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005627 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Douglas Gregor091f0422009-10-23 22:18:25 +00005628 isa<FunctionTemplateDecl>(DR->getDecl()) ||
5629 isa<FunctionDecl>(DR->getDecl())) &&
5630 "Expected function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005631 DR->setDecl(Fn);
5632 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005633 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5634 MemExpr->setMemberDecl(Fn);
5635 E->setType(Fn->getType());
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005636 } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005637 E = DeclRefExpr::Create(Context,
5638 TID->getQualifier(), TID->getQualifierRange(),
5639 Fn, TID->getTemplateNameLoc(),
5640 true,
5641 TID->getLAngleLoc(),
5642 TID->getTemplateArgs(),
5643 TID->getNumTemplateArgs(),
5644 TID->getRAngleLoc(),
5645 Fn->getType(),
5646 /*FIXME?*/false, /*FIXME?*/false);
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005647
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005648 // FIXME: Don't destroy TID here, since we need its template arguments
5649 // to survive.
5650 // TID->Destroy(Context);
Douglas Gregor091f0422009-10-23 22:18:25 +00005651 } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5652 return DeclRefExpr::Create(Context,
5653 /*Qualifier=*/0,
5654 /*QualifierRange=*/SourceRange(),
5655 Fn, E->getLocStart(),
5656 Fn->getType(), false, false);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005657 } else {
5658 assert(false && "Invalid reference to overloaded function");
5659 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005660
5661 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005662}
5663
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005664} // end namespace clang